Merge branch 'drm-forlinus' of git://git.kernel.org/pub/scm/linux/kernel/git/airlied...
[pandora-kernel.git] / arch / sh64 / kernel / time.c
1 /*
2  * This file is subject to the terms and conditions of the GNU General Public
3  * License.  See the file "COPYING" in the main directory of this archive
4  * for more details.
5  *
6  * arch/sh64/kernel/time.c
7  *
8  * Copyright (C) 2000, 2001  Paolo Alberelli
9  * Copyright (C) 2003, 2004  Paul Mundt
10  * Copyright (C) 2003  Richard Curnow
11  *
12  *    Original TMU/RTC code taken from sh version.
13  *    Copyright (C) 1999  Tetsuya Okada & Niibe Yutaka
14  *      Some code taken from i386 version.
15  *      Copyright (C) 1991, 1992, 1995  Linus Torvalds
16  */
17
18 #include <linux/config.h>
19 #include <linux/errno.h>
20 #include <linux/rwsem.h>
21 #include <linux/sched.h>
22 #include <linux/kernel.h>
23 #include <linux/param.h>
24 #include <linux/string.h>
25 #include <linux/mm.h>
26 #include <linux/interrupt.h>
27 #include <linux/time.h>
28 #include <linux/delay.h>
29 #include <linux/init.h>
30 #include <linux/profile.h>
31 #include <linux/smp.h>
32
33 #include <asm/registers.h>       /* required by inline __asm__ stmt. */
34
35 #include <asm/processor.h>
36 #include <asm/uaccess.h>
37 #include <asm/io.h>
38 #include <asm/irq.h>
39 #include <asm/delay.h>
40
41 #include <linux/timex.h>
42 #include <linux/irq.h>
43 #include <asm/hardware.h>
44
45 #define TMU_TOCR_INIT   0x00
46 #define TMU0_TCR_INIT   0x0020
47 #define TMU_TSTR_INIT   1
48 #define TMU_TSTR_OFF    0
49
50 /* RCR1 Bits */
51 #define RCR1_CF         0x80    /* Carry Flag             */
52 #define RCR1_CIE        0x10    /* Carry Interrupt Enable */
53 #define RCR1_AIE        0x08    /* Alarm Interrupt Enable */
54 #define RCR1_AF         0x01    /* Alarm Flag             */
55
56 /* RCR2 Bits */
57 #define RCR2_PEF        0x80    /* PEriodic interrupt Flag */
58 #define RCR2_PESMASK    0x70    /* Periodic interrupt Set  */
59 #define RCR2_RTCEN      0x08    /* ENable RTC              */
60 #define RCR2_ADJ        0x04    /* ADJustment (30-second)  */
61 #define RCR2_RESET      0x02    /* Reset bit               */
62 #define RCR2_START      0x01    /* Start bit               */
63
64 /* Clock, Power and Reset Controller */
65 #define CPRC_BLOCK_OFF  0x01010000
66 #define CPRC_BASE       PHYS_PERIPHERAL_BLOCK + CPRC_BLOCK_OFF
67
68 #define FRQCR           (cprc_base+0x0)
69 #define WTCSR           (cprc_base+0x0018)
70 #define STBCR           (cprc_base+0x0030)
71
72 /* Time Management Unit */
73 #define TMU_BLOCK_OFF   0x01020000
74 #define TMU_BASE        PHYS_PERIPHERAL_BLOCK + TMU_BLOCK_OFF
75 #define TMU0_BASE       tmu_base + 0x8 + (0xc * 0x0)
76 #define TMU1_BASE       tmu_base + 0x8 + (0xc * 0x1)
77 #define TMU2_BASE       tmu_base + 0x8 + (0xc * 0x2)
78
79 #define TMU_TOCR        tmu_base+0x0    /* Byte access */
80 #define TMU_TSTR        tmu_base+0x4    /* Byte access */
81
82 #define TMU0_TCOR       TMU0_BASE+0x0   /* Long access */
83 #define TMU0_TCNT       TMU0_BASE+0x4   /* Long access */
84 #define TMU0_TCR        TMU0_BASE+0x8   /* Word access */
85
86 /* Real Time Clock */
87 #define RTC_BLOCK_OFF   0x01040000
88 #define RTC_BASE        PHYS_PERIPHERAL_BLOCK + RTC_BLOCK_OFF
89
90 #define R64CNT          rtc_base+0x00
91 #define RSECCNT         rtc_base+0x04
92 #define RMINCNT         rtc_base+0x08
93 #define RHRCNT          rtc_base+0x0c
94 #define RWKCNT          rtc_base+0x10
95 #define RDAYCNT         rtc_base+0x14
96 #define RMONCNT         rtc_base+0x18
97 #define RYRCNT          rtc_base+0x1c   /* 16bit */
98 #define RSECAR          rtc_base+0x20
99 #define RMINAR          rtc_base+0x24
100 #define RHRAR           rtc_base+0x28
101 #define RWKAR           rtc_base+0x2c
102 #define RDAYAR          rtc_base+0x30
103 #define RMONAR          rtc_base+0x34
104 #define RCR1            rtc_base+0x38
105 #define RCR2            rtc_base+0x3c
106
107 #ifndef BCD_TO_BIN
108 #define BCD_TO_BIN(val) ((val)=((val)&15) + ((val)>>4)*10)
109 #endif
110
111 #ifndef BIN_TO_BCD
112 #define BIN_TO_BCD(val) ((val)=(((val)/10)<<4) + (val)%10)
113 #endif
114
115 #define TICK_SIZE (tick_nsec / 1000)
116
117 extern unsigned long wall_jiffies;
118
119 static unsigned long tmu_base, rtc_base;
120 unsigned long cprc_base;
121
122 /* Variables to allow interpolation of time of day to resolution better than a
123  * jiffy. */
124
125 /* This is effectively protected by xtime_lock */
126 static unsigned long ctc_last_interrupt;
127 static unsigned long long usecs_per_jiffy = 1000000/HZ; /* Approximation */
128
129 #define CTC_JIFFY_SCALE_SHIFT 40
130
131 /* 2**CTC_JIFFY_SCALE_SHIFT / ctc_ticks_per_jiffy */
132 static unsigned long long scaled_recip_ctc_ticks_per_jiffy;
133
134 /* Estimate number of microseconds that have elapsed since the last timer tick,
135    by scaling the delta that has occured in the CTC register.
136
137    WARNING WARNING WARNING : This algorithm relies on the CTC decrementing at
138    the CPU clock rate.  If the CPU sleeps, the CTC stops counting.  Bear this
139    in mind if enabling SLEEP_WORKS in process.c.  In that case, this algorithm
140    probably needs to use TMU.TCNT0 instead.  This will work even if the CPU is
141    sleeping, though will be coarser.
142
143    FIXME : What if usecs_per_tick is moving around too much, e.g. if an adjtime
144    is running or if the freq or tick arguments of adjtimex are modified after
145    we have calibrated the scaling factor?  This will result in either a jump at
146    the end of a tick period, or a wrap backwards at the start of the next one,
147    if the application is reading the time of day often enough.  I think we
148    ought to do better than this.  For this reason, usecs_per_jiffy is left
149    separated out in the calculation below.  This allows some future hook into
150    the adjtime-related stuff in kernel/timer.c to remove this hazard.
151
152 */
153
154 static unsigned long usecs_since_tick(void)
155 {
156         unsigned long long current_ctc;
157         long ctc_ticks_since_interrupt;
158         unsigned long long ull_ctc_ticks_since_interrupt;
159         unsigned long result;
160
161         unsigned long long mul1_out;
162         unsigned long long mul1_out_high;
163         unsigned long long mul2_out_low, mul2_out_high;
164
165         /* Read CTC register */
166         asm ("getcon cr62, %0" : "=r" (current_ctc));
167         /* Note, the CTC counts down on each CPU clock, not up.
168            Note(2), use long type to get correct wraparound arithmetic when
169            the counter crosses zero. */
170         ctc_ticks_since_interrupt = (long) ctc_last_interrupt - (long) current_ctc;
171         ull_ctc_ticks_since_interrupt = (unsigned long long) ctc_ticks_since_interrupt;
172
173         /* Inline assembly to do 32x32x32->64 multiplier */
174         asm volatile ("mulu.l %1, %2, %0" :
175              "=r" (mul1_out) :
176              "r" (ull_ctc_ticks_since_interrupt), "r" (usecs_per_jiffy));
177
178         mul1_out_high = mul1_out >> 32;
179
180         asm volatile ("mulu.l %1, %2, %0" :
181              "=r" (mul2_out_low) :
182              "r" (mul1_out), "r" (scaled_recip_ctc_ticks_per_jiffy));
183
184 #if 1
185         asm volatile ("mulu.l %1, %2, %0" :
186              "=r" (mul2_out_high) :
187              "r" (mul1_out_high), "r" (scaled_recip_ctc_ticks_per_jiffy));
188 #endif
189
190         result = (unsigned long) (((mul2_out_high << 32) + mul2_out_low) >> CTC_JIFFY_SCALE_SHIFT);
191
192         return result;
193 }
194
195 void do_gettimeofday(struct timeval *tv)
196 {
197         unsigned long flags;
198         unsigned long seq;
199         unsigned long usec, sec;
200
201         do {
202                 seq = read_seqbegin_irqsave(&xtime_lock, flags);
203                 usec = usecs_since_tick();
204                 {
205                         unsigned long lost = jiffies - wall_jiffies;
206
207                         if (lost)
208                                 usec += lost * (1000000 / HZ);
209                 }
210
211                 sec = xtime.tv_sec;
212                 usec += xtime.tv_nsec / 1000;
213         } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
214
215         while (usec >= 1000000) {
216                 usec -= 1000000;
217                 sec++;
218         }
219
220         tv->tv_sec = sec;
221         tv->tv_usec = usec;
222 }
223
224 int do_settimeofday(struct timespec *tv)
225 {
226         time_t wtm_sec, sec = tv->tv_sec;
227         long wtm_nsec, nsec = tv->tv_nsec;
228
229         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
230                 return -EINVAL;
231
232         write_seqlock_irq(&xtime_lock);
233         /*
234          * This is revolting. We need to set "xtime" correctly. However, the
235          * value in this location is the value at the most recent update of
236          * wall time.  Discover what correction gettimeofday() would have
237          * made, and then undo it!
238          */
239         nsec -= 1000 * (usecs_since_tick() +
240                                 (jiffies - wall_jiffies) * (1000000 / HZ));
241
242         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
243         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
244
245         set_normalized_timespec(&xtime, sec, nsec);
246         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
247
248         ntp_clear();
249         write_sequnlock_irq(&xtime_lock);
250         clock_was_set();
251
252         return 0;
253 }
254 EXPORT_SYMBOL(do_settimeofday);
255
256 static int set_rtc_time(unsigned long nowtime)
257 {
258         int retval = 0;
259         int real_seconds, real_minutes, cmos_minutes;
260
261         ctrl_outb(RCR2_RESET, RCR2);  /* Reset pre-scaler & stop RTC */
262
263         cmos_minutes = ctrl_inb(RMINCNT);
264         BCD_TO_BIN(cmos_minutes);
265
266         /*
267          * since we're only adjusting minutes and seconds,
268          * don't interfere with hour overflow. This avoids
269          * messing with unknown time zones but requires your
270          * RTC not to be off by more than 15 minutes
271          */
272         real_seconds = nowtime % 60;
273         real_minutes = nowtime / 60;
274         if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1)
275                 real_minutes += 30;     /* correct for half hour time zone */
276         real_minutes %= 60;
277
278         if (abs(real_minutes - cmos_minutes) < 30) {
279                 BIN_TO_BCD(real_seconds);
280                 BIN_TO_BCD(real_minutes);
281                 ctrl_outb(real_seconds, RSECCNT);
282                 ctrl_outb(real_minutes, RMINCNT);
283         } else {
284                 printk(KERN_WARNING
285                        "set_rtc_time: can't update from %d to %d\n",
286                        cmos_minutes, real_minutes);
287                 retval = -1;
288         }
289
290         ctrl_outb(RCR2_RTCEN|RCR2_START, RCR2);  /* Start RTC */
291
292         return retval;
293 }
294
295 /* last time the RTC clock got updated */
296 static long last_rtc_update = 0;
297
298 /*
299  * timer_interrupt() needs to keep up the real-time clock,
300  * as well as call the "do_timer()" routine every clocktick
301  */
302 static inline void do_timer_interrupt(int irq, struct pt_regs *regs)
303 {
304         unsigned long long current_ctc;
305         asm ("getcon cr62, %0" : "=r" (current_ctc));
306         ctc_last_interrupt = (unsigned long) current_ctc;
307
308         do_timer(regs);
309 #ifndef CONFIG_SMP
310         update_process_times(user_mode(regs));
311 #endif
312         profile_tick(CPU_PROFILING, regs);
313
314 #ifdef CONFIG_HEARTBEAT
315         {
316                 extern void heartbeat(void);
317
318                 heartbeat();
319         }
320 #endif
321
322         /*
323          * If we have an externally synchronized Linux clock, then update
324          * RTC clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
325          * called as close as possible to 500 ms before the new second starts.
326          */
327         if (ntp_synced() &&
328             xtime.tv_sec > last_rtc_update + 660 &&
329             (xtime.tv_nsec / 1000) >= 500000 - ((unsigned) TICK_SIZE) / 2 &&
330             (xtime.tv_nsec / 1000) <= 500000 + ((unsigned) TICK_SIZE) / 2) {
331                 if (set_rtc_time(xtime.tv_sec) == 0)
332                         last_rtc_update = xtime.tv_sec;
333                 else
334                         last_rtc_update = xtime.tv_sec - 600; /* do it again in 60 s */
335         }
336 }
337
338 /*
339  * This is the same as the above, except we _also_ save the current
340  * Time Stamp Counter value at the time of the timer interrupt, so that
341  * we later on can estimate the time of day more exactly.
342  */
343 static irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs *regs)
344 {
345         unsigned long timer_status;
346
347         /* Clear UNF bit */
348         timer_status = ctrl_inw(TMU0_TCR);
349         timer_status &= ~0x100;
350         ctrl_outw(timer_status, TMU0_TCR);
351
352         /*
353          * Here we are in the timer irq handler. We just have irqs locally
354          * disabled but we don't know if the timer_bh is running on the other
355          * CPU. We need to avoid to SMP race with it. NOTE: we don' t need
356          * the irq version of write_lock because as just said we have irq
357          * locally disabled. -arca
358          */
359         write_lock(&xtime_lock);
360         do_timer_interrupt(irq, regs);
361         write_unlock(&xtime_lock);
362
363         return IRQ_HANDLED;
364 }
365
366 static unsigned long get_rtc_time(void)
367 {
368         unsigned int sec, min, hr, wk, day, mon, yr, yr100;
369
370  again:
371         do {
372                 ctrl_outb(0, RCR1);  /* Clear CF-bit */
373                 sec = ctrl_inb(RSECCNT);
374                 min = ctrl_inb(RMINCNT);
375                 hr  = ctrl_inb(RHRCNT);
376                 wk  = ctrl_inb(RWKCNT);
377                 day = ctrl_inb(RDAYCNT);
378                 mon = ctrl_inb(RMONCNT);
379                 yr  = ctrl_inw(RYRCNT);
380                 yr100 = (yr >> 8);
381                 yr &= 0xff;
382         } while ((ctrl_inb(RCR1) & RCR1_CF) != 0);
383
384         BCD_TO_BIN(yr100);
385         BCD_TO_BIN(yr);
386         BCD_TO_BIN(mon);
387         BCD_TO_BIN(day);
388         BCD_TO_BIN(hr);
389         BCD_TO_BIN(min);
390         BCD_TO_BIN(sec);
391
392         if (yr > 99 || mon < 1 || mon > 12 || day > 31 || day < 1 ||
393             hr > 23 || min > 59 || sec > 59) {
394                 printk(KERN_ERR
395                        "SH RTC: invalid value, resetting to 1 Jan 2000\n");
396                 ctrl_outb(RCR2_RESET, RCR2);  /* Reset & Stop */
397                 ctrl_outb(0, RSECCNT);
398                 ctrl_outb(0, RMINCNT);
399                 ctrl_outb(0, RHRCNT);
400                 ctrl_outb(6, RWKCNT);
401                 ctrl_outb(1, RDAYCNT);
402                 ctrl_outb(1, RMONCNT);
403                 ctrl_outw(0x2000, RYRCNT);
404                 ctrl_outb(RCR2_RTCEN|RCR2_START, RCR2);  /* Start */
405                 goto again;
406         }
407
408         return mktime(yr100 * 100 + yr, mon, day, hr, min, sec);
409 }
410
411 static __init unsigned int get_cpu_hz(void)
412 {
413         unsigned int count;
414         unsigned long __dummy;
415         unsigned long ctc_val_init, ctc_val;
416
417         /*
418         ** Regardless the toolchain, force the compiler to use the
419         ** arbitrary register r3 as a clock tick counter.
420         ** NOTE: r3 must be in accordance with sh64_rtc_interrupt()
421         */
422         register unsigned long long  __rtc_irq_flag __asm__ ("r3");
423
424         local_irq_enable();
425         do {} while (ctrl_inb(R64CNT) != 0);
426         ctrl_outb(RCR1_CIE, RCR1); /* Enable carry interrupt */
427
428         /*
429          * r3 is arbitrary. CDC does not support "=z".
430          */
431         ctc_val_init = 0xffffffff;
432         ctc_val = ctc_val_init;
433
434         asm volatile("gettr     tr0, %1\n\t"
435                      "putcon    %0, " __CTC "\n\t"
436                      "and       %2, r63, %2\n\t"
437                      "pta       $+4, tr0\n\t"
438                      "beq/l     %2, r63, tr0\n\t"
439                      "ptabs     %1, tr0\n\t"
440                      "getcon    " __CTC ", %0\n\t"
441                 : "=r"(ctc_val), "=r" (__dummy), "=r" (__rtc_irq_flag)
442                 : "0" (0));
443         local_irq_disable();
444         /*
445          * SH-3:
446          * CPU clock = 4 stages * loop
447          * tst    rm,rm      if id ex
448          * bt/s   1b            if id ex
449          * add    #1,rd            if id ex
450          *                            (if) pipe line stole
451          * tst    rm,rm                  if id ex
452          * ....
453          *
454          *
455          * SH-4:
456          * CPU clock = 6 stages * loop
457          * I don't know why.
458          * ....
459          *
460          * SH-5:
461          * Use CTC register to count.  This approach returns the right value
462          * even if the I-cache is disabled (e.g. whilst debugging.)
463          *
464          */
465
466         count = ctc_val_init - ctc_val; /* CTC counts down */
467
468 #if defined (CONFIG_SH_SIMULATOR)
469         /*
470          * Let's pretend we are a 5MHz SH-5 to avoid a too
471          * little timer interval. Also to keep delay
472          * calibration within a reasonable time.
473          */
474         return 5000000;
475 #else
476         /*
477          * This really is count by the number of clock cycles
478          * by the ratio between a complete R64CNT
479          * wrap-around (128) and CUI interrupt being raised (64).
480          */
481         return count*2;
482 #endif
483 }
484
485 static irqreturn_t sh64_rtc_interrupt(int irq, void *dev_id,
486                                       struct pt_regs *regs)
487 {
488         ctrl_outb(0, RCR1);     /* Disable Carry Interrupts */
489         regs->regs[3] = 1;      /* Using r3 */
490
491         return IRQ_HANDLED;
492 }
493
494 static struct irqaction irq0  = { timer_interrupt, SA_INTERRUPT, CPU_MASK_NONE, "timer", NULL, NULL};
495 static struct irqaction irq1  = { sh64_rtc_interrupt, SA_INTERRUPT, CPU_MASK_NONE, "rtc", NULL, NULL};
496
497 void __init time_init(void)
498 {
499         unsigned int cpu_clock, master_clock, bus_clock, module_clock;
500         unsigned long interval;
501         unsigned long frqcr, ifc, pfc;
502         static int ifc_table[] = { 2, 4, 6, 8, 10, 12, 16, 24 };
503 #define bfc_table ifc_table     /* Same */
504 #define pfc_table ifc_table     /* Same */
505
506         tmu_base = onchip_remap(TMU_BASE, 1024, "TMU");
507         if (!tmu_base) {
508                 panic("Unable to remap TMU\n");
509         }
510
511         rtc_base = onchip_remap(RTC_BASE, 1024, "RTC");
512         if (!rtc_base) {
513                 panic("Unable to remap RTC\n");
514         }
515
516         cprc_base = onchip_remap(CPRC_BASE, 1024, "CPRC");
517         if (!cprc_base) {
518                 panic("Unable to remap CPRC\n");
519         }
520
521         xtime.tv_sec = get_rtc_time();
522         xtime.tv_nsec = 0;
523
524         setup_irq(TIMER_IRQ, &irq0);
525         setup_irq(RTC_IRQ, &irq1);
526
527         /* Check how fast it is.. */
528         cpu_clock = get_cpu_hz();
529
530         /* Note careful order of operations to maintain reasonable precision and avoid overflow. */
531         scaled_recip_ctc_ticks_per_jiffy = ((1ULL << CTC_JIFFY_SCALE_SHIFT) / (unsigned long long)(cpu_clock / HZ));
532
533         disable_irq(RTC_IRQ);
534
535         printk("CPU clock: %d.%02dMHz\n",
536                (cpu_clock / 1000000), (cpu_clock % 1000000)/10000);
537         {
538                 unsigned short bfc;
539                 frqcr = ctrl_inl(FRQCR);
540                 ifc  = ifc_table[(frqcr>> 6) & 0x0007];
541                 bfc  = bfc_table[(frqcr>> 3) & 0x0007];
542                 pfc  = pfc_table[(frqcr>> 12) & 0x0007];
543                 master_clock = cpu_clock * ifc;
544                 bus_clock = master_clock/bfc;
545         }
546
547         printk("Bus clock: %d.%02dMHz\n",
548                (bus_clock/1000000), (bus_clock % 1000000)/10000);
549         module_clock = master_clock/pfc;
550         printk("Module clock: %d.%02dMHz\n",
551                (module_clock/1000000), (module_clock % 1000000)/10000);
552         interval = (module_clock/(HZ*4));
553
554         printk("Interval = %ld\n", interval);
555
556         current_cpu_data.cpu_clock    = cpu_clock;
557         current_cpu_data.master_clock = master_clock;
558         current_cpu_data.bus_clock    = bus_clock;
559         current_cpu_data.module_clock = module_clock;
560
561         /* Start TMU0 */
562         ctrl_outb(TMU_TSTR_OFF, TMU_TSTR);
563         ctrl_outb(TMU_TOCR_INIT, TMU_TOCR);
564         ctrl_outw(TMU0_TCR_INIT, TMU0_TCR);
565         ctrl_outl(interval, TMU0_TCOR);
566         ctrl_outl(interval, TMU0_TCNT);
567         ctrl_outb(TMU_TSTR_INIT, TMU_TSTR);
568 }
569
570 void enter_deep_standby(void)
571 {
572         /* Disable watchdog timer */
573         ctrl_outl(0xa5000000, WTCSR);
574         /* Configure deep standby on sleep */
575         ctrl_outl(0x03, STBCR);
576
577 #ifdef CONFIG_SH_ALPHANUMERIC
578         {
579                 extern void mach_alphanum(int position, unsigned char value);
580                 extern void mach_alphanum_brightness(int setting);
581                 char halted[] = "Halted. ";
582                 int i;
583                 mach_alphanum_brightness(6); /* dimmest setting above off */
584                 for (i=0; i<8; i++) {
585                         mach_alphanum(i, halted[i]);
586                 }
587                 asm __volatile__ ("synco");
588         }
589 #endif
590
591         asm __volatile__ ("sleep");
592         asm __volatile__ ("synci");
593         asm __volatile__ ("nop");
594         asm __volatile__ ("nop");
595         asm __volatile__ ("nop");
596         asm __volatile__ ("nop");
597         panic("Unexpected wakeup!\n");
598 }
599
600 /*
601  * Scheduler clock - returns current time in nanosec units.
602  */
603 unsigned long long sched_clock(void)
604 {
605         return (unsigned long long)jiffies * (1000000000 / HZ);
606 }
607