alpha: Reorganize rtc handling
[linux-drm-fsl-dcu.git] / arch / alpha / kernel / time.c
1 /*
2  *  linux/arch/alpha/kernel/time.c
3  *
4  *  Copyright (C) 1991, 1992, 1995, 1999, 2000  Linus Torvalds
5  *
6  * This file contains the clocksource time handling.
7  * 1997-09-10   Updated NTP code according to technical memorandum Jan '96
8  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
9  * 1997-01-09    Adrian Sun
10  *      use interval timer if CONFIG_RTC=y
11  * 1997-10-29    John Bowman (bowman@math.ualberta.ca)
12  *      fixed tick loss calculation in timer_interrupt
13  *      (round system clock to nearest tick instead of truncating)
14  *      fixed algorithm in time_init for getting time from CMOS clock
15  * 1999-04-16   Thorsten Kranzkowski (dl8bcu@gmx.net)
16  *      fixed algorithm in do_gettimeofday() for calculating the precise time
17  *      from processor cycle counter (now taking lost_ticks into account)
18  * 2003-06-03   R. Scott Bailey <scott.bailey@eds.com>
19  *      Tighten sanity in time_init from 1% (10,000 PPM) to 250 PPM
20  */
21 #include <linux/errno.h>
22 #include <linux/module.h>
23 #include <linux/sched.h>
24 #include <linux/kernel.h>
25 #include <linux/param.h>
26 #include <linux/string.h>
27 #include <linux/mm.h>
28 #include <linux/delay.h>
29 #include <linux/ioport.h>
30 #include <linux/irq.h>
31 #include <linux/interrupt.h>
32 #include <linux/init.h>
33 #include <linux/bcd.h>
34 #include <linux/profile.h>
35 #include <linux/irq_work.h>
36
37 #include <asm/uaccess.h>
38 #include <asm/io.h>
39 #include <asm/hwrpb.h>
40
41 #include <linux/mc146818rtc.h>
42 #include <linux/time.h>
43 #include <linux/timex.h>
44 #include <linux/clocksource.h>
45
46 #include "proto.h"
47 #include "irq_impl.h"
48
49 DEFINE_SPINLOCK(rtc_lock);
50 EXPORT_SYMBOL(rtc_lock);
51
52 #define TICK_SIZE (tick_nsec / 1000)
53
54 /*
55  * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
56  * by 48 gives us 16 bits for HZ while keeping the accuracy good even
57  * for large CPU clock rates.
58  */
59 #define FIX_SHIFT       48
60
61 /* lump static variables together for more efficient access: */
62 static struct {
63         /* cycle counter last time it got invoked */
64         __u32 last_time;
65         /* ticks/cycle * 2^48 */
66         unsigned long scaled_ticks_per_cycle;
67         /* partial unused tick */
68         unsigned long partial_tick;
69 } state;
70
71 unsigned long est_cycle_freq;
72
73 #ifdef CONFIG_IRQ_WORK
74
75 DEFINE_PER_CPU(u8, irq_work_pending);
76
77 #define set_irq_work_pending_flag()  __get_cpu_var(irq_work_pending) = 1
78 #define test_irq_work_pending()      __get_cpu_var(irq_work_pending)
79 #define clear_irq_work_pending()     __get_cpu_var(irq_work_pending) = 0
80
81 void arch_irq_work_raise(void)
82 {
83         set_irq_work_pending_flag();
84 }
85
86 #else  /* CONFIG_IRQ_WORK */
87
88 #define test_irq_work_pending()      0
89 #define clear_irq_work_pending()
90
91 #endif /* CONFIG_IRQ_WORK */
92
93
94 static inline __u32 rpcc(void)
95 {
96         return __builtin_alpha_rpcc();
97 }
98
99 /*
100  * timer_interrupt() needs to keep up the real-time clock,
101  * as well as call the "xtime_update()" routine every clocktick
102  */
103 irqreturn_t timer_interrupt(int irq, void *dev)
104 {
105         unsigned long delta;
106         __u32 now;
107         long nticks;
108
109 #ifndef CONFIG_SMP
110         /* Not SMP, do kernel PC profiling here.  */
111         profile_tick(CPU_PROFILING);
112 #endif
113
114         /*
115          * Calculate how many ticks have passed since the last update,
116          * including any previous partial leftover.  Save any resulting
117          * fraction for the next pass.
118          */
119         now = rpcc();
120         delta = now - state.last_time;
121         state.last_time = now;
122         delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
123         state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1); 
124         nticks = delta >> FIX_SHIFT;
125
126         if (nticks)
127                 xtime_update(nticks);
128
129         if (test_irq_work_pending()) {
130                 clear_irq_work_pending();
131                 irq_work_run();
132         }
133
134 #ifndef CONFIG_SMP
135         while (nticks--)
136                 update_process_times(user_mode(get_irq_regs()));
137 #endif
138
139         return IRQ_HANDLED;
140 }
141
142 void __init
143 common_init_rtc(void)
144 {
145         unsigned char x, sel = 0;
146
147         /* Reset periodic interrupt frequency.  */
148 #if CONFIG_HZ == 1024 || CONFIG_HZ == 1200
149         x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
150         /* Test includes known working values on various platforms
151            where 0x26 is wrong; we refuse to change those. */
152         if (x != 0x26 && x != 0x25 && x != 0x19 && x != 0x06) {
153                 sel = RTC_REF_CLCK_32KHZ + 6;
154         }
155 #elif CONFIG_HZ == 256 || CONFIG_HZ == 128 || CONFIG_HZ == 64 || CONFIG_HZ == 32
156         sel = RTC_REF_CLCK_32KHZ + __builtin_ffs(32768 / CONFIG_HZ);
157 #else
158 # error "Unknown HZ from arch/alpha/Kconfig"
159 #endif
160         if (sel) {
161                 printk(KERN_INFO "Setting RTC_FREQ to %d Hz (%x)\n",
162                        CONFIG_HZ, sel);
163                 CMOS_WRITE(sel, RTC_FREQ_SELECT);
164         }
165
166         /* Turn on periodic interrupts.  */
167         x = CMOS_READ(RTC_CONTROL);
168         if (!(x & RTC_PIE)) {
169                 printk("Turning on RTC interrupts.\n");
170                 x |= RTC_PIE;
171                 x &= ~(RTC_AIE | RTC_UIE);
172                 CMOS_WRITE(x, RTC_CONTROL);
173         }
174         (void) CMOS_READ(RTC_INTR_FLAGS);
175
176         outb(0x36, 0x43);       /* pit counter 0: system timer */
177         outb(0x00, 0x40);
178         outb(0x00, 0x40);
179
180         outb(0xb6, 0x43);       /* pit counter 2: speaker */
181         outb(0x31, 0x42);
182         outb(0x13, 0x42);
183
184         init_rtc_irq();
185 }
186
187 /* Validate a computed cycle counter result against the known bounds for
188    the given processor core.  There's too much brokenness in the way of
189    timing hardware for any one method to work everywhere.  :-(
190
191    Return 0 if the result cannot be trusted, otherwise return the argument.  */
192
193 static unsigned long __init
194 validate_cc_value(unsigned long cc)
195 {
196         static struct bounds {
197                 unsigned int min, max;
198         } cpu_hz[] __initdata = {
199                 [EV3_CPU]    = {   50000000,  200000000 },      /* guess */
200                 [EV4_CPU]    = {  100000000,  300000000 },
201                 [LCA4_CPU]   = {  100000000,  300000000 },      /* guess */
202                 [EV45_CPU]   = {  200000000,  300000000 },
203                 [EV5_CPU]    = {  250000000,  433000000 },
204                 [EV56_CPU]   = {  333000000,  667000000 },
205                 [PCA56_CPU]  = {  400000000,  600000000 },      /* guess */
206                 [PCA57_CPU]  = {  500000000,  600000000 },      /* guess */
207                 [EV6_CPU]    = {  466000000,  600000000 },
208                 [EV67_CPU]   = {  600000000,  750000000 },
209                 [EV68AL_CPU] = {  750000000,  940000000 },
210                 [EV68CB_CPU] = { 1000000000, 1333333333 },
211                 /* None of the following are shipping as of 2001-11-01.  */
212                 [EV68CX_CPU] = { 1000000000, 1700000000 },      /* guess */
213                 [EV69_CPU]   = { 1000000000, 1700000000 },      /* guess */
214                 [EV7_CPU]    = {  800000000, 1400000000 },      /* guess */
215                 [EV79_CPU]   = { 1000000000, 2000000000 },      /* guess */
216         };
217
218         /* Allow for some drift in the crystal.  10MHz is more than enough.  */
219         const unsigned int deviation = 10000000;
220
221         struct percpu_struct *cpu;
222         unsigned int index;
223
224         cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
225         index = cpu->type & 0xffffffff;
226
227         /* If index out of bounds, no way to validate.  */
228         if (index >= ARRAY_SIZE(cpu_hz))
229                 return cc;
230
231         /* If index contains no data, no way to validate.  */
232         if (cpu_hz[index].max == 0)
233                 return cc;
234
235         if (cc < cpu_hz[index].min - deviation
236             || cc > cpu_hz[index].max + deviation)
237                 return 0;
238
239         return cc;
240 }
241
242
243 /*
244  * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
245  * arch/i386/time.c.
246  */
247
248 #define CALIBRATE_LATCH 0xffff
249 #define TIMEOUT_COUNT   0x100000
250
251 static unsigned long __init
252 calibrate_cc_with_pit(void)
253 {
254         int cc, count = 0;
255
256         /* Set the Gate high, disable speaker */
257         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
258
259         /*
260          * Now let's take care of CTC channel 2
261          *
262          * Set the Gate high, program CTC channel 2 for mode 0,
263          * (interrupt on terminal count mode), binary count,
264          * load 5 * LATCH count, (LSB and MSB) to begin countdown.
265          */
266         outb(0xb0, 0x43);               /* binary, mode 0, LSB/MSB, Ch 2 */
267         outb(CALIBRATE_LATCH & 0xff, 0x42);     /* LSB of count */
268         outb(CALIBRATE_LATCH >> 8, 0x42);       /* MSB of count */
269
270         cc = rpcc();
271         do {
272                 count++;
273         } while ((inb(0x61) & 0x20) == 0 && count < TIMEOUT_COUNT);
274         cc = rpcc() - cc;
275
276         /* Error: ECTCNEVERSET or ECPUTOOFAST.  */
277         if (count <= 1 || count == TIMEOUT_COUNT)
278                 return 0;
279
280         return ((long)cc * PIT_TICK_RATE) / (CALIBRATE_LATCH + 1);
281 }
282
283 /* The Linux interpretation of the CMOS clock register contents:
284    When the Update-In-Progress (UIP) flag goes from 1 to 0, the
285    RTC registers show the second which has precisely just started.
286    Let's hope other operating systems interpret the RTC the same way.  */
287
288 static unsigned long __init
289 rpcc_after_update_in_progress(void)
290 {
291         do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
292         do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
293
294         return rpcc();
295 }
296
297 #ifndef CONFIG_SMP
298 /* Until and unless we figure out how to get cpu cycle counters
299    in sync and keep them there, we can't use the rpcc.  */
300 static cycle_t read_rpcc(struct clocksource *cs)
301 {
302         cycle_t ret = (cycle_t)rpcc();
303         return ret;
304 }
305
306 static struct clocksource clocksource_rpcc = {
307         .name                   = "rpcc",
308         .rating                 = 300,
309         .read                   = read_rpcc,
310         .mask                   = CLOCKSOURCE_MASK(32),
311         .flags                  = CLOCK_SOURCE_IS_CONTINUOUS
312 };
313
314 static inline void register_rpcc_clocksource(long cycle_freq)
315 {
316         clocksource_register_hz(&clocksource_rpcc, cycle_freq);
317 }
318 #else /* !CONFIG_SMP */
319 static inline void register_rpcc_clocksource(long cycle_freq)
320 {
321 }
322 #endif /* !CONFIG_SMP */
323
324 void __init
325 time_init(void)
326 {
327         unsigned int cc1, cc2;
328         unsigned long cycle_freq, tolerance;
329         long diff;
330
331         /* Calibrate CPU clock -- attempt #1.  */
332         if (!est_cycle_freq)
333                 est_cycle_freq = validate_cc_value(calibrate_cc_with_pit());
334
335         cc1 = rpcc();
336
337         /* Calibrate CPU clock -- attempt #2.  */
338         if (!est_cycle_freq) {
339                 cc1 = rpcc_after_update_in_progress();
340                 cc2 = rpcc_after_update_in_progress();
341                 est_cycle_freq = validate_cc_value(cc2 - cc1);
342                 cc1 = cc2;
343         }
344
345         cycle_freq = hwrpb->cycle_freq;
346         if (est_cycle_freq) {
347                 /* If the given value is within 250 PPM of what we calculated,
348                    accept it.  Otherwise, use what we found.  */
349                 tolerance = cycle_freq / 4000;
350                 diff = cycle_freq - est_cycle_freq;
351                 if (diff < 0)
352                         diff = -diff;
353                 if ((unsigned long)diff > tolerance) {
354                         cycle_freq = est_cycle_freq;
355                         printk("HWRPB cycle frequency bogus.  "
356                                "Estimated %lu Hz\n", cycle_freq);
357                 } else {
358                         est_cycle_freq = 0;
359                 }
360         } else if (! validate_cc_value (cycle_freq)) {
361                 printk("HWRPB cycle frequency bogus, "
362                        "and unable to estimate a proper value!\n");
363         }
364
365         /* From John Bowman <bowman@math.ualberta.ca>: allow the values
366            to settle, as the Update-In-Progress bit going low isn't good
367            enough on some hardware.  2ms is our guess; we haven't found 
368            bogomips yet, but this is close on a 500Mhz box.  */
369         __delay(1000000);
370
371
372         if (HZ > (1<<16)) {
373                 extern void __you_loose (void);
374                 __you_loose();
375         }
376
377         register_rpcc_clocksource(cycle_freq);
378
379         state.last_time = cc1;
380         state.scaled_ticks_per_cycle
381                 = ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
382         state.partial_tick = 0L;
383
384         /* Startup the timer source. */
385         alpha_mv.init_rtc();
386 }