c508fd4f7a546e5114386b60dfa57897ddca0aa4
[linux-flexiantxendom0-3.2.10.git] / arch / mips / kernel / time.c
1 /*
2  * Copyright 2001 MontaVista Software Inc.
3  * Author: Jun Sun, jsun@mvista.com or jsun@junsun.net
4  * Copyright (c) 2003  Maciej W. Rozycki
5  *
6  * Common time service routines for MIPS machines. See
7  * Documentation/mips/time.README.
8  *
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.
13  */
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/smp.h>
22 #include <linux/kernel_stat.h>
23 #include <linux/spinlock.h>
24 #include <linux/interrupt.h>
25 #include <linux/module.h>
26
27 #include <asm/bootinfo.h>
28 #include <asm/cpu.h>
29 #include <asm/div64.h>
30 #include <asm/hardirq.h>
31 #include <asm/sections.h>
32 #include <asm/time.h>
33
34 /* This is for machines which generate the exact clock. */
35 #define USECS_PER_JIFFY (1000000/HZ)
36 #define USECS_PER_JIFFY_FRAC ((u32)((1000000ULL << 32) / HZ))
37
38 #define TICK_SIZE       (tick_nsec / 1000)
39
40 u64 jiffies_64 = INITIAL_JIFFIES;
41
42 EXPORT_SYMBOL(jiffies_64);
43
44 /*
45  * forward reference
46  */
47 extern volatile unsigned long wall_jiffies;
48
49 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
50
51 /*
52  * whether we emulate local_timer_interrupts for SMP machines.
53  */
54 int emulate_local_timer_interrupt;
55
56 /*
57  * By default we provide the null RTC ops
58  */
59 static unsigned long null_rtc_get_time(void)
60 {
61         return mktime(2000, 1, 1, 0, 0, 0);
62 }
63
64 static int null_rtc_set_time(unsigned long sec)
65 {
66         return 0;
67 }
68
69 unsigned long (*rtc_get_time)(void) = null_rtc_get_time;
70 int (*rtc_set_time)(unsigned long) = null_rtc_set_time;
71 int (*rtc_set_mmss)(unsigned long);
72
73
74 /*
75  * This version of gettimeofday has microsecond resolution and better than
76  * microsecond precision on fast machines with cycle counter.
77  */
78 void do_gettimeofday(struct timeval *tv)
79 {
80         unsigned long seq;
81         unsigned long usec, sec;
82
83         do {
84                 seq = read_seqbegin(&xtime_lock);
85                 usec = do_gettimeoffset();
86                 {
87                         unsigned long lost = jiffies - wall_jiffies;
88                         if (lost)
89                                 usec += lost * (1000000 / HZ);
90                 }
91                 sec = xtime.tv_sec;
92                 usec += (xtime.tv_nsec / 1000);
93         } while (read_seqretry(&xtime_lock, seq));
94
95         while (usec >= 1000000) {
96                 usec -= 1000000;
97                 sec++;
98         }
99
100         tv->tv_sec = sec;
101         tv->tv_usec = usec;
102 }
103
104 EXPORT_SYMBOL(do_gettimeofday);
105
106 int do_settimeofday(struct timespec *tv)
107 {
108         time_t wtm_sec, sec = tv->tv_sec;
109         long wtm_nsec, nsec = tv->tv_nsec;
110
111         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
112                 return -EINVAL;
113
114         write_seqlock_irq(&xtime_lock);
115         /*
116          * This is revolting. We need to set "xtime" correctly. However, the
117          * value in this location is the value at the most recent update of
118          * wall time.  Discover what correction gettimeofday() would have
119          * made, and then undo it!
120          */
121         nsec -= do_gettimeoffset() * NSEC_PER_USEC;
122         nsec -= (jiffies - wall_jiffies) * TICK_NSEC;
123
124         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
125         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
126
127         set_normalized_timespec(&xtime, sec, nsec);
128         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
129
130         time_adjust = 0;                /* stop active adjtime() */
131         time_status |= STA_UNSYNC;
132         time_maxerror = NTP_PHASE_LIMIT;
133         time_esterror = NTP_PHASE_LIMIT;
134         write_sequnlock_irq(&xtime_lock);
135
136         return 0;
137 }
138
139 EXPORT_SYMBOL(do_settimeofday);
140
141 /*
142  * Gettimeoffset routines.  These routines returns the time duration
143  * since last timer interrupt in usecs.
144  *
145  * If the exact CPU counter frequency is known, use fixed_rate_gettimeoffset.
146  * Otherwise use calibrate_gettimeoffset()
147  *
148  * If the CPU does not have counter register all, you can either supply
149  * your own gettimeoffset() routine, or use null_gettimeoffset() routines,
150  * which gives the same resolution as HZ.
151  */
152
153
154 /* usecs per counter cycle, shifted to left by 32 bits */
155 static unsigned int sll32_usecs_per_cycle;
156
157 /* how many counter cycles in a jiffy */
158 static unsigned long cycles_per_jiffy;
159
160 /* Cycle counter value at the previous timer interrupt.. */
161 static unsigned int timerhi, timerlo;
162
163 /* expirelo is the count value for next CPU timer interrupt */
164 static unsigned int expirelo;
165
166 /* last time when xtime and rtc are sync'ed up */
167 static long last_rtc_update;
168
169 /* the function pointer to one of the gettimeoffset funcs*/
170 unsigned long (*do_gettimeoffset)(void) = null_gettimeoffset;
171
172 unsigned long null_gettimeoffset(void)
173 {
174         return 0;
175 }
176
177 unsigned long fixed_rate_gettimeoffset(void)
178 {
179         u32 count;
180         unsigned long res;
181
182         /* Get last timer tick in absolute kernel time */
183         count = read_c0_count();
184
185         /* .. relative to previous jiffy (32 bits is enough) */
186         count -= timerlo;
187
188         __asm__("multu  %1,%2"
189                 : "=h" (res)
190                 : "r" (count), "r" (sll32_usecs_per_cycle)
191                 : "lo", "accum");
192
193         /*
194          * Due to possible jiffies inconsistencies, we need to check
195          * the result so that we'll get a timer that is monotonic.
196          */
197         if (res >= USECS_PER_JIFFY)
198                 res = USECS_PER_JIFFY - 1;
199
200         return res;
201 }
202
203 /*
204  * Cached "1/(clocks per usec) * 2^32" value.
205  * It has to be recalculated once each jiffy.
206  */
207 static unsigned long cached_quotient;
208
209 /* Last jiffy when calibrate_divXX_gettimeoffset() was called. */
210 static unsigned long last_jiffies;
211
212
213 /*
214  * This is copied from dec/time.c:do_ioasic_gettimeoffset() by Maciej.
215  */
216 unsigned long calibrate_div32_gettimeoffset(void)
217 {
218         u32 count;
219         unsigned long res, tmp;
220         unsigned long quotient;
221
222         tmp = jiffies;
223
224         quotient = cached_quotient;
225
226         if (last_jiffies != tmp) {
227                 last_jiffies = tmp;
228                 if (last_jiffies != 0) {
229                         unsigned long r0;
230                         do_div64_32(r0, timerhi, timerlo, tmp);
231                         do_div64_32(quotient, USECS_PER_JIFFY,
232                                     USECS_PER_JIFFY_FRAC, r0);
233                         cached_quotient = quotient;
234                 }
235         }
236
237         /* Get last timer tick in absolute kernel time */
238         count = read_c0_count();
239
240         /* .. relative to previous jiffy (32 bits is enough) */
241         count -= timerlo;
242
243         __asm__("multu  %1,%2"
244                 : "=h" (res)
245                 : "r" (count), "r" (quotient)
246                 : "lo", "accum");
247
248         /*
249          * Due to possible jiffies inconsistencies, we need to check
250          * the result so that we'll get a timer that is monotonic.
251          */
252         if (res >= USECS_PER_JIFFY)
253                 res = USECS_PER_JIFFY - 1;
254
255         return res;
256 }
257
258 unsigned long calibrate_div64_gettimeoffset(void)
259 {
260         u32 count;
261         unsigned long res, tmp;
262         unsigned long quotient;
263
264         tmp = jiffies;
265
266         quotient = cached_quotient;
267
268         if (tmp && last_jiffies != tmp) {
269                 last_jiffies = tmp;
270                 __asm__(".set   push\n\t"
271                         ".set   noreorder\n\t"
272                         ".set   noat\n\t"
273                         ".set   mips3\n\t"
274                         "lwu    %0,%2\n\t"
275                         "dsll32 $1,%1,0\n\t"
276                         "or     $1,$1,%0\n\t"
277                         "ddivu  $0,$1,%3\n\t"
278                         "mflo   $1\n\t"
279                         "dsll32 %0,%4,0\n\t"
280                         "nop\n\t"
281                         "ddivu  $0,%0,$1\n\t"
282                         "mflo   %0\n\t"
283                         ".set   pop"
284                         : "=&r" (quotient)
285                         : "r" (timerhi), "m" (timerlo),
286                           "r" (tmp), "r" (USECS_PER_JIFFY));
287                 cached_quotient = quotient;
288         }
289
290         /* Get last timer tick in absolute kernel time */
291         count = read_c0_count();
292
293         /* .. relative to previous jiffy (32 bits is enough) */
294         count -= timerlo;
295
296         __asm__("multu  %1,%2"
297                 : "=h" (res)
298                 : "r" (count), "r" (quotient)
299                 : "lo", "accum");
300
301         /*
302          * Due to possible jiffies inconsistencies, we need to check
303          * the result so that we'll get a timer that is monotonic.
304          */
305         if (res >= USECS_PER_JIFFY)
306                 res = USECS_PER_JIFFY - 1;
307
308         return res;
309 }
310
311
312 /*
313  * local_timer_interrupt() does profiling and process accounting
314  * on a per-CPU basis.
315  *
316  * In UP mode, it is invoked from the (global) timer_interrupt.
317  *
318  * In SMP mode, it might invoked by per-CPU timer interrupt, or
319  * a broadcasted inter-processor interrupt which itself is triggered
320  * by the global timer interrupt.
321  */
322 void local_timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
323 {
324         if (!user_mode(regs)) {
325                 if (prof_buffer && current->pid) {
326                         unsigned long pc = regs->cp0_epc;
327
328                         pc -= (unsigned long) _stext;
329                         pc >>= prof_shift;
330                         /*
331                          * Dont ignore out-of-bounds pc values silently,
332                          * put them into the last histogram slot, so if
333                          * present, they will show up as a sharp peak.
334                          */
335                         if (pc > prof_len - 1)
336                                 pc = prof_len - 1;
337                         atomic_inc((atomic_t *)&prof_buffer[pc]);
338                 }
339         }
340
341 #ifdef CONFIG_SMP
342         /* in UP mode, update_process_times() is invoked by do_timer() */
343         update_process_times(user_mode(regs));
344 #endif
345 }
346
347 /*
348  * high-level timer interrupt service routines.  This function
349  * is set as irqaction->handler and is invoked through do_IRQ.
350  */
351 irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
352 {
353         if (cpu_has_counter) {
354                 unsigned int count;
355
356                 /* ack timer interrupt, and try to set next interrupt */
357                 expirelo += cycles_per_jiffy;
358                 write_c0_compare(expirelo);
359                 count = read_c0_count();
360
361                 /* check to see if we have missed any timer interrupts */
362                 if ((count - expirelo) < 0x7fffffff) {
363                         /* missed_timer_count++; */
364                         expirelo = count + cycles_per_jiffy;
365                         write_c0_compare(expirelo);
366                 }
367
368                 /* Update timerhi/timerlo for intra-jiffy calibration. */
369                 timerhi += count < timerlo;     /* Wrap around */
370                 timerlo = count;
371         }
372
373         /*
374          * call the generic timer interrupt handling
375          */
376         do_timer(regs);
377
378         /*
379          * If we have an externally synchronized Linux clock, then update
380          * CMOS clock accordingly every ~11 minutes. rtc_set_time() has to be
381          * called as close as possible to 500 ms before the new second starts.
382          */
383         write_seqlock(&xtime_lock);
384         if ((time_status & STA_UNSYNC) == 0 &&
385             xtime.tv_sec > last_rtc_update + 660 &&
386             (xtime.tv_nsec / 1000) >= 500000 - ((unsigned) TICK_SIZE) / 2 &&
387             (xtime.tv_nsec / 1000) <= 500000 + ((unsigned) TICK_SIZE) / 2) {
388                 if (rtc_set_mmss(xtime.tv_sec) == 0) {
389                         last_rtc_update = xtime.tv_sec;
390                 } else {
391                         /* do it again in 60 s */
392                         last_rtc_update = xtime.tv_sec - 600;
393                 }
394         }
395         write_sequnlock(&xtime_lock);
396
397         /*
398          * If jiffies has overflowed in this timer_interrupt we must
399          * update the timer[hi]/[lo] to make fast gettimeoffset funcs
400          * quotient calc still valid. -arca
401          */
402         if (!jiffies) {
403                 timerhi = timerlo = 0;
404         }
405
406 #if !defined(CONFIG_SMP)
407         /*
408          * In UP mode, we call local_timer_interrupt() to do profiling
409          * and process accouting.
410          *
411          * In SMP mode, local_timer_interrupt() is invoked by appropriate
412          * low-level local timer interrupt handler.
413          */
414         local_timer_interrupt(irq, dev_id, regs);
415
416 #else   /* CONFIG_SMP */
417
418         if (emulate_local_timer_interrupt) {
419                 /*
420                  * this is the place where we send out inter-process
421                  * interrupts and let each CPU do its own profiling
422                  * and process accouting.
423                  *
424                  * Obviously we need to call local_timer_interrupt() for
425                  * the current CPU too.
426                  */
427                 panic("Not implemented yet!!!");
428         }
429 #endif  /* CONFIG_SMP */
430
431         return IRQ_HANDLED;
432 }
433
434 asmlinkage void ll_timer_interrupt(int irq, struct pt_regs *regs)
435 {
436         irq_enter();
437         kstat_this_cpu.irqs[irq]++;
438
439         /* we keep interrupt disabled all the time */
440         timer_interrupt(irq, NULL, regs);
441
442         irq_exit();
443 }
444
445 asmlinkage void ll_local_timer_interrupt(int irq, struct pt_regs *regs)
446 {
447         irq_enter();
448         kstat_this_cpu.irqs[irq]++;
449
450         /* we keep interrupt disabled all the time */
451         local_timer_interrupt(irq, NULL, regs);
452
453         irq_exit();
454 }
455
456 /*
457  * time_init() - it does the following things.
458  *
459  * 1) board_time_init() -
460  *      a) (optional) set up RTC routines,
461  *      b) (optional) calibrate and set the mips_counter_frequency
462  *          (only needed if you intended to use fixed_rate_gettimeoffset
463  *           or use cpu counter as timer interrupt source)
464  * 2) setup xtime based on rtc_get_time().
465  * 3) choose a appropriate gettimeoffset routine.
466  * 4) calculate a couple of cached variables for later usage
467  * 5) board_timer_setup() -
468  *      a) (optional) over-write any choices made above by time_init().
469  *      b) machine specific code should setup the timer irqaction.
470  *      c) enable the timer interrupt
471  */
472
473 void (*board_time_init)(void);
474 void (*board_timer_setup)(struct irqaction *irq);
475
476 unsigned int mips_counter_frequency;
477
478 static struct irqaction timer_irqaction = {
479         .handler = timer_interrupt,
480         .flags = SA_INTERRUPT,
481         .name = "timer",
482 };
483
484 void __init time_init(void)
485 {
486         if (board_time_init)
487                 board_time_init();
488
489         if (!rtc_set_mmss)
490                 rtc_set_mmss = rtc_set_time;
491
492         xtime.tv_sec = rtc_get_time();
493         xtime.tv_nsec = 0;
494
495         set_normalized_timespec(&wall_to_monotonic,
496                                 -xtime.tv_sec, -xtime.tv_nsec);
497
498         /* choose appropriate gettimeoffset routine */
499         if (!cpu_has_counter) {
500                 /* no cpu counter - sorry */
501                 do_gettimeoffset = null_gettimeoffset;
502         } else if (mips_counter_frequency != 0) {
503                 /* we have cpu counter and know counter frequency! */
504                 do_gettimeoffset = fixed_rate_gettimeoffset;
505         } else if ((current_cpu_data.isa_level == MIPS_CPU_ISA_M32) ||
506                    (current_cpu_data.isa_level == MIPS_CPU_ISA_I) ||
507                    (current_cpu_data.isa_level == MIPS_CPU_ISA_II) ) {
508                 /* we need to calibrate the counter but we don't have
509                  * 64-bit division. */
510                 do_gettimeoffset = calibrate_div32_gettimeoffset;
511         } else {
512                 /* we need to calibrate the counter but we *do* have
513                  * 64-bit division. */
514                 do_gettimeoffset = calibrate_div64_gettimeoffset;
515         }
516
517         /* caclulate cache parameters */
518         if (mips_counter_frequency) {
519                 cycles_per_jiffy = mips_counter_frequency / HZ;
520
521                 /* sll32_usecs_per_cycle = 10^6 * 2^32 / mips_counter_freq */
522                 /* any better way to do this? */
523                 sll32_usecs_per_cycle = mips_counter_frequency / 100000;
524                 sll32_usecs_per_cycle = 0xffffffff / sll32_usecs_per_cycle;
525                 sll32_usecs_per_cycle *= 10;
526
527                 /*
528                  * For those using cpu counter as timer,  this sets up the
529                  * first interrupt
530                  */
531                 write_c0_compare(cycles_per_jiffy);
532                 write_c0_count(0);
533                 expirelo = cycles_per_jiffy;
534         }
535
536         /*
537          * Call board specific timer interrupt setup.
538          *
539          * this pointer must be setup in machine setup routine.
540          *
541          * Even if the machine choose to use low-level timer interrupt,
542          * it still needs to setup the timer_irqaction.
543          * In that case, it might be better to set timer_irqaction.handler
544          * to be NULL function so that we are sure the high-level code
545          * is not invoked accidentally.
546          */
547         board_timer_setup(&timer_irqaction);
548 }
549
550 #define FEBRUARY                2
551 #define STARTOFTIME             1970
552 #define SECDAY                  86400L
553 #define SECYR                   (SECDAY * 365)
554 #define leapyear(y)             ((!((y) % 4) && ((y) % 100)) || !((y) % 400))
555 #define days_in_year(y)         (leapyear(y) ? 366 : 365)
556 #define days_in_month(m)        (month_days[(m) - 1])
557
558 static int month_days[12] = {
559         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
560 };
561
562 void to_tm(unsigned long tim, struct rtc_time *tm)
563 {
564         long hms, day, gday;
565         int i;
566
567         gday = day = tim / SECDAY;
568         hms = tim % SECDAY;
569
570         /* Hours, minutes, seconds are easy */
571         tm->tm_hour = hms / 3600;
572         tm->tm_min = (hms % 3600) / 60;
573         tm->tm_sec = (hms % 3600) % 60;
574
575         /* Number of years in days */
576         for (i = STARTOFTIME; day >= days_in_year(i); i++)
577                 day -= days_in_year(i);
578         tm->tm_year = i;
579
580         /* Number of months in days left */
581         if (leapyear(tm->tm_year))
582                 days_in_month(FEBRUARY) = 29;
583         for (i = 1; day >= days_in_month(i); i++)
584                 day -= days_in_month(i);
585         days_in_month(FEBRUARY) = 28;
586         tm->tm_mon = i - 1;             /* tm_mon starts from 0 to 11 */
587
588         /* Days are what is left over (+1) from all that. */
589         tm->tm_mday = day + 1;
590
591         /*
592          * Determine the day of week
593          */
594         tm->tm_wday = (gday + 4) % 7;   /* 1970/1/1 was Thursday */
595 }
596
597 EXPORT_SYMBOL(rtc_lock);
598 EXPORT_SYMBOL(to_tm);
599 EXPORT_SYMBOL(rtc_set_time);
600 EXPORT_SYMBOL(rtc_get_time);