File: /usr/src/linux/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      */
28     #include <linux/config.h>
29     #include <linux/errno.h>
30     #include <linux/sched.h>
31     #include <linux/kernel.h>
32     #include <linux/param.h>
33     #include <linux/string.h>
34     #include <linux/mm.h>
35     #include <linux/delay.h>
36     #include <linux/ioport.h>
37     #include <linux/irq.h>
38     #include <linux/interrupt.h>
39     #include <linux/init.h>
40     
41     #include <asm/uaccess.h>
42     #include <asm/io.h>
43     #include <asm/hwrpb.h>
44     
45     #include <linux/mc146818rtc.h>
46     #include <linux/timex.h>
47     
48     #include "proto.h"
49     #include "irq_impl.h"
50     
51     extern rwlock_t xtime_lock;
52     extern unsigned long wall_jiffies;	/* kernel/timer.c */
53     
54     static int set_rtc_mmss(unsigned long);
55     
56     spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
57     
58     /*
59      * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
60      * by 48 gives us 16 bits for HZ while keeping the accuracy good even
61      * for large CPU clock rates.
62      */
63     #define FIX_SHIFT	48
64     
65     /* lump static variables together for more efficient access: */
66     static struct {
67     	/* cycle counter last time it got invoked */
68     	__u32 last_time;
69     	/* ticks/cycle * 2^48 */
70     	unsigned long scaled_ticks_per_cycle;
71     	/* last time the CMOS clock got updated */
72     	time_t last_rtc_update;
73     	/* partial unused tick */
74     	unsigned long partial_tick;
75     } state;
76     
77     unsigned long est_cycle_freq;
78     
79     
80     static inline __u32 rpcc(void)
81     {
82         __u32 result;
83         asm volatile ("rpcc %0" : "=r"(result));
84         return result;
85     }
86     
87     
88     /*
89      * timer_interrupt() needs to keep up the real-time clock,
90      * as well as call the "do_timer()" routine every clocktick
91      */
92     void timer_interrupt(int irq, void *dev, struct pt_regs * regs)
93     {
94     	unsigned long delta;
95     	__u32 now;
96     	long nticks;
97     
98     #ifndef CONFIG_SMP
99     	/* Not SMP, do kernel PC profiling here.  */
100     	if (!user_mode(regs))
101     		alpha_do_profile(regs->pc);
102     #endif
103     
104     	write_lock(&xtime_lock);
105     
106     	/*
107     	 * Calculate how many ticks have passed since the last update,
108     	 * including any previous partial leftover.  Save any resulting
109     	 * fraction for the next pass.
110     	 */
111     	now = rpcc();
112     	delta = now - state.last_time;
113     	state.last_time = now;
114     	delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
115     	state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1); 
116     	nticks = delta >> FIX_SHIFT;
117     
118     	while (nticks > 0) {
119     		do_timer(regs);
120     		nticks--;
121     	}
122     
123     	/*
124     	 * If we have an externally synchronized Linux clock, then update
125     	 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
126     	 * called as close as possible to 500 ms before the new second starts.
127     	 */
128     	if ((time_status & STA_UNSYNC) == 0
129     	    && xtime.tv_sec > state.last_rtc_update + 660
130     	    && xtime.tv_usec >= 500000 - ((unsigned) tick) / 2
131     	    && xtime.tv_usec <= 500000 + ((unsigned) tick) / 2) {
132     		int tmp = set_rtc_mmss(xtime.tv_sec);
133     		state.last_rtc_update = xtime.tv_sec - (tmp ? 600 : 0);
134     	}
135     
136     	write_unlock(&xtime_lock);
137     }
138     
139     void
140     common_init_rtc(void)
141     {
142     	unsigned char x;
143     
144     	/* Reset periodic interrupt frequency.  */
145     	x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
146     	if (x != 0x26 && x != 0x19 && x != 0x06) {
147     		printk("Setting RTC_FREQ to 1024 Hz (%x)\n", x);
148     		CMOS_WRITE(0x26, RTC_FREQ_SELECT);
149     	}
150     
151     	/* Turn on periodic interrupts.  */
152     	x = CMOS_READ(RTC_CONTROL);
153     	if (!(x & RTC_PIE)) {
154     		printk("Turning on RTC interrupts.\n");
155     		x |= RTC_PIE;
156     		x &= ~(RTC_AIE | RTC_UIE);
157     		CMOS_WRITE(x, RTC_CONTROL);
158     	}
159     	(void) CMOS_READ(RTC_INTR_FLAGS);
160     
161     	outb(0x36, 0x43);	/* pit counter 0: system timer */
162     	outb(0x00, 0x40);
163     	outb(0x00, 0x40);
164     
165     	outb(0xb6, 0x43);	/* pit counter 2: speaker */
166     	outb(0x31, 0x42);
167     	outb(0x13, 0x42);
168     
169     	init_rtc_irq();
170     }
171     
172     /*
173      * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
174      * arch/i386/time.c.
175      */
176     
177     #define CALIBRATE_LATCH	(52 * LATCH)
178     #define CALIBRATE_TIME	(52 * 1000020 / HZ)
179     
180     static unsigned long __init
181     calibrate_cc_with_pic(void)
182     {
183     	int cc;
184     	unsigned long count = 0;
185     
186     	/* Set the Gate high, disable speaker */
187     	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
188     
189     	/*
190     	 * Now let's take care of CTC channel 2
191     	 *
192     	 * Set the Gate high, program CTC channel 2 for mode 0,
193     	 * (interrupt on terminal count mode), binary count,
194     	 * load 5 * LATCH count, (LSB and MSB) to begin countdown.
195     	 */
196     	outb(0xb0, 0x43);		/* binary, mode 0, LSB/MSB, Ch 2 */
197     	outb(CALIBRATE_LATCH & 0xff, 0x42);	/* LSB of count */
198     	outb(CALIBRATE_LATCH >> 8, 0x42);	/* MSB of count */
199     
200     	cc = rpcc();
201     	do {
202     		count++;
203     	} while ((inb(0x61) & 0x20) == 0);
204     	cc = rpcc() - cc;
205     
206     	/* Error: ECTCNEVERSET */
207     	if (count <= 1)
208     		goto bad_ctc;
209     
210     	/* Error: ECPUTOOFAST */
211     	if (count >> 32)
212     		goto bad_ctc;
213     
214     	/* Error: ECPUTOOSLOW */
215     	if (cc <= CALIBRATE_TIME)
216     		goto bad_ctc;
217     
218     	return ((long)cc * 1000000) / CALIBRATE_TIME;
219     
220     	/*
221     	 * The CTC wasn't reliable: we got a hit on the very first read,
222     	 * or the CPU was so fast/slow that the quotient wouldn't fit in
223     	 * 32 bits..
224     	 */
225      bad_ctc:
226     	return 0;
227     }
228     
229     /* The Linux interpretation of the CMOS clock register contents:
230        When the Update-In-Progress (UIP) flag goes from 1 to 0, the
231        RTC registers show the second which has precisely just started.
232        Let's hope other operating systems interpret the RTC the same way.  */
233     
234     static unsigned long __init
235     rpcc_after_update_in_progress(void)
236     {
237     	do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
238     	do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
239     
240     	return rpcc();
241     }
242     
243     void __init
244     time_init(void)
245     {
246     	unsigned int year, mon, day, hour, min, sec, cc1, cc2, epoch;
247     	unsigned long cycle_freq, one_percent;
248     	long diff;
249     
250     	/* Calibrate CPU clock -- attempt #1.  */
251     	if (!est_cycle_freq)
252     		est_cycle_freq = calibrate_cc_with_pic();
253     
254     	cc1 = rpcc_after_update_in_progress();
255     
256     	/* Calibrate CPU clock -- attempt #2.  */
257     	if (!est_cycle_freq) {
258     		cc2 = rpcc_after_update_in_progress();
259     		est_cycle_freq = cc2 - cc1;
260     		cc1 = cc2;
261     	}
262     
263     	/* If the given value is within 1% of what we calculated, 
264     	   accept it.  Otherwise, use what we found.  */
265     	cycle_freq = hwrpb->cycle_freq;
266     	one_percent = cycle_freq / 100;
267     	diff = cycle_freq - est_cycle_freq;
268     	if (diff < 0)
269     		diff = -diff;
270     	if (diff > one_percent) {
271     		cycle_freq = est_cycle_freq;
272     		printk("HWRPB cycle frequency bogus.  Estimated %lu Hz\n",
273     		       cycle_freq);
274     	}
275     	else {
276     		est_cycle_freq = 0;
277     	}
278     
279     	/* From John Bowman <bowman@math.ualberta.ca>: allow the values
280     	   to settle, as the Update-In-Progress bit going low isn't good
281     	   enough on some hardware.  2ms is our guess; we havn't found 
282     	   bogomips yet, but this is close on a 500Mhz box.  */
283     	__delay(1000000);
284     
285     	sec = CMOS_READ(RTC_SECONDS);
286     	min = CMOS_READ(RTC_MINUTES);
287     	hour = CMOS_READ(RTC_HOURS);
288     	day = CMOS_READ(RTC_DAY_OF_MONTH);
289     	mon = CMOS_READ(RTC_MONTH);
290     	year = CMOS_READ(RTC_YEAR);
291     
292     	if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
293     		BCD_TO_BIN(sec);
294     		BCD_TO_BIN(min);
295     		BCD_TO_BIN(hour);
296     		BCD_TO_BIN(day);
297     		BCD_TO_BIN(mon);
298     		BCD_TO_BIN(year);
299     	}
300     
301     	/* PC-like is standard; used for year < 20 || year >= 70 */
302     	epoch = 1900;
303     	if (year < 20)
304     		epoch = 2000;
305     	else if (year >= 20 && year < 48)
306     		/* NT epoch */
307     		epoch = 1980;
308     	else if (year >= 48 && year < 70)
309     		/* Digital UNIX epoch */
310     		epoch = 1952;
311     
312     	printk(KERN_INFO "Using epoch = %d\n", epoch);
313     
314     	if ((year += epoch) < 1970)
315     		year += 100;
316     
317     	xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
318     	xtime.tv_usec = 0;
319     
320     	if (HZ > (1<<16)) {
321     		extern void __you_loose (void);
322     		__you_loose();
323     	}
324     
325     	state.last_time = cc1;
326     	state.scaled_ticks_per_cycle
327     		= ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
328     	state.last_rtc_update = 0;
329     	state.partial_tick = 0L;
330     
331     	/* Startup the timer source. */
332     	alpha_mv.init_rtc();
333     
334     	do_get_fast_time = do_gettimeofday;
335     }
336     
337     /*
338      * Use the cycle counter to estimate an displacement from the last time
339      * tick.  Unfortunately the Alpha designers made only the low 32-bits of
340      * the cycle counter active, so we overflow on 8.2 seconds on a 500MHz
341      * part.  So we can't do the "find absolute time in terms of cycles" thing
342      * that the other ports do.
343      */
344     void
345     do_gettimeofday(struct timeval *tv)
346     {
347     	unsigned long sec, usec, lost, flags;
348     	unsigned long delta_cycles, delta_usec, partial_tick;
349     
350     	read_lock_irqsave(&xtime_lock, flags);
351     
352     	delta_cycles = rpcc() - state.last_time;
353     	sec = xtime.tv_sec;
354     	usec = xtime.tv_usec;
355     	partial_tick = state.partial_tick;
356     	lost = jiffies - wall_jiffies;
357     
358     	read_unlock_irqrestore(&xtime_lock, flags);
359     
360     #ifdef CONFIG_SMP
361     	/* Until and unless we figure out how to get cpu cycle counters
362     	   in sync and keep them there, we can't use the rpcc tricks.  */
363     	delta_usec = lost * (1000000 / HZ);
364     #else
365     	/*
366     	 * usec = cycles * ticks_per_cycle * 2**48 * 1e6 / (2**48 * ticks)
367     	 *	= cycles * (s_t_p_c) * 1e6 / (2**48 * ticks)
368     	 *	= cycles * (s_t_p_c) * 15625 / (2**42 * ticks)
369     	 *
370     	 * which, given a 600MHz cycle and a 1024Hz tick, has a
371     	 * dynamic range of about 1.7e17, which is less than the
372     	 * 1.8e19 in an unsigned long, so we are safe from overflow.
373     	 *
374     	 * Round, but with .5 up always, since .5 to even is harder
375     	 * with no clear gain.
376     	 */
377     
378     	delta_usec = (delta_cycles * state.scaled_ticks_per_cycle 
379     		      + partial_tick
380     		      + (lost << FIX_SHIFT)) * 15625;
381     	delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
382     #endif
383     
384     	usec += delta_usec;
385     	if (usec >= 1000000) {
386     		sec += 1;
387     		usec -= 1000000;
388     	}
389     
390     	tv->tv_sec = sec;
391     	tv->tv_usec = usec;
392     }
393     
394     void
395     do_settimeofday(struct timeval *tv)
396     {
397     	unsigned long delta_usec;
398     	long sec, usec;
399     	
400     	write_lock_irq(&xtime_lock);
401     
402     	/* The offset that is added into time in do_gettimeofday above
403     	   must be subtracted out here to keep a coherent view of the
404     	   time.  Without this, a full-tick error is possible.  */
405     
406     #ifdef CONFIG_SMP
407     	delta_usec = (jiffies - wall_jiffies) * (1000000 / HZ);
408     #else
409     	delta_usec = rpcc() - state.last_time;
410     	delta_usec = (delta_usec * state.scaled_ticks_per_cycle 
411     		      + state.partial_tick
412     		      + ((jiffies - wall_jiffies) << FIX_SHIFT)) * 15625;
413     	delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
414     #endif
415     
416     	sec = tv->tv_sec;
417     	usec = tv->tv_usec;
418     	usec -= delta_usec;
419     	if (usec < 0) {
420     		usec += 1000000;
421     		sec -= 1;
422     	}
423     
424     	xtime.tv_sec = sec;
425     	xtime.tv_usec = usec;
426     	time_adjust = 0;		/* stop active adjtime() */
427     	time_status |= STA_UNSYNC;
428     	time_maxerror = NTP_PHASE_LIMIT;
429     	time_esterror = NTP_PHASE_LIMIT;
430     
431     	write_unlock_irq(&xtime_lock);
432     }
433     
434     
435     /*
436      * In order to set the CMOS clock precisely, set_rtc_mmss has to be
437      * called 500 ms after the second nowtime has started, because when
438      * nowtime is written into the registers of the CMOS clock, it will
439      * jump to the next second precisely 500 ms later. Check the Motorola
440      * MC146818A or Dallas DS12887 data sheet for details.
441      *
442      * BUG: This routine does not handle hour overflow properly; it just
443      *      sets the minutes. Usually you won't notice until after reboot!
444      */
445     
446     extern int abs(int);
447     
448     static int
449     set_rtc_mmss(unsigned long nowtime)
450     {
451     	int retval = 0;
452     	int real_seconds, real_minutes, cmos_minutes;
453     	unsigned char save_control, save_freq_select;
454     
455     	/* irq are locally disabled here */
456     	spin_lock(&rtc_lock);
457     	/* Tell the clock it's being set */
458     	save_control = CMOS_READ(RTC_CONTROL);
459     	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
460     
461     	/* Stop and reset prescaler */
462     	save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
463     	CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
464     
465     	cmos_minutes = CMOS_READ(RTC_MINUTES);
466     	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
467     		BCD_TO_BIN(cmos_minutes);
468     
469     	/*
470     	 * since we're only adjusting minutes and seconds,
471     	 * don't interfere with hour overflow. This avoids
472     	 * messing with unknown time zones but requires your
473     	 * RTC not to be off by more than 15 minutes
474     	 */
475     	real_seconds = nowtime % 60;
476     	real_minutes = nowtime / 60;
477     	if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
478     		/* correct for half hour time zone */
479     		real_minutes += 30;
480     	}
481     	real_minutes %= 60;
482     
483     	if (abs(real_minutes - cmos_minutes) < 30) {
484     		if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
485     			BIN_TO_BCD(real_seconds);
486     			BIN_TO_BCD(real_minutes);
487     		}
488     		CMOS_WRITE(real_seconds,RTC_SECONDS);
489     		CMOS_WRITE(real_minutes,RTC_MINUTES);
490     	} else {
491     		printk(KERN_WARNING
492     		       "set_rtc_mmss: can't update from %d to %d\n",
493     		       cmos_minutes, real_minutes);
494      		retval = -1;
495     	}
496     
497     	/* The following flags have to be released exactly in this order,
498     	 * otherwise the DS12887 (popular MC146818A clone with integrated
499     	 * battery and quartz) will not reset the oscillator and will not
500     	 * update precisely 500 ms later. You won't find this mentioned in
501     	 * the Dallas Semiconductor data sheets, but who believes data
502     	 * sheets anyway ...                           -- Markus Kuhn
503     	 */
504     	CMOS_WRITE(save_control, RTC_CONTROL);
505     	CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
506     	spin_unlock(&rtc_lock);
507     
508     	return retval;
509     }
510