alpha: Allow HZ to be configured
[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 PC-specific time handling details:
7  * reading the RTC at bootup, etc..
8  * 1994-07-02    Alan Modra
9  *      fixed set_rtc_mmss, fixed time.year for >= 2000, new mktime
10  * 1995-03-26    Markus Kuhn
11  *      fixed 500 ms bug at call to set_rtc_mmss, fixed DS12887
12  *      precision CMOS clock update
13  * 1997-09-10   Updated NTP code according to technical memorandum Jan '96
14  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
15  * 1997-01-09    Adrian Sun
16  *      use interval timer if CONFIG_RTC=y
17  * 1997-10-29    John Bowman (bowman@math.ualberta.ca)
18  *      fixed tick loss calculation in timer_interrupt
19  *      (round system clock to nearest tick instead of truncating)
20  *      fixed algorithm in time_init for getting time from CMOS clock
21  * 1999-04-16   Thorsten Kranzkowski (dl8bcu@gmx.net)
22  *      fixed algorithm in do_gettimeofday() for calculating the precise time
23  *      from processor cycle counter (now taking lost_ticks into account)
24  * 2000-08-13   Jan-Benedict Glaw <jbglaw@lug-owl.de>
25  *      Fixed time_init to be aware of epoches != 1900. This prevents
26  *      booting up in 2048 for me;) Code is stolen from rtc.c.
27  * 2003-06-03   R. Scott Bailey <scott.bailey@eds.com>
28  *      Tighten sanity in time_init from 1% (10,000 PPM) to 250 PPM
29  */
30 #include <linux/errno.h>
31 #include <linux/module.h>
32 #include <linux/sched.h>
33 #include <linux/kernel.h>
34 #include <linux/param.h>
35 #include <linux/string.h>
36 #include <linux/mm.h>
37 #include <linux/delay.h>
38 #include <linux/ioport.h>
39 #include <linux/irq.h>
40 #include <linux/interrupt.h>
41 #include <linux/init.h>
42 #include <linux/bcd.h>
43 #include <linux/profile.h>
44 #include <linux/irq_work.h>
45
46 #include <asm/uaccess.h>
47 #include <asm/io.h>
48 #include <asm/hwrpb.h>
49 #include <asm/rtc.h>
50
51 #include <linux/mc146818rtc.h>
52 #include <linux/time.h>
53 #include <linux/timex.h>
54 #include <linux/clocksource.h>
55
56 #include "proto.h"
57 #include "irq_impl.h"
58
59 static int set_rtc_mmss(unsigned long);
60
61 DEFINE_SPINLOCK(rtc_lock);
62 EXPORT_SYMBOL(rtc_lock);
63
64 #define TICK_SIZE (tick_nsec / 1000)
65
66 /*
67  * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
68  * by 48 gives us 16 bits for HZ while keeping the accuracy good even
69  * for large CPU clock rates.
70  */
71 #define FIX_SHIFT       48
72
73 /* lump static variables together for more efficient access: */
74 static struct {
75         /* cycle counter last time it got invoked */
76         __u32 last_time;
77         /* ticks/cycle * 2^48 */
78         unsigned long scaled_ticks_per_cycle;
79         /* partial unused tick */
80         unsigned long partial_tick;
81 } state;
82
83 unsigned long est_cycle_freq;
84
85 #ifdef CONFIG_IRQ_WORK
86
87 DEFINE_PER_CPU(u8, irq_work_pending);
88
89 #define set_irq_work_pending_flag()  __get_cpu_var(irq_work_pending) = 1
90 #define test_irq_work_pending()      __get_cpu_var(irq_work_pending)
91 #define clear_irq_work_pending()     __get_cpu_var(irq_work_pending) = 0
92
93 void arch_irq_work_raise(void)
94 {
95         set_irq_work_pending_flag();
96 }
97
98 #else  /* CONFIG_IRQ_WORK */
99
100 #define test_irq_work_pending()      0
101 #define clear_irq_work_pending()
102
103 #endif /* CONFIG_IRQ_WORK */
104
105
106 static inline __u32 rpcc(void)
107 {
108         return __builtin_alpha_rpcc();
109 }
110
111 int update_persistent_clock(struct timespec now)
112 {
113         return set_rtc_mmss(now.tv_sec);
114 }
115
116 void read_persistent_clock(struct timespec *ts)
117 {
118         unsigned int year, mon, day, hour, min, sec, epoch;
119
120         sec = CMOS_READ(RTC_SECONDS);
121         min = CMOS_READ(RTC_MINUTES);
122         hour = CMOS_READ(RTC_HOURS);
123         day = CMOS_READ(RTC_DAY_OF_MONTH);
124         mon = CMOS_READ(RTC_MONTH);
125         year = CMOS_READ(RTC_YEAR);
126
127         if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
128                 sec = bcd2bin(sec);
129                 min = bcd2bin(min);
130                 hour = bcd2bin(hour);
131                 day = bcd2bin(day);
132                 mon = bcd2bin(mon);
133                 year = bcd2bin(year);
134         }
135
136         /* PC-like is standard; used for year >= 70 */
137         epoch = 1900;
138         if (year < 20)
139                 epoch = 2000;
140         else if (year >= 20 && year < 48)
141                 /* NT epoch */
142                 epoch = 1980;
143         else if (year >= 48 && year < 70)
144                 /* Digital UNIX epoch */
145                 epoch = 1952;
146
147         printk(KERN_INFO "Using epoch = %d\n", epoch);
148
149         if ((year += epoch) < 1970)
150                 year += 100;
151
152         ts->tv_sec = mktime(year, mon, day, hour, min, sec);
153         ts->tv_nsec = 0;
154 }
155
156
157
158 /*
159  * timer_interrupt() needs to keep up the real-time clock,
160  * as well as call the "xtime_update()" routine every clocktick
161  */
162 irqreturn_t timer_interrupt(int irq, void *dev)
163 {
164         unsigned long delta;
165         __u32 now;
166         long nticks;
167
168 #ifndef CONFIG_SMP
169         /* Not SMP, do kernel PC profiling here.  */
170         profile_tick(CPU_PROFILING);
171 #endif
172
173         /*
174          * Calculate how many ticks have passed since the last update,
175          * including any previous partial leftover.  Save any resulting
176          * fraction for the next pass.
177          */
178         now = rpcc();
179         delta = now - state.last_time;
180         state.last_time = now;
181         delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
182         state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1); 
183         nticks = delta >> FIX_SHIFT;
184
185         if (nticks)
186                 xtime_update(nticks);
187
188         if (test_irq_work_pending()) {
189                 clear_irq_work_pending();
190                 irq_work_run();
191         }
192
193 #ifndef CONFIG_SMP
194         while (nticks--)
195                 update_process_times(user_mode(get_irq_regs()));
196 #endif
197
198         return IRQ_HANDLED;
199 }
200
201 void __init
202 common_init_rtc(void)
203 {
204         unsigned char x, sel = 0;
205
206         /* Reset periodic interrupt frequency.  */
207 #if CONFIG_HZ == 1024 || CONFIG_HZ == 1200
208         x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
209         /* Test includes known working values on various platforms
210            where 0x26 is wrong; we refuse to change those. */
211         if (x != 0x26 && x != 0x25 && x != 0x19 && x != 0x06) {
212                 sel = RTC_REF_CLCK_32KHZ + 6;
213         }
214 #elif CONFIG_HZ == 256 || CONFIG_HZ == 128 || CONFIG_HZ == 64 || CONFIG_HZ == 32
215         sel = RTC_REF_CLCK_32KHZ + __builtin_ffs(32768 / CONFIG_HZ);
216 #else
217 # error "Unknown HZ from arch/alpha/Kconfig"
218 #endif
219         if (sel) {
220                 printk(KERN_INFO "Setting RTC_FREQ to %d Hz (%x)\n",
221                        CONFIG_HZ, sel);
222                 CMOS_WRITE(sel, RTC_FREQ_SELECT);
223         }
224
225         /* Turn on periodic interrupts.  */
226         x = CMOS_READ(RTC_CONTROL);
227         if (!(x & RTC_PIE)) {
228                 printk("Turning on RTC interrupts.\n");
229                 x |= RTC_PIE;
230                 x &= ~(RTC_AIE | RTC_UIE);
231                 CMOS_WRITE(x, RTC_CONTROL);
232         }
233         (void) CMOS_READ(RTC_INTR_FLAGS);
234
235         outb(0x36, 0x43);       /* pit counter 0: system timer */
236         outb(0x00, 0x40);
237         outb(0x00, 0x40);
238
239         outb(0xb6, 0x43);       /* pit counter 2: speaker */
240         outb(0x31, 0x42);
241         outb(0x13, 0x42);
242
243         init_rtc_irq();
244 }
245
246 unsigned int common_get_rtc_time(struct rtc_time *time)
247 {
248         return __get_rtc_time(time);
249 }
250
251 int common_set_rtc_time(struct rtc_time *time)
252 {
253         return __set_rtc_time(time);
254 }
255
256 /* Validate a computed cycle counter result against the known bounds for
257    the given processor core.  There's too much brokenness in the way of
258    timing hardware for any one method to work everywhere.  :-(
259
260    Return 0 if the result cannot be trusted, otherwise return the argument.  */
261
262 static unsigned long __init
263 validate_cc_value(unsigned long cc)
264 {
265         static struct bounds {
266                 unsigned int min, max;
267         } cpu_hz[] __initdata = {
268                 [EV3_CPU]    = {   50000000,  200000000 },      /* guess */
269                 [EV4_CPU]    = {  100000000,  300000000 },
270                 [LCA4_CPU]   = {  100000000,  300000000 },      /* guess */
271                 [EV45_CPU]   = {  200000000,  300000000 },
272                 [EV5_CPU]    = {  250000000,  433000000 },
273                 [EV56_CPU]   = {  333000000,  667000000 },
274                 [PCA56_CPU]  = {  400000000,  600000000 },      /* guess */
275                 [PCA57_CPU]  = {  500000000,  600000000 },      /* guess */
276                 [EV6_CPU]    = {  466000000,  600000000 },
277                 [EV67_CPU]   = {  600000000,  750000000 },
278                 [EV68AL_CPU] = {  750000000,  940000000 },
279                 [EV68CB_CPU] = { 1000000000, 1333333333 },
280                 /* None of the following are shipping as of 2001-11-01.  */
281                 [EV68CX_CPU] = { 1000000000, 1700000000 },      /* guess */
282                 [EV69_CPU]   = { 1000000000, 1700000000 },      /* guess */
283                 [EV7_CPU]    = {  800000000, 1400000000 },      /* guess */
284                 [EV79_CPU]   = { 1000000000, 2000000000 },      /* guess */
285         };
286
287         /* Allow for some drift in the crystal.  10MHz is more than enough.  */
288         const unsigned int deviation = 10000000;
289
290         struct percpu_struct *cpu;
291         unsigned int index;
292
293         cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
294         index = cpu->type & 0xffffffff;
295
296         /* If index out of bounds, no way to validate.  */
297         if (index >= ARRAY_SIZE(cpu_hz))
298                 return cc;
299
300         /* If index contains no data, no way to validate.  */
301         if (cpu_hz[index].max == 0)
302                 return cc;
303
304         if (cc < cpu_hz[index].min - deviation
305             || cc > cpu_hz[index].max + deviation)
306                 return 0;
307
308         return cc;
309 }
310
311
312 /*
313  * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
314  * arch/i386/time.c.
315  */
316
317 #define CALIBRATE_LATCH 0xffff
318 #define TIMEOUT_COUNT   0x100000
319
320 static unsigned long __init
321 calibrate_cc_with_pit(void)
322 {
323         int cc, count = 0;
324
325         /* Set the Gate high, disable speaker */
326         outb((inb(0x61) & ~0x02) | 0x01, 0x61);
327
328         /*
329          * Now let's take care of CTC channel 2
330          *
331          * Set the Gate high, program CTC channel 2 for mode 0,
332          * (interrupt on terminal count mode), binary count,
333          * load 5 * LATCH count, (LSB and MSB) to begin countdown.
334          */
335         outb(0xb0, 0x43);               /* binary, mode 0, LSB/MSB, Ch 2 */
336         outb(CALIBRATE_LATCH & 0xff, 0x42);     /* LSB of count */
337         outb(CALIBRATE_LATCH >> 8, 0x42);       /* MSB of count */
338
339         cc = rpcc();
340         do {
341                 count++;
342         } while ((inb(0x61) & 0x20) == 0 && count < TIMEOUT_COUNT);
343         cc = rpcc() - cc;
344
345         /* Error: ECTCNEVERSET or ECPUTOOFAST.  */
346         if (count <= 1 || count == TIMEOUT_COUNT)
347                 return 0;
348
349         return ((long)cc * PIT_TICK_RATE) / (CALIBRATE_LATCH + 1);
350 }
351
352 /* The Linux interpretation of the CMOS clock register contents:
353    When the Update-In-Progress (UIP) flag goes from 1 to 0, the
354    RTC registers show the second which has precisely just started.
355    Let's hope other operating systems interpret the RTC the same way.  */
356
357 static unsigned long __init
358 rpcc_after_update_in_progress(void)
359 {
360         do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
361         do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
362
363         return rpcc();
364 }
365
366 #ifndef CONFIG_SMP
367 /* Until and unless we figure out how to get cpu cycle counters
368    in sync and keep them there, we can't use the rpcc.  */
369 static cycle_t read_rpcc(struct clocksource *cs)
370 {
371         cycle_t ret = (cycle_t)rpcc();
372         return ret;
373 }
374
375 static struct clocksource clocksource_rpcc = {
376         .name                   = "rpcc",
377         .rating                 = 300,
378         .read                   = read_rpcc,
379         .mask                   = CLOCKSOURCE_MASK(32),
380         .flags                  = CLOCK_SOURCE_IS_CONTINUOUS
381 };
382
383 static inline void register_rpcc_clocksource(long cycle_freq)
384 {
385         clocksource_register_hz(&clocksource_rpcc, cycle_freq);
386 }
387 #else /* !CONFIG_SMP */
388 static inline void register_rpcc_clocksource(long cycle_freq)
389 {
390 }
391 #endif /* !CONFIG_SMP */
392
393 void __init
394 time_init(void)
395 {
396         unsigned int cc1, cc2;
397         unsigned long cycle_freq, tolerance;
398         long diff;
399
400         /* Calibrate CPU clock -- attempt #1.  */
401         if (!est_cycle_freq)
402                 est_cycle_freq = validate_cc_value(calibrate_cc_with_pit());
403
404         cc1 = rpcc();
405
406         /* Calibrate CPU clock -- attempt #2.  */
407         if (!est_cycle_freq) {
408                 cc1 = rpcc_after_update_in_progress();
409                 cc2 = rpcc_after_update_in_progress();
410                 est_cycle_freq = validate_cc_value(cc2 - cc1);
411                 cc1 = cc2;
412         }
413
414         cycle_freq = hwrpb->cycle_freq;
415         if (est_cycle_freq) {
416                 /* If the given value is within 250 PPM of what we calculated,
417                    accept it.  Otherwise, use what we found.  */
418                 tolerance = cycle_freq / 4000;
419                 diff = cycle_freq - est_cycle_freq;
420                 if (diff < 0)
421                         diff = -diff;
422                 if ((unsigned long)diff > tolerance) {
423                         cycle_freq = est_cycle_freq;
424                         printk("HWRPB cycle frequency bogus.  "
425                                "Estimated %lu Hz\n", cycle_freq);
426                 } else {
427                         est_cycle_freq = 0;
428                 }
429         } else if (! validate_cc_value (cycle_freq)) {
430                 printk("HWRPB cycle frequency bogus, "
431                        "and unable to estimate a proper value!\n");
432         }
433
434         /* From John Bowman <bowman@math.ualberta.ca>: allow the values
435            to settle, as the Update-In-Progress bit going low isn't good
436            enough on some hardware.  2ms is our guess; we haven't found 
437            bogomips yet, but this is close on a 500Mhz box.  */
438         __delay(1000000);
439
440
441         if (HZ > (1<<16)) {
442                 extern void __you_loose (void);
443                 __you_loose();
444         }
445
446         register_rpcc_clocksource(cycle_freq);
447
448         state.last_time = cc1;
449         state.scaled_ticks_per_cycle
450                 = ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
451         state.partial_tick = 0L;
452
453         /* Startup the timer source. */
454         alpha_mv.init_rtc();
455 }
456
457 /*
458  * In order to set the CMOS clock precisely, set_rtc_mmss has to be
459  * called 500 ms after the second nowtime has started, because when
460  * nowtime is written into the registers of the CMOS clock, it will
461  * jump to the next second precisely 500 ms later. Check the Motorola
462  * MC146818A or Dallas DS12887 data sheet for details.
463  *
464  * BUG: This routine does not handle hour overflow properly; it just
465  *      sets the minutes. Usually you won't notice until after reboot!
466  */
467
468
469 static int
470 set_rtc_mmss(unsigned long nowtime)
471 {
472         int retval = 0;
473         int real_seconds, real_minutes, cmos_minutes;
474         unsigned char save_control, save_freq_select;
475
476         /* irq are locally disabled here */
477         spin_lock(&rtc_lock);
478         /* Tell the clock it's being set */
479         save_control = CMOS_READ(RTC_CONTROL);
480         CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
481
482         /* Stop and reset prescaler */
483         save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
484         CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
485
486         cmos_minutes = CMOS_READ(RTC_MINUTES);
487         if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
488                 cmos_minutes = bcd2bin(cmos_minutes);
489
490         /*
491          * since we're only adjusting minutes and seconds,
492          * don't interfere with hour overflow. This avoids
493          * messing with unknown time zones but requires your
494          * RTC not to be off by more than 15 minutes
495          */
496         real_seconds = nowtime % 60;
497         real_minutes = nowtime / 60;
498         if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
499                 /* correct for half hour time zone */
500                 real_minutes += 30;
501         }
502         real_minutes %= 60;
503
504         if (abs(real_minutes - cmos_minutes) < 30) {
505                 if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
506                         real_seconds = bin2bcd(real_seconds);
507                         real_minutes = bin2bcd(real_minutes);
508                 }
509                 CMOS_WRITE(real_seconds,RTC_SECONDS);
510                 CMOS_WRITE(real_minutes,RTC_MINUTES);
511         } else {
512                 printk_once(KERN_NOTICE
513                        "set_rtc_mmss: can't update from %d to %d\n",
514                        cmos_minutes, real_minutes);
515                 retval = -1;
516         }
517
518         /* The following flags have to be released exactly in this order,
519          * otherwise the DS12887 (popular MC146818A clone with integrated
520          * battery and quartz) will not reset the oscillator and will not
521          * update precisely 500 ms later. You won't find this mentioned in
522          * the Dallas Semiconductor data sheets, but who believes data
523          * sheets anyway ...                           -- Markus Kuhn
524          */
525         CMOS_WRITE(save_control, RTC_CONTROL);
526         CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
527         spin_unlock(&rtc_lock);
528
529         return retval;
530 }