2 * Copyright 2001 MontaVista Software Inc.
3 * Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
4 * Copyright (c) 2003 Maciej W. Rozycki
6 * Common time service routines for MIPS machines. See
7 * Documentation/mips/time.README.
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation; either version 2 of the License, or (at your
12 * option) any later version.
14 #include <linux/config.h>
15 #include <linux/types.h>
16 #include <linux/kernel.h>
17 #include <linux/init.h>
18 #include <linux/sched.h>
19 #include <linux/param.h>
20 #include <linux/time.h>
21 #include <linux/timex.h>
22 #include <linux/smp.h>
23 #include <linux/kernel_stat.h>
24 #include <linux/spinlock.h>
25 #include <linux/interrupt.h>
26 #include <linux/module.h>
28 #include <asm/bootinfo.h>
30 #include <asm/cpu-features.h>
31 #include <asm/div64.h>
32 #include <asm/hardirq.h>
33 #include <asm/sections.h>
37 * The integer part of the number of usecs per jiffy is taken from tick,
38 * but the fractional part is not recorded, so we calculate it using the
39 * initial value of HZ. This aids systems where tick isn't really an
40 * integer (e.g. for HZ = 128).
42 #define USECS_PER_JIFFY TICK_SIZE
43 #define USECS_PER_JIFFY_FRAC ((unsigned long)(u32)((1000000ULL << 32) / HZ))
45 #define TICK_SIZE (tick_nsec / 1000)
47 u64 jiffies_64 = INITIAL_JIFFIES;
49 EXPORT_SYMBOL(jiffies_64);
54 extern volatile unsigned long wall_jiffies;
56 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
59 * whether we emulate local_timer_interrupts for SMP machines.
61 int emulate_local_timer_interrupt;
65 * By default we provide the null RTC ops
67 static unsigned long null_rtc_get_time(void)
69 return mktime(2000, 1, 1, 0, 0, 0);
72 static int null_rtc_set_time(unsigned long sec)
77 unsigned long (*rtc_get_time)(void) = null_rtc_get_time;
78 int (*rtc_set_time)(unsigned long) = null_rtc_set_time;
79 int (*rtc_set_mmss)(unsigned long);
82 /* usecs per counter cycle, shifted to left by 32 bits */
83 static unsigned int sll32_usecs_per_cycle;
85 /* how many counter cycles in a jiffy */
86 static unsigned long cycles_per_jiffy;
88 /* Cycle counter value at the previous timer interrupt.. */
89 static unsigned int timerhi, timerlo;
91 /* expirelo is the count value for next CPU timer interrupt */
92 static unsigned int expirelo;
96 * Null timer ack for systems not needing one (e.g. i8254).
98 static void null_timer_ack(void) { /* nothing */ }
101 * Null high precision timer functions for systems lacking one.
103 static unsigned int null_hpt_read(void)
108 static void null_hpt_init(unsigned int count) { /* nothing */ }
112 * Timer ack for an R4k-compatible timer of a known frequency.
114 static void c0_timer_ack(void)
118 /* Ack this timer interrupt and set the next one. */
119 expirelo += cycles_per_jiffy;
120 write_c0_compare(expirelo);
122 /* Check to see if we have missed any timer interrupts. */
123 count = read_c0_count();
124 if ((count - expirelo) < 0x7fffffff) {
125 /* missed_timer_count++; */
126 expirelo = count + cycles_per_jiffy;
127 write_c0_compare(expirelo);
132 * High precision timer functions for a R4k-compatible timer.
134 static unsigned int c0_hpt_read(void)
136 return read_c0_count();
139 /* For use solely as a high precision timer. */
140 static void c0_hpt_init(unsigned int count)
142 write_c0_count(read_c0_count() - count);
145 /* For use both as a high precision timer and an interrupt source. */
146 static void c0_hpt_timer_init(unsigned int count)
148 count = read_c0_count() - count;
149 expirelo = (count / cycles_per_jiffy + 1) * cycles_per_jiffy;
150 write_c0_count(expirelo - cycles_per_jiffy);
151 write_c0_compare(expirelo);
152 write_c0_count(count);
155 int (*mips_timer_state)(void);
156 void (*mips_timer_ack)(void);
157 unsigned int (*mips_hpt_read)(void);
158 void (*mips_hpt_init)(unsigned int);
162 * This version of gettimeofday has microsecond resolution and better than
163 * microsecond precision on fast machines with cycle counter.
165 void do_gettimeofday(struct timeval *tv)
169 unsigned long usec, sec;
170 unsigned long max_ntp_tick = tick_usec - tickadj;
173 seq = read_seqbegin(&xtime_lock);
175 usec = do_gettimeoffset();
177 lost = jiffies - wall_jiffies;
180 * If time_adjust is negative then NTP is slowing the clock
181 * so make sure not to go into next possible interval.
182 * Better to lose some accuracy than have time go backwards..
184 if (unlikely(time_adjust < 0)) {
185 usec = min(usec, max_ntp_tick);
188 usec += lost * max_ntp_tick;
189 } else if (unlikely(lost))
190 usec += lost * tick_usec;
193 usec += (xtime.tv_nsec / 1000);
195 } while (read_seqretry(&xtime_lock, seq));
197 while (usec >= 1000000) {
206 EXPORT_SYMBOL(do_gettimeofday);
208 int do_settimeofday(struct timespec *tv)
210 time_t wtm_sec, sec = tv->tv_sec;
211 long wtm_nsec, nsec = tv->tv_nsec;
213 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
216 write_seqlock_irq(&xtime_lock);
219 * This is revolting. We need to set "xtime" correctly. However,
220 * the value in this location is the value at the most recent update
221 * of wall time. Discover what correction gettimeofday() would have
222 * made, and then undo it!
224 nsec -= do_gettimeoffset() * NSEC_PER_USEC;
225 nsec -= (jiffies - wall_jiffies) * tick_nsec;
227 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
228 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
230 set_normalized_timespec(&xtime, sec, nsec);
231 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
233 time_adjust = 0; /* stop active adjtime() */
234 time_status |= STA_UNSYNC;
235 time_maxerror = NTP_PHASE_LIMIT;
236 time_esterror = NTP_PHASE_LIMIT;
238 write_sequnlock_irq(&xtime_lock);
243 EXPORT_SYMBOL(do_settimeofday);
246 * Gettimeoffset routines. These routines returns the time duration
247 * since last timer interrupt in usecs.
249 * If the exact CPU counter frequency is known, use fixed_rate_gettimeoffset.
250 * Otherwise use calibrate_gettimeoffset()
252 * If the CPU does not have the counter register, you can either supply
253 * your own gettimeoffset() routine, or use null_gettimeoffset(), which
254 * gives the same resolution as HZ.
257 static unsigned long null_gettimeoffset(void)
263 /* The function pointer to one of the gettimeoffset funcs. */
264 unsigned long (*do_gettimeoffset)(void) = null_gettimeoffset;
267 static unsigned long fixed_rate_gettimeoffset(void)
272 /* Get last timer tick in absolute kernel time */
273 count = mips_hpt_read();
275 /* .. relative to previous jiffy (32 bits is enough) */
278 __asm__("multu %1,%2"
280 : "r" (count), "r" (sll32_usecs_per_cycle)
284 * Due to possible jiffies inconsistencies, we need to check
285 * the result so that we'll get a timer that is monotonic.
287 if (res >= USECS_PER_JIFFY)
288 res = USECS_PER_JIFFY - 1;
295 * Cached "1/(clocks per usec) * 2^32" value.
296 * It has to be recalculated once each jiffy.
298 static unsigned long cached_quotient;
300 /* Last jiffy when calibrate_divXX_gettimeoffset() was called. */
301 static unsigned long last_jiffies;
304 * This is moved from dec/time.c:do_ioasic_gettimeoffset() by Maciej.
306 static unsigned long calibrate_div32_gettimeoffset(void)
309 unsigned long res, tmp;
310 unsigned long quotient;
314 quotient = cached_quotient;
316 if (last_jiffies != tmp) {
318 if (last_jiffies != 0) {
320 do_div64_32(r0, timerhi, timerlo, tmp);
321 do_div64_32(quotient, USECS_PER_JIFFY,
322 USECS_PER_JIFFY_FRAC, r0);
323 cached_quotient = quotient;
327 /* Get last timer tick in absolute kernel time */
328 count = mips_hpt_read();
330 /* .. relative to previous jiffy (32 bits is enough) */
333 __asm__("multu %1,%2"
335 : "r" (count), "r" (quotient)
339 * Due to possible jiffies inconsistencies, we need to check
340 * the result so that we'll get a timer that is monotonic.
342 if (res >= USECS_PER_JIFFY)
343 res = USECS_PER_JIFFY - 1;
348 static unsigned long calibrate_div64_gettimeoffset(void)
351 unsigned long res, tmp;
352 unsigned long quotient;
356 quotient = cached_quotient;
358 if (last_jiffies != tmp) {
362 __asm__(".set push\n\t"
374 : "=&r" (quotient), "=&r" (r0)
375 : "r" (timerhi), "m" (timerlo),
376 "r" (tmp), "r" (USECS_PER_JIFFY),
377 "r" (USECS_PER_JIFFY_FRAC)
378 : "hi", "lo", "accum");
379 cached_quotient = quotient;
383 /* Get last timer tick in absolute kernel time */
384 count = mips_hpt_read();
386 /* .. relative to previous jiffy (32 bits is enough) */
389 __asm__("multu %1,%2"
391 : "r" (count), "r" (quotient)
395 * Due to possible jiffies inconsistencies, we need to check
396 * the result so that we'll get a timer that is monotonic.
398 if (res >= USECS_PER_JIFFY)
399 res = USECS_PER_JIFFY - 1;
405 /* last time when xtime and rtc are sync'ed up */
406 static long last_rtc_update;
409 * local_timer_interrupt() does profiling and process accounting
410 * on a per-CPU basis.
412 * In UP mode, it is invoked from the (global) timer_interrupt.
414 * In SMP mode, it might invoked by per-CPU timer interrupt, or
415 * a broadcasted inter-processor interrupt which itself is triggered
416 * by the global timer interrupt.
418 void local_timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
420 if (!user_mode(regs)) {
421 if (prof_buffer && current->pid) {
422 unsigned long pc = regs->cp0_epc;
424 pc -= (unsigned long) _stext;
427 * Dont ignore out-of-bounds pc values silently,
428 * put them into the last histogram slot, so if
429 * present, they will show up as a sharp peak.
431 if (pc > prof_len - 1)
433 atomic_inc((atomic_t *)&prof_buffer[pc]);
438 /* in UP mode, update_process_times() is invoked by do_timer() */
439 update_process_times(user_mode(regs));
444 * High-level timer interrupt service routines. This function
445 * is set as irqaction->handler and is invoked through do_IRQ.
447 irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
452 count = mips_hpt_read();
455 /* Update timerhi/timerlo for intra-jiffy calibration. */
456 timerhi += count < timerlo; /* Wrap around */
460 * call the generic timer interrupt handling
465 * If we have an externally synchronized Linux clock, then update
466 * CMOS clock accordingly every ~11 minutes. rtc_set_time() has to be
467 * called as close as possible to 500 ms before the new second starts.
469 write_seqlock(&xtime_lock);
470 if ((time_status & STA_UNSYNC) == 0 &&
471 xtime.tv_sec > last_rtc_update + 660 &&
472 (xtime.tv_nsec / 1000) >= 500000 - ((unsigned) TICK_SIZE) / 2 &&
473 (xtime.tv_nsec / 1000) <= 500000 + ((unsigned) TICK_SIZE) / 2) {
474 if (rtc_set_mmss(xtime.tv_sec) == 0) {
475 last_rtc_update = xtime.tv_sec;
477 /* do it again in 60 s */
478 last_rtc_update = xtime.tv_sec - 600;
481 write_sequnlock(&xtime_lock);
484 * If jiffies has overflown in this timer_interrupt, we must
485 * update the timer[hi]/[lo] to make fast gettimeoffset funcs
486 * quotient calc still valid. -arca
488 * The first timer interrupt comes late as interrupts are
489 * enabled long after timers are initialized. Therefore the
490 * high precision timer is fast, leading to wrong gettimeoffset()
491 * calculations. We deal with it by setting it based on the
492 * number of its ticks between the second and the third interrupt.
493 * That is still somewhat imprecise, but it's a good estimate.
498 static unsigned int prev_count;
499 static int hpt_initialized;
503 timerhi = timerlo = 0;
504 mips_hpt_init(count);
510 if (!hpt_initialized) {
511 unsigned int c3 = 3 * (count - prev_count);
515 mips_hpt_init(count - c3);
524 #if !defined(CONFIG_SMP)
526 * In UP mode, we call local_timer_interrupt() to do profiling
527 * and process accouting.
529 * In SMP mode, local_timer_interrupt() is invoked by appropriate
530 * low-level local timer interrupt handler.
532 local_timer_interrupt(irq, dev_id, regs);
534 #else /* CONFIG_SMP */
536 if (emulate_local_timer_interrupt) {
538 * this is the place where we send out inter-process
539 * interrupts and let each CPU do its own profiling
540 * and process accouting.
542 * Obviously we need to call local_timer_interrupt() for
543 * the current CPU too.
545 panic("Not implemented yet!!!");
547 #endif /* CONFIG_SMP */
552 asmlinkage void ll_timer_interrupt(int irq, struct pt_regs *regs)
555 kstat_this_cpu.irqs[irq]++;
557 /* we keep interrupt disabled all the time */
558 timer_interrupt(irq, NULL, regs);
563 asmlinkage void ll_local_timer_interrupt(int irq, struct pt_regs *regs)
566 if (smp_processor_id() != 0)
567 kstat_this_cpu.irqs[irq]++;
569 /* we keep interrupt disabled all the time */
570 local_timer_interrupt(irq, NULL, regs);
576 * time_init() - it does the following things.
578 * 1) board_time_init() -
579 * a) (optional) set up RTC routines,
580 * b) (optional) calibrate and set the mips_hpt_frequency
581 * (only needed if you intended to use fixed_rate_gettimeoffset
582 * or use cpu counter as timer interrupt source)
583 * 2) setup xtime based on rtc_get_time().
584 * 3) choose a appropriate gettimeoffset routine.
585 * 4) calculate a couple of cached variables for later usage
586 * 5) board_timer_setup() -
587 * a) (optional) over-write any choices made above by time_init().
588 * b) machine specific code should setup the timer irqaction.
589 * c) enable the timer interrupt
592 void (*board_time_init)(void);
593 void (*board_timer_setup)(struct irqaction *irq);
595 unsigned int mips_hpt_frequency;
597 static struct irqaction timer_irqaction = {
598 .handler = timer_interrupt,
599 .flags = SA_INTERRUPT,
603 static unsigned int __init calibrate_hpt(void)
606 u32 hpt_start, hpt_end, hpt_count, hz;
608 const int loops = HZ / 10;
613 * We want to calibrate for 0.1s, but to avoid a 64-bit
614 * division we round the number of loops up to the nearest
617 while (loops > 1 << log_2_loops)
619 i = 1 << log_2_loops;
622 * Wait for a rising edge of the timer interrupt.
624 while (mips_timer_state());
625 while (!mips_timer_state());
628 * Now see how many high precision timer ticks happen
629 * during the calculated number of periods between timer
632 hpt_start = mips_hpt_read();
634 while (mips_timer_state());
635 while (!mips_timer_state());
637 hpt_end = mips_hpt_read();
639 hpt_count = hpt_end - hpt_start;
641 frequency = (u64)hpt_count * (u64)hz;
643 return frequency >> log_2_loops;
646 void __init time_init(void)
652 rtc_set_mmss = rtc_set_time;
654 xtime.tv_sec = rtc_get_time();
657 set_normalized_timespec(&wall_to_monotonic,
658 -xtime.tv_sec, -xtime.tv_nsec);
660 /* Choose appropriate high precision timer routines. */
661 if (!cpu_has_counter && !mips_hpt_read) {
662 /* No high precision timer -- sorry. */
663 mips_hpt_read = null_hpt_read;
664 mips_hpt_init = null_hpt_init;
665 } else if (!mips_hpt_frequency && !mips_timer_state) {
666 /* A high precision timer of unknown frequency. */
667 if (!mips_hpt_read) {
668 /* No external high precision timer -- use R4k. */
669 mips_hpt_read = c0_hpt_read;
670 mips_hpt_init = c0_hpt_init;
673 if ((current_cpu_data.isa_level == MIPS_CPU_ISA_M32) ||
674 (current_cpu_data.isa_level == MIPS_CPU_ISA_I) ||
675 (current_cpu_data.isa_level == MIPS_CPU_ISA_II))
677 * We need to calibrate the counter but we don't have
680 do_gettimeoffset = calibrate_div32_gettimeoffset;
683 * We need to calibrate the counter but we *do* have
686 do_gettimeoffset = calibrate_div64_gettimeoffset;
688 /* We know counter frequency. Or we can get it. */
689 if (!mips_hpt_read) {
690 /* No external high precision timer -- use R4k. */
691 mips_hpt_read = c0_hpt_read;
693 if (mips_timer_state)
694 mips_hpt_init = c0_hpt_init;
696 /* No external timer interrupt -- use R4k. */
697 mips_hpt_init = c0_hpt_timer_init;
698 mips_timer_ack = c0_timer_ack;
701 if (!mips_hpt_frequency)
702 mips_hpt_frequency = calibrate_hpt();
704 do_gettimeoffset = fixed_rate_gettimeoffset;
706 /* Calculate cache parameters. */
707 cycles_per_jiffy = (mips_hpt_frequency + HZ / 2) / HZ;
709 /* sll32_usecs_per_cycle = 10^6 * 2^32 / mips_counter_freq */
710 do_div64_32(sll32_usecs_per_cycle,
711 1000000, mips_hpt_frequency / 2,
714 /* Report the high precision timer rate for a reference. */
715 printk("Using %u.%03u MHz high precision timer.\n",
716 ((mips_hpt_frequency + 500) / 1000) / 1000,
717 ((mips_hpt_frequency + 500) / 1000) % 1000);
721 /* No timer interrupt ack (e.g. i8254). */
722 mips_timer_ack = null_timer_ack;
724 /* This sets up the high precision timer for the first interrupt. */
725 mips_hpt_init(mips_hpt_read());
728 * Call board specific timer interrupt setup.
730 * this pointer must be setup in machine setup routine.
732 * Even if a machine chooses to use a low-level timer interrupt,
733 * it still needs to setup the timer_irqaction.
734 * In that case, it might be better to set timer_irqaction.handler
735 * to be NULL function so that we are sure the high-level code
736 * is not invoked accidentally.
738 board_timer_setup(&timer_irqaction);
742 #define STARTOFTIME 1970
743 #define SECDAY 86400L
744 #define SECYR (SECDAY * 365)
745 #define leapyear(y) ((!((y) % 4) && ((y) % 100)) || !((y) % 400))
746 #define days_in_year(y) (leapyear(y) ? 366 : 365)
747 #define days_in_month(m) (month_days[(m) - 1])
749 static int month_days[12] = {
750 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
753 void to_tm(unsigned long tim, struct rtc_time *tm)
758 gday = day = tim / SECDAY;
761 /* Hours, minutes, seconds are easy */
762 tm->tm_hour = hms / 3600;
763 tm->tm_min = (hms % 3600) / 60;
764 tm->tm_sec = (hms % 3600) % 60;
766 /* Number of years in days */
767 for (i = STARTOFTIME; day >= days_in_year(i); i++)
768 day -= days_in_year(i);
771 /* Number of months in days left */
772 if (leapyear(tm->tm_year))
773 days_in_month(FEBRUARY) = 29;
774 for (i = 1; day >= days_in_month(i); i++)
775 day -= days_in_month(i);
776 days_in_month(FEBRUARY) = 28;
777 tm->tm_mon = i - 1; /* tm_mon starts from 0 to 11 */
779 /* Days are what is left over (+1) from all that. */
780 tm->tm_mday = day + 1;
783 * Determine the day of week
785 tm->tm_wday = (gday + 4) % 7; /* 1970/1/1 was Thursday */
788 EXPORT_SYMBOL(rtc_lock);
789 EXPORT_SYMBOL(to_tm);
790 EXPORT_SYMBOL(rtc_set_time);
791 EXPORT_SYMBOL(rtc_get_time);