[POWERPC] Implement generic time of day clocksource for powerpc
[linux-2.6/sactl.git] / arch / powerpc / kernel / time.c
blobe71a0d8c597ab38fd27cfc21362ea7ff13592ed6
1 /*
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. (for iSeries, we calibrate the timebase
21 * against the Titan chip's clock.)
22 * - for astronomical applications: add a new function to get
23 * non ambiguous timestamps even around leap seconds. This needs
24 * a new timestamp format and a good name.
26 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
27 * "A Kernel Model for Precision Timekeeping" by Dave Mills
29 * This program is free software; you can redistribute it and/or
30 * modify it under the terms of the GNU General Public License
31 * as published by the Free Software Foundation; either version
32 * 2 of the License, or (at your option) any later version.
35 #include <linux/errno.h>
36 #include <linux/module.h>
37 #include <linux/sched.h>
38 #include <linux/kernel.h>
39 #include <linux/param.h>
40 #include <linux/string.h>
41 #include <linux/mm.h>
42 #include <linux/interrupt.h>
43 #include <linux/timex.h>
44 #include <linux/kernel_stat.h>
45 #include <linux/time.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>
56 #include <asm/io.h>
57 #include <asm/processor.h>
58 #include <asm/nvram.h>
59 #include <asm/cache.h>
60 #include <asm/machdep.h>
61 #include <asm/uaccess.h>
62 #include <asm/time.h>
63 #include <asm/prom.h>
64 #include <asm/irq.h>
65 #include <asm/div64.h>
66 #include <asm/smp.h>
67 #include <asm/vdso_datapage.h>
68 #include <asm/firmware.h>
69 #ifdef CONFIG_PPC_ISERIES
70 #include <asm/iseries/it_lp_queue.h>
71 #include <asm/iseries/hv_call_xm.h>
72 #endif
74 /* powerpc clocksource/clockevent code */
76 #include <linux/clocksource.h>
78 static cycle_t rtc_read(void);
79 static struct clocksource clocksource_rtc = {
80 .name = "rtc",
81 .rating = 400,
82 .flags = CLOCK_SOURCE_IS_CONTINUOUS,
83 .mask = CLOCKSOURCE_MASK(64),
84 .shift = 22,
85 .mult = 0, /* To be filled in */
86 .read = rtc_read,
89 static cycle_t timebase_read(void);
90 static struct clocksource clocksource_timebase = {
91 .name = "timebase",
92 .rating = 400,
93 .flags = CLOCK_SOURCE_IS_CONTINUOUS,
94 .mask = CLOCKSOURCE_MASK(64),
95 .shift = 22,
96 .mult = 0, /* To be filled in */
97 .read = timebase_read,
100 #ifdef CONFIG_PPC_ISERIES
101 static unsigned long __initdata iSeries_recal_titan;
102 static signed long __initdata iSeries_recal_tb;
104 /* Forward declaration is only needed for iSereis compiles */
105 void __init clocksource_init(void);
106 #endif
108 #define XSEC_PER_SEC (1024*1024)
110 #ifdef CONFIG_PPC64
111 #define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
112 #else
113 /* compute ((xsec << 12) * max) >> 32 */
114 #define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
115 #endif
117 unsigned long tb_ticks_per_jiffy;
118 unsigned long tb_ticks_per_usec = 100; /* sane default */
119 EXPORT_SYMBOL(tb_ticks_per_usec);
120 unsigned long tb_ticks_per_sec;
121 EXPORT_SYMBOL(tb_ticks_per_sec); /* for cputime_t conversions */
122 u64 tb_to_xs;
123 unsigned tb_to_us;
125 #define TICKLEN_SCALE TICK_LENGTH_SHIFT
126 u64 last_tick_len; /* units are ns / 2^TICKLEN_SCALE */
127 u64 ticklen_to_xs; /* 0.64 fraction */
129 /* If last_tick_len corresponds to about 1/HZ seconds, then
130 last_tick_len << TICKLEN_SHIFT will be about 2^63. */
131 #define TICKLEN_SHIFT (63 - 30 - TICKLEN_SCALE + SHIFT_HZ)
133 DEFINE_SPINLOCK(rtc_lock);
134 EXPORT_SYMBOL_GPL(rtc_lock);
136 static u64 tb_to_ns_scale __read_mostly;
137 static unsigned tb_to_ns_shift __read_mostly;
138 static unsigned long boot_tb __read_mostly;
140 struct gettimeofday_struct do_gtod;
142 extern struct timezone sys_tz;
143 static long timezone_offset;
145 unsigned long ppc_proc_freq;
146 EXPORT_SYMBOL(ppc_proc_freq);
147 unsigned long ppc_tb_freq;
149 static u64 tb_last_jiffy __cacheline_aligned_in_smp;
150 static DEFINE_PER_CPU(u64, last_jiffy);
152 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
154 * Factors for converting from cputime_t (timebase ticks) to
155 * jiffies, milliseconds, seconds, and clock_t (1/USER_HZ seconds).
156 * These are all stored as 0.64 fixed-point binary fractions.
158 u64 __cputime_jiffies_factor;
159 EXPORT_SYMBOL(__cputime_jiffies_factor);
160 u64 __cputime_msec_factor;
161 EXPORT_SYMBOL(__cputime_msec_factor);
162 u64 __cputime_sec_factor;
163 EXPORT_SYMBOL(__cputime_sec_factor);
164 u64 __cputime_clockt_factor;
165 EXPORT_SYMBOL(__cputime_clockt_factor);
167 static void calc_cputime_factors(void)
169 struct div_result res;
171 div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
172 __cputime_jiffies_factor = res.result_low;
173 div128_by_32(1000, 0, tb_ticks_per_sec, &res);
174 __cputime_msec_factor = res.result_low;
175 div128_by_32(1, 0, tb_ticks_per_sec, &res);
176 __cputime_sec_factor = res.result_low;
177 div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
178 __cputime_clockt_factor = res.result_low;
182 * Read the PURR on systems that have it, otherwise the timebase.
184 static u64 read_purr(void)
186 if (cpu_has_feature(CPU_FTR_PURR))
187 return mfspr(SPRN_PURR);
188 return mftb();
192 * Account time for a transition between system, hard irq
193 * or soft irq state.
195 void account_system_vtime(struct task_struct *tsk)
197 u64 now, delta;
198 unsigned long flags;
200 local_irq_save(flags);
201 now = read_purr();
202 delta = now - get_paca()->startpurr;
203 get_paca()->startpurr = now;
204 if (!in_interrupt()) {
205 delta += get_paca()->system_time;
206 get_paca()->system_time = 0;
208 account_system_time(tsk, 0, delta);
209 local_irq_restore(flags);
213 * Transfer the user and system times accumulated in the paca
214 * by the exception entry and exit code to the generic process
215 * user and system time records.
216 * Must be called with interrupts disabled.
218 void account_process_vtime(struct task_struct *tsk)
220 cputime_t utime;
222 utime = get_paca()->user_time;
223 get_paca()->user_time = 0;
224 account_user_time(tsk, utime);
227 static void account_process_time(struct pt_regs *regs)
229 int cpu = smp_processor_id();
231 account_process_vtime(current);
232 run_local_timers();
233 if (rcu_pending(cpu))
234 rcu_check_callbacks(cpu, user_mode(regs));
235 scheduler_tick();
236 run_posix_cpu_timers(current);
240 * Stuff for accounting stolen time.
242 struct cpu_purr_data {
243 int initialized; /* thread is running */
244 u64 tb; /* last TB value read */
245 u64 purr; /* last PURR value read */
249 * Each entry in the cpu_purr_data array is manipulated only by its
250 * "owner" cpu -- usually in the timer interrupt but also occasionally
251 * in process context for cpu online. As long as cpus do not touch
252 * each others' cpu_purr_data, disabling local interrupts is
253 * sufficient to serialize accesses.
255 static DEFINE_PER_CPU(struct cpu_purr_data, cpu_purr_data);
257 static void snapshot_tb_and_purr(void *data)
259 unsigned long flags;
260 struct cpu_purr_data *p = &__get_cpu_var(cpu_purr_data);
262 local_irq_save(flags);
263 p->tb = get_tb_or_rtc();
264 p->purr = mfspr(SPRN_PURR);
265 wmb();
266 p->initialized = 1;
267 local_irq_restore(flags);
271 * Called during boot when all cpus have come up.
273 void snapshot_timebases(void)
275 if (!cpu_has_feature(CPU_FTR_PURR))
276 return;
277 on_each_cpu(snapshot_tb_and_purr, NULL, 0, 1);
281 * Must be called with interrupts disabled.
283 void calculate_steal_time(void)
285 u64 tb, purr;
286 s64 stolen;
287 struct cpu_purr_data *pme;
289 if (!cpu_has_feature(CPU_FTR_PURR))
290 return;
291 pme = &per_cpu(cpu_purr_data, smp_processor_id());
292 if (!pme->initialized)
293 return; /* this can happen in early boot */
294 tb = mftb();
295 purr = mfspr(SPRN_PURR);
296 stolen = (tb - pme->tb) - (purr - pme->purr);
297 if (stolen > 0)
298 account_steal_time(current, stolen);
299 pme->tb = tb;
300 pme->purr = purr;
303 #ifdef CONFIG_PPC_SPLPAR
305 * Must be called before the cpu is added to the online map when
306 * a cpu is being brought up at runtime.
308 static void snapshot_purr(void)
310 struct cpu_purr_data *pme;
311 unsigned long flags;
313 if (!cpu_has_feature(CPU_FTR_PURR))
314 return;
315 local_irq_save(flags);
316 pme = &per_cpu(cpu_purr_data, smp_processor_id());
317 pme->tb = mftb();
318 pme->purr = mfspr(SPRN_PURR);
319 pme->initialized = 1;
320 local_irq_restore(flags);
323 #endif /* CONFIG_PPC_SPLPAR */
325 #else /* ! CONFIG_VIRT_CPU_ACCOUNTING */
326 #define calc_cputime_factors()
327 #define account_process_time(regs) update_process_times(user_mode(regs))
328 #define calculate_steal_time() do { } while (0)
329 #endif
331 #if !(defined(CONFIG_VIRT_CPU_ACCOUNTING) && defined(CONFIG_PPC_SPLPAR))
332 #define snapshot_purr() do { } while (0)
333 #endif
336 * Called when a cpu comes up after the system has finished booting,
337 * i.e. as a result of a hotplug cpu action.
339 void snapshot_timebase(void)
341 __get_cpu_var(last_jiffy) = get_tb_or_rtc();
342 snapshot_purr();
345 void __delay(unsigned long loops)
347 unsigned long start;
348 int diff;
350 if (__USE_RTC()) {
351 start = get_rtcl();
352 do {
353 /* the RTCL register wraps at 1000000000 */
354 diff = get_rtcl() - start;
355 if (diff < 0)
356 diff += 1000000000;
357 } while (diff < loops);
358 } else {
359 start = get_tbl();
360 while (get_tbl() - start < loops)
361 HMT_low();
362 HMT_medium();
365 EXPORT_SYMBOL(__delay);
367 void udelay(unsigned long usecs)
369 __delay(tb_ticks_per_usec * usecs);
371 EXPORT_SYMBOL(udelay);
375 * There are two copies of tb_to_xs and stamp_xsec so that no
376 * lock is needed to access and use these values in
377 * do_gettimeofday. We alternate the copies and as long as a
378 * reasonable time elapses between changes, there will never
379 * be inconsistent values. ntpd has a minimum of one minute
380 * between updates.
382 static inline void update_gtod(u64 new_tb_stamp, u64 new_stamp_xsec,
383 u64 new_tb_to_xs)
385 unsigned temp_idx;
386 struct gettimeofday_vars *temp_varp;
388 temp_idx = (do_gtod.var_idx == 0);
389 temp_varp = &do_gtod.vars[temp_idx];
391 temp_varp->tb_to_xs = new_tb_to_xs;
392 temp_varp->tb_orig_stamp = new_tb_stamp;
393 temp_varp->stamp_xsec = new_stamp_xsec;
394 smp_mb();
395 do_gtod.varp = temp_varp;
396 do_gtod.var_idx = temp_idx;
399 * tb_update_count is used to allow the userspace gettimeofday code
400 * to assure itself that it sees a consistent view of the tb_to_xs and
401 * stamp_xsec variables. It reads the tb_update_count, then reads
402 * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
403 * the two values of tb_update_count match and are even then the
404 * tb_to_xs and stamp_xsec values are consistent. If not, then it
405 * loops back and reads them again until this criteria is met.
406 * We expect the caller to have done the first increment of
407 * vdso_data->tb_update_count already.
409 vdso_data->tb_orig_stamp = new_tb_stamp;
410 vdso_data->stamp_xsec = new_stamp_xsec;
411 vdso_data->tb_to_xs = new_tb_to_xs;
412 vdso_data->wtom_clock_sec = wall_to_monotonic.tv_sec;
413 vdso_data->wtom_clock_nsec = wall_to_monotonic.tv_nsec;
414 smp_wmb();
415 ++(vdso_data->tb_update_count);
418 #ifdef CONFIG_SMP
419 unsigned long profile_pc(struct pt_regs *regs)
421 unsigned long pc = instruction_pointer(regs);
423 if (in_lock_functions(pc))
424 return regs->link;
426 return pc;
428 EXPORT_SYMBOL(profile_pc);
429 #endif
431 #ifdef CONFIG_PPC_ISERIES
434 * This function recalibrates the timebase based on the 49-bit time-of-day
435 * value in the Titan chip. The Titan is much more accurate than the value
436 * returned by the service processor for the timebase frequency.
439 static int __init iSeries_tb_recal(void)
441 struct div_result divres;
442 unsigned long titan, tb;
444 /* Make sure we only run on iSeries */
445 if (!firmware_has_feature(FW_FEATURE_ISERIES))
446 return -ENODEV;
448 tb = get_tb();
449 titan = HvCallXm_loadTod();
450 if ( iSeries_recal_titan ) {
451 unsigned long tb_ticks = tb - iSeries_recal_tb;
452 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
453 unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
454 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
455 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
456 char sign = '+';
457 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
458 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
460 if ( tick_diff < 0 ) {
461 tick_diff = -tick_diff;
462 sign = '-';
464 if ( tick_diff ) {
465 if ( tick_diff < tb_ticks_per_jiffy/25 ) {
466 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
467 new_tb_ticks_per_jiffy, sign, tick_diff );
468 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
469 tb_ticks_per_sec = new_tb_ticks_per_sec;
470 calc_cputime_factors();
471 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
472 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
473 tb_to_xs = divres.result_low;
474 do_gtod.varp->tb_to_xs = tb_to_xs;
475 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
476 vdso_data->tb_to_xs = tb_to_xs;
478 else {
479 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
480 " new tb_ticks_per_jiffy = %lu\n"
481 " old tb_ticks_per_jiffy = %lu\n",
482 new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
486 iSeries_recal_titan = titan;
487 iSeries_recal_tb = tb;
489 /* Called here as now we know accurate values for the timebase */
490 clocksource_init();
491 return 0;
493 late_initcall(iSeries_tb_recal);
495 /* Called from platform early init */
496 void __init iSeries_time_init_early(void)
498 iSeries_recal_tb = get_tb();
499 iSeries_recal_titan = HvCallXm_loadTod();
501 #endif /* CONFIG_PPC_ISERIES */
504 * For iSeries shared processors, we have to let the hypervisor
505 * set the hardware decrementer. We set a virtual decrementer
506 * in the lppaca and call the hypervisor if the virtual
507 * decrementer is less than the current value in the hardware
508 * decrementer. (almost always the new decrementer value will
509 * be greater than the current hardware decementer so the hypervisor
510 * call will not be needed)
514 * timer_interrupt - gets called when the decrementer overflows,
515 * with interrupts disabled.
517 void timer_interrupt(struct pt_regs * regs)
519 struct pt_regs *old_regs;
520 int next_dec;
521 int cpu = smp_processor_id();
522 unsigned long ticks;
523 u64 tb_next_jiffy;
525 #ifdef CONFIG_PPC32
526 if (atomic_read(&ppc_n_lost_interrupts) != 0)
527 do_IRQ(regs);
528 #endif
530 old_regs = set_irq_regs(regs);
531 irq_enter();
533 profile_tick(CPU_PROFILING);
534 calculate_steal_time();
536 #ifdef CONFIG_PPC_ISERIES
537 if (firmware_has_feature(FW_FEATURE_ISERIES))
538 get_lppaca()->int_dword.fields.decr_int = 0;
539 #endif
541 while ((ticks = tb_ticks_since(per_cpu(last_jiffy, cpu)))
542 >= tb_ticks_per_jiffy) {
543 /* Update last_jiffy */
544 per_cpu(last_jiffy, cpu) += tb_ticks_per_jiffy;
545 /* Handle RTCL overflow on 601 */
546 if (__USE_RTC() && per_cpu(last_jiffy, cpu) >= 1000000000)
547 per_cpu(last_jiffy, cpu) -= 1000000000;
550 * We cannot disable the decrementer, so in the period
551 * between this cpu's being marked offline in cpu_online_map
552 * and calling stop-self, it is taking timer interrupts.
553 * Avoid calling into the scheduler rebalancing code if this
554 * is the case.
556 if (!cpu_is_offline(cpu))
557 account_process_time(regs);
560 * No need to check whether cpu is offline here; boot_cpuid
561 * should have been fixed up by now.
563 if (cpu != boot_cpuid)
564 continue;
566 write_seqlock(&xtime_lock);
567 tb_next_jiffy = tb_last_jiffy + tb_ticks_per_jiffy;
568 if (__USE_RTC() && tb_next_jiffy >= 1000000000)
569 tb_next_jiffy -= 1000000000;
570 if (per_cpu(last_jiffy, cpu) >= tb_next_jiffy) {
571 tb_last_jiffy = tb_next_jiffy;
572 do_timer(1);
574 write_sequnlock(&xtime_lock);
577 next_dec = tb_ticks_per_jiffy - ticks;
578 set_dec(next_dec);
580 #ifdef CONFIG_PPC_ISERIES
581 if (firmware_has_feature(FW_FEATURE_ISERIES) && hvlpevent_is_pending())
582 process_hvlpevents();
583 #endif
585 #ifdef CONFIG_PPC64
586 /* collect purr register values often, for accurate calculations */
587 if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
588 struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
589 cu->current_tb = mfspr(SPRN_PURR);
591 #endif
593 irq_exit();
594 set_irq_regs(old_regs);
597 void wakeup_decrementer(void)
599 unsigned long ticks;
602 * The timebase gets saved on sleep and restored on wakeup,
603 * so all we need to do is to reset the decrementer.
605 ticks = tb_ticks_since(__get_cpu_var(last_jiffy));
606 if (ticks < tb_ticks_per_jiffy)
607 ticks = tb_ticks_per_jiffy - ticks;
608 else
609 ticks = 1;
610 set_dec(ticks);
613 #ifdef CONFIG_SMP
614 void __init smp_space_timers(unsigned int max_cpus)
616 int i;
617 u64 previous_tb = per_cpu(last_jiffy, boot_cpuid);
619 /* make sure tb > per_cpu(last_jiffy, cpu) for all cpus always */
620 previous_tb -= tb_ticks_per_jiffy;
622 for_each_possible_cpu(i) {
623 if (i == boot_cpuid)
624 continue;
625 per_cpu(last_jiffy, i) = previous_tb;
628 #endif
631 * Scheduler clock - returns current time in nanosec units.
633 * Note: mulhdu(a, b) (multiply high double unsigned) returns
634 * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
635 * are 64-bit unsigned numbers.
637 unsigned long long sched_clock(void)
639 if (__USE_RTC())
640 return get_rtc();
641 return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
644 static int __init get_freq(char *name, int cells, unsigned long *val)
646 struct device_node *cpu;
647 const unsigned int *fp;
648 int found = 0;
650 /* The cpu node should have timebase and clock frequency properties */
651 cpu = of_find_node_by_type(NULL, "cpu");
653 if (cpu) {
654 fp = of_get_property(cpu, name, NULL);
655 if (fp) {
656 found = 1;
657 *val = of_read_ulong(fp, cells);
660 of_node_put(cpu);
663 return found;
666 void __init generic_calibrate_decr(void)
668 ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
670 if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
671 !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
673 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
674 "(not found)\n");
677 ppc_proc_freq = DEFAULT_PROC_FREQ; /* hardcoded default */
679 if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
680 !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
682 printk(KERN_ERR "WARNING: Estimating processor frequency "
683 "(not found)\n");
686 #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
687 /* Set the time base to zero */
688 mtspr(SPRN_TBWL, 0);
689 mtspr(SPRN_TBWU, 0);
691 /* Clear any pending timer interrupts */
692 mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
694 /* Enable decrementer interrupt */
695 mtspr(SPRN_TCR, TCR_DIE);
696 #endif
699 int update_persistent_clock(struct timespec now)
701 struct rtc_time tm;
703 if (!ppc_md.set_rtc_time)
704 return 0;
706 to_tm(now.tv_sec + 1 + timezone_offset, &tm);
707 tm.tm_year -= 1900;
708 tm.tm_mon -= 1;
710 return ppc_md.set_rtc_time(&tm);
713 unsigned long read_persistent_clock(void)
715 struct rtc_time tm;
716 static int first = 1;
718 /* XXX this is a litle fragile but will work okay in the short term */
719 if (first) {
720 first = 0;
721 if (ppc_md.time_init)
722 timezone_offset = ppc_md.time_init();
724 /* get_boot_time() isn't guaranteed to be safe to call late */
725 if (ppc_md.get_boot_time)
726 return ppc_md.get_boot_time() -timezone_offset;
728 if (!ppc_md.get_rtc_time)
729 return 0;
730 ppc_md.get_rtc_time(&tm);
731 return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
732 tm.tm_hour, tm.tm_min, tm.tm_sec);
735 /* clocksource code */
736 static cycle_t rtc_read(void)
738 return (cycle_t)get_rtc();
741 static cycle_t timebase_read(void)
743 return (cycle_t)get_tb();
746 void update_vsyscall(struct timespec *wall_time, struct clocksource *clock)
748 u64 t2x, stamp_xsec;
750 if (clock != &clocksource_timebase)
751 return;
753 /* Make userspace gettimeofday spin until we're done. */
754 ++vdso_data->tb_update_count;
755 smp_mb();
757 /* XXX this assumes clock->shift == 22 */
758 /* 4611686018 ~= 2^(20+64-22) / 1e9 */
759 t2x = (u64) clock->mult * 4611686018ULL;
760 stamp_xsec = (u64) xtime.tv_nsec * XSEC_PER_SEC;
761 do_div(stamp_xsec, 1000000000);
762 stamp_xsec += (u64) xtime.tv_sec * XSEC_PER_SEC;
763 update_gtod(clock->cycle_last, stamp_xsec, t2x);
766 void update_vsyscall_tz(void)
768 /* Make userspace gettimeofday spin until we're done. */
769 ++vdso_data->tb_update_count;
770 smp_mb();
771 vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
772 vdso_data->tz_dsttime = sys_tz.tz_dsttime;
773 smp_mb();
774 ++vdso_data->tb_update_count;
777 void __init clocksource_init(void)
779 struct clocksource *clock;
781 if (__USE_RTC())
782 clock = &clocksource_rtc;
783 else
784 clock = &clocksource_timebase;
786 clock->mult = clocksource_hz2mult(tb_ticks_per_sec, clock->shift);
788 if (clocksource_register(clock)) {
789 printk(KERN_ERR "clocksource: %s is already registered\n",
790 clock->name);
791 return;
794 printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
795 clock->name, clock->mult, clock->shift);
798 /* This function is only called on the boot processor */
799 void __init time_init(void)
801 unsigned long flags;
802 struct div_result res;
803 u64 scale, x;
804 unsigned shift;
806 if (__USE_RTC()) {
807 /* 601 processor: dec counts down by 128 every 128ns */
808 ppc_tb_freq = 1000000000;
809 tb_last_jiffy = get_rtcl();
810 } else {
811 /* Normal PowerPC with timebase register */
812 ppc_md.calibrate_decr();
813 printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
814 ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
815 printk(KERN_DEBUG "time_init: processor frequency = %lu.%.6lu MHz\n",
816 ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
817 tb_last_jiffy = get_tb();
820 tb_ticks_per_jiffy = ppc_tb_freq / HZ;
821 tb_ticks_per_sec = ppc_tb_freq;
822 tb_ticks_per_usec = ppc_tb_freq / 1000000;
823 tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
824 calc_cputime_factors();
827 * Calculate the length of each tick in ns. It will not be
828 * exactly 1e9/HZ unless ppc_tb_freq is divisible by HZ.
829 * We compute 1e9 * tb_ticks_per_jiffy / ppc_tb_freq,
830 * rounded up.
832 x = (u64) NSEC_PER_SEC * tb_ticks_per_jiffy + ppc_tb_freq - 1;
833 do_div(x, ppc_tb_freq);
834 tick_nsec = x;
835 last_tick_len = x << TICKLEN_SCALE;
838 * Compute ticklen_to_xs, which is a factor which gets multiplied
839 * by (last_tick_len << TICKLEN_SHIFT) to get a tb_to_xs value.
840 * It is computed as:
841 * ticklen_to_xs = 2^N / (tb_ticks_per_jiffy * 1e9)
842 * where N = 64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT
843 * which turns out to be N = 51 - SHIFT_HZ.
844 * This gives the result as a 0.64 fixed-point fraction.
845 * That value is reduced by an offset amounting to 1 xsec per
846 * 2^31 timebase ticks to avoid problems with time going backwards
847 * by 1 xsec when we do timer_recalc_offset due to losing the
848 * fractional xsec. That offset is equal to ppc_tb_freq/2^51
849 * since there are 2^20 xsec in a second.
851 div128_by_32((1ULL << 51) - ppc_tb_freq, 0,
852 tb_ticks_per_jiffy << SHIFT_HZ, &res);
853 div128_by_32(res.result_high, res.result_low, NSEC_PER_SEC, &res);
854 ticklen_to_xs = res.result_low;
856 /* Compute tb_to_xs from tick_nsec */
857 tb_to_xs = mulhdu(last_tick_len << TICKLEN_SHIFT, ticklen_to_xs);
860 * Compute scale factor for sched_clock.
861 * The calibrate_decr() function has set tb_ticks_per_sec,
862 * which is the timebase frequency.
863 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
864 * the 128-bit result as a 64.64 fixed-point number.
865 * We then shift that number right until it is less than 1.0,
866 * giving us the scale factor and shift count to use in
867 * sched_clock().
869 div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
870 scale = res.result_low;
871 for (shift = 0; res.result_high != 0; ++shift) {
872 scale = (scale >> 1) | (res.result_high << 63);
873 res.result_high >>= 1;
875 tb_to_ns_scale = scale;
876 tb_to_ns_shift = shift;
877 /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
878 boot_tb = get_tb_or_rtc();
880 write_seqlock_irqsave(&xtime_lock, flags);
882 /* If platform provided a timezone (pmac), we correct the time */
883 if (timezone_offset) {
884 sys_tz.tz_minuteswest = -timezone_offset / 60;
885 sys_tz.tz_dsttime = 0;
888 do_gtod.varp = &do_gtod.vars[0];
889 do_gtod.var_idx = 0;
890 do_gtod.varp->tb_orig_stamp = tb_last_jiffy;
891 __get_cpu_var(last_jiffy) = tb_last_jiffy;
892 do_gtod.varp->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
893 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
894 do_gtod.varp->tb_to_xs = tb_to_xs;
895 do_gtod.tb_to_us = tb_to_us;
897 vdso_data->tb_orig_stamp = tb_last_jiffy;
898 vdso_data->tb_update_count = 0;
899 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
900 vdso_data->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
901 vdso_data->tb_to_xs = tb_to_xs;
903 time_freq = 0;
905 write_sequnlock_irqrestore(&xtime_lock, flags);
907 /* Register the clocksource, if we're not running on iSeries */
908 if (!firmware_has_feature(FW_FEATURE_ISERIES))
909 clocksource_init();
911 /* Not exact, but the timer interrupt takes care of this */
912 set_dec(tb_ticks_per_jiffy);
916 #define FEBRUARY 2
917 #define STARTOFTIME 1970
918 #define SECDAY 86400L
919 #define SECYR (SECDAY * 365)
920 #define leapyear(year) ((year) % 4 == 0 && \
921 ((year) % 100 != 0 || (year) % 400 == 0))
922 #define days_in_year(a) (leapyear(a) ? 366 : 365)
923 #define days_in_month(a) (month_days[(a) - 1])
925 static int month_days[12] = {
926 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
930 * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
932 void GregorianDay(struct rtc_time * tm)
934 int leapsToDate;
935 int lastYear;
936 int day;
937 int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
939 lastYear = tm->tm_year - 1;
942 * Number of leap corrections to apply up to end of last year
944 leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
947 * This year is a leap year if it is divisible by 4 except when it is
948 * divisible by 100 unless it is divisible by 400
950 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
952 day = tm->tm_mon > 2 && leapyear(tm->tm_year);
954 day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
955 tm->tm_mday;
957 tm->tm_wday = day % 7;
960 void to_tm(int tim, struct rtc_time * tm)
962 register int i;
963 register long hms, day;
965 day = tim / SECDAY;
966 hms = tim % SECDAY;
968 /* Hours, minutes, seconds are easy */
969 tm->tm_hour = hms / 3600;
970 tm->tm_min = (hms % 3600) / 60;
971 tm->tm_sec = (hms % 3600) % 60;
973 /* Number of years in days */
974 for (i = STARTOFTIME; day >= days_in_year(i); i++)
975 day -= days_in_year(i);
976 tm->tm_year = i;
978 /* Number of months in days left */
979 if (leapyear(tm->tm_year))
980 days_in_month(FEBRUARY) = 29;
981 for (i = 1; day >= days_in_month(i); i++)
982 day -= days_in_month(i);
983 days_in_month(FEBRUARY) = 28;
984 tm->tm_mon = i;
986 /* Days are what is left over (+1) from all that. */
987 tm->tm_mday = day + 1;
990 * Determine the day of week
992 GregorianDay(tm);
995 /* Auxiliary function to compute scaling factors */
996 /* Actually the choice of a timebase running at 1/4 the of the bus
997 * frequency giving resolution of a few tens of nanoseconds is quite nice.
998 * It makes this computation very precise (27-28 bits typically) which
999 * is optimistic considering the stability of most processor clock
1000 * oscillators and the precision with which the timebase frequency
1001 * is measured but does not harm.
1003 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale)
1005 unsigned mlt=0, tmp, err;
1006 /* No concern for performance, it's done once: use a stupid
1007 * but safe and compact method to find the multiplier.
1010 for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
1011 if (mulhwu(inscale, mlt|tmp) < outscale)
1012 mlt |= tmp;
1015 /* We might still be off by 1 for the best approximation.
1016 * A side effect of this is that if outscale is too large
1017 * the returned value will be zero.
1018 * Many corner cases have been checked and seem to work,
1019 * some might have been forgotten in the test however.
1022 err = inscale * (mlt+1);
1023 if (err <= inscale/2)
1024 mlt++;
1025 return mlt;
1029 * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1030 * result.
1032 void div128_by_32(u64 dividend_high, u64 dividend_low,
1033 unsigned divisor, struct div_result *dr)
1035 unsigned long a, b, c, d;
1036 unsigned long w, x, y, z;
1037 u64 ra, rb, rc;
1039 a = dividend_high >> 32;
1040 b = dividend_high & 0xffffffff;
1041 c = dividend_low >> 32;
1042 d = dividend_low & 0xffffffff;
1044 w = a / divisor;
1045 ra = ((u64)(a - (w * divisor)) << 32) + b;
1047 rb = ((u64) do_div(ra, divisor) << 32) + c;
1048 x = ra;
1050 rc = ((u64) do_div(rb, divisor) << 32) + d;
1051 y = rb;
1053 do_div(rc, divisor);
1054 z = rc;
1056 dr->result_high = ((u64)w << 32) + x;
1057 dr->result_low = ((u64)y << 32) + z;