File: /usr/src/linux/arch/mips/kernel/old-time.c

1     /*
2      * Copyright (C) 1991, 1992, 1995  Linus Torvalds
3      * Copyright (C) 1996 - 2000  Ralf Baechle
4      * Kevin D. Kissell, kevink@mips.com and Carsten Langgaard, carstenl@mips
5      * Copyright (C) 2000 MIPS Technologies, Inc.  All rights reserved.
6      *
7      * Don't use.  Deprecated.  Dead meat.
8      */
9     #include <linux/config.h>
10     #include <linux/errno.h>
11     #include <linux/init.h>
12     #include <linux/sched.h>
13     #include <linux/kernel.h>
14     #include <linux/param.h>
15     #include <linux/string.h>
16     #include <linux/mm.h>
17     #include <linux/interrupt.h>
18     #include <linux/kernel_stat.h>
19     
20     #include <asm/bootinfo.h>
21     #include <asm/cpu.h>
22     #include <asm/mipsregs.h>
23     #include <asm/io.h>
24     #include <asm/irq.h>
25     #include <asm/ddb5074.h>
26     
27     #include <linux/mc146818rtc.h>
28     #include <linux/timex.h>
29     
30     extern volatile unsigned long wall_jiffies;
31     unsigned long r4k_interval;
32     extern rwlock_t xtime_lock;
33     
34     /*
35      * Change this if you have some constant time drift
36      */
37     /* This is the value for the PC-style PICs. */
38     /* #define USECS_PER_JIFFY (1000020/HZ) */
39     
40     /* This is for machines which generate the exact clock. */
41     #define USECS_PER_JIFFY (1000000/HZ)
42     
43     /* Cycle counter value at the previous timer interrupt.. */
44     
45     static unsigned int timerhi, timerlo;
46     
47     /*
48      * On MIPS only R4000 and better have a cycle counter.
49      *
50      * FIXME: Does playing with the RP bit in c0_status interfere with this code?
51      */
52     static unsigned long do_fast_gettimeoffset(void)
53     {
54     	u32 count;
55     	unsigned long res, tmp;
56     
57     	/* Last jiffy when do_fast_gettimeoffset() was called. */
58     	static unsigned long last_jiffies;
59     	unsigned long quotient;
60     
61     	/*
62     	 * Cached "1/(clocks per usec)*2^32" value.
63     	 * It has to be recalculated once each jiffy.
64     	 */
65     	static unsigned long cached_quotient;
66     
67     	tmp = jiffies;
68     
69     	quotient = cached_quotient;
70     
71     	if (tmp && last_jiffies != tmp) {
72     		last_jiffies = tmp;
73     		__asm__(".set\tnoreorder\n\t"
74     			".set\tnoat\n\t"
75     			".set\tmips3\n\t"
76     			"lwu\t%0,%2\n\t"
77     			"dsll32\t$1,%1,0\n\t"
78     			"or\t$1,$1,%0\n\t"
79     			"ddivu\t$0,$1,%3\n\t"
80     			"mflo\t$1\n\t"
81     			"dsll32\t%0,%4,0\n\t"
82     			"nop\n\t"
83     			"ddivu\t$0,%0,$1\n\t"
84     			"mflo\t%0\n\t"
85     			".set\tmips0\n\t"
86     			".set\tat\n\t"
87     			".set\treorder"
88     			:"=&r" (quotient)
89     			:"r" (timerhi),
90     			 "m" (timerlo),
91     			 "r" (tmp),
92     			 "r" (USECS_PER_JIFFY)
93     			:"$1");
94     		cached_quotient = quotient;
95     	}
96     
97     	/* Get last timer tick in absolute kernel time */
98     	count = read_32bit_cp0_register(CP0_COUNT);
99     
100     	/* .. relative to previous jiffy (32 bits is enough) */
101     	count -= timerlo;
102     
103     	__asm__("multu\t%1,%2\n\t"
104     		"mfhi\t%0"
105     		:"=r" (res)
106     		:"r" (count),
107     		 "r" (quotient));
108     
109     	/*
110      	 * Due to possible jiffies inconsistencies, we need to check 
111     	 * the result so that we'll get a timer that is monotonic.
112     	 */
113     	if (res >= USECS_PER_JIFFY)
114     		res = USECS_PER_JIFFY-1;
115     
116     	return res;
117     }
118     
119     /* This function must be called with interrupts disabled 
120      * It was inspired by Steve McCanne's microtime-i386 for BSD.  -- jrs
121      * 
122      * However, the pc-audio speaker driver changes the divisor so that
123      * it gets interrupted rather more often - it loads 64 into the
124      * counter rather than 11932! This has an adverse impact on
125      * do_gettimeoffset() -- it stops working! What is also not
126      * good is that the interval that our timer function gets called
127      * is no longer 10.0002 ms, but 9.9767 ms. To get around this
128      * would require using a different timing source. Maybe someone
129      * could use the RTC - I know that this can interrupt at frequencies
130      * ranging from 8192Hz to 2Hz. If I had the energy, I'd somehow fix
131      * it so that at startup, the timer code in sched.c would select
132      * using either the RTC or the 8253 timer. The decision would be
133      * based on whether there was any other device around that needed
134      * to trample on the 8253. I'd set up the RTC to interrupt at 1024 Hz,
135      * and then do some jiggery to have a version of do_timer that 
136      * advanced the clock by 1/1024 s. Every time that reached over 1/100
137      * of a second, then do all the old code. If the time was kept correct
138      * then do_gettimeoffset could just return 0 - there is no low order
139      * divider that can be accessed.
140      *
141      * Ideally, you would be able to use the RTC for the speaker driver,
142      * but it appears that the speaker driver really needs interrupt more
143      * often than every 120 us or so.
144      *
145      * Anyway, this needs more thought....		pjsg (1993-08-28)
146      * 
147      * If you are really that interested, you should be reading
148      * comp.protocols.time.ntp!
149      */
150     
151     #define TICK_SIZE tick
152     
153     static unsigned long do_slow_gettimeoffset(void)
154     {
155     	int count;
156     
157     	static int count_p = LATCH;    /* for the first call after boot */
158     	static unsigned long jiffies_p;
159     
160     	/*
161     	 * cache volatile jiffies temporarily; we have IRQs turned off. 
162     	 */
163     	unsigned long jiffies_t;
164     
165     	/* timer count may underflow right here */
166     	outb_p(0x00, 0x43);	/* latch the count ASAP */
167     
168     	count = inb_p(0x40);	/* read the latched count */
169     
170     	/*
171     	 * We do this guaranteed double memory access instead of a _p 
172     	 * postfix in the previous port access. Wheee, hackady hack
173     	 */
174     	jiffies_t = jiffies;
175     
176     	count |= inb_p(0x40) << 8;
177     
178     	/*
179     	 * avoiding timer inconsistencies (they are rare, but they happen)...
180     	 * there are two kinds of problems that must be avoided here:
181     	 *  1. the timer counter underflows
182     	 *  2. hardware problem with the timer, not giving us continuous time,
183     	 *     the counter does small "jumps" upwards on some Pentium systems,
184     	 *     (see c't 95/10 page 335 for Neptun bug.)
185     	 */
186     
187     	if( jiffies_t == jiffies_p ) {
188     		if( count > count_p ) {
189     			/* the nutcase */
190     
191     			outb_p(0x0A, 0x20);
192     
193     			/* assumption about timer being IRQ1 */
194     			if (inb(0x20) & 0x01) {
195     				/*
196     				 * We cannot detect lost timer interrupts ... 
197     				 * well, that's why we call them lost, don't we? :)
198     				 * [hmm, on the Pentium and Alpha we can ... sort of]
199     				 */
200     				count -= LATCH;
201     			} else {
202     				printk("do_slow_gettimeoffset(): hardware timer problem?\n");
203     			}
204     		}
205     	} else
206     		jiffies_p = jiffies_t;
207     
208     	count_p = count;
209     
210     	count = ((LATCH-1) - count) * TICK_SIZE;
211     	count = (count + LATCH/2) / LATCH;
212     
213     	return count;
214     }
215     
216     static unsigned long (*do_gettimeoffset)(void) = do_slow_gettimeoffset;
217     
218     /*
219      * This version of gettimeofday has near microsecond resolution.
220      */
221     void do_gettimeofday(struct timeval *tv)
222     {
223     	unsigned long flags;
224     
225     	read_lock_irqsave (&xtime_lock, flags);
226     	*tv = xtime;
227     	tv->tv_usec += do_gettimeoffset();
228     
229     	/*
230     	 * xtime is atomically updated in timer_bh. jiffies - wall_jiffies
231     	 * is nonzero if the timer bottom half hasnt executed yet.
232     	 */
233     	if (jiffies - wall_jiffies)
234     		tv->tv_usec += USECS_PER_JIFFY;
235     
236     	read_unlock_irqrestore (&xtime_lock, flags);
237     
238     	if (tv->tv_usec >= 1000000) {
239     		tv->tv_usec -= 1000000;
240     		tv->tv_sec++;
241     	}
242     }
243     
244     void do_settimeofday(struct timeval *tv)
245     {
246     	write_lock_irq (&xtime_lock);
247     
248     	/* This is revolting. We need to set the xtime.tv_usec
249     	 * correctly. However, the value in this location is
250     	 * is value at the last tick.
251     	 * Discover what correction gettimeofday
252     	 * would have done, and then undo it!
253     	 */
254     	tv->tv_usec -= do_gettimeoffset();
255     
256     	if (tv->tv_usec < 0) {
257     		tv->tv_usec += 1000000;
258     		tv->tv_sec--;
259     	}
260     
261     	xtime = *tv;
262     	time_adjust = 0;		/* stop active adjtime() */
263     	time_status |= STA_UNSYNC;
264     	time_maxerror = NTP_PHASE_LIMIT;
265     	time_esterror = NTP_PHASE_LIMIT;
266     
267     	write_unlock_irq (&xtime_lock);
268     }
269     
270     /*
271      * In order to set the CMOS clock precisely, set_rtc_mmss has to be
272      * called 500 ms after the second nowtime has started, because when
273      * nowtime is written into the registers of the CMOS clock, it will
274      * jump to the next second precisely 500 ms later. Check the Motorola
275      * MC146818A or Dallas DS12887 data sheet for details.
276      *
277      * BUG: This routine does not handle hour overflow properly; it just
278      *      sets the minutes. Usually you won't notice until after reboot!
279      */
280     static int set_rtc_mmss(unsigned long nowtime)
281     {
282     	int retval = 0;
283     	int real_seconds, real_minutes, cmos_minutes;
284     	unsigned char save_control, save_freq_select;
285     
286     	save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being set */
287     	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
288     
289     	save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset prescaler */
290     	CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
291     
292     	cmos_minutes = CMOS_READ(RTC_MINUTES);
293     	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
294     		BCD_TO_BIN(cmos_minutes);
295     
296     	/*
297     	 * since we're only adjusting minutes and seconds,
298     	 * don't interfere with hour overflow. This avoids
299     	 * messing with unknown time zones but requires your
300     	 * RTC not to be off by more than 15 minutes
301     	 */
302     	real_seconds = nowtime % 60;
303     	real_minutes = nowtime / 60;
304     	if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1)
305     		real_minutes += 30;		/* correct for half hour time zone */
306     	real_minutes %= 60;
307     
308     	if (abs(real_minutes - cmos_minutes) < 30) {
309     		if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
310     			BIN_TO_BCD(real_seconds);
311     			BIN_TO_BCD(real_minutes);
312     		}
313     		CMOS_WRITE(real_seconds,RTC_SECONDS);
314     		CMOS_WRITE(real_minutes,RTC_MINUTES);
315     	} else {
316     		printk(KERN_WARNING
317     		       "set_rtc_mmss: can't update from %d to %d\n",
318     		       cmos_minutes, real_minutes);
319      		retval = -1;
320     	}
321     
322     	/* The following flags have to be released exactly in this order,
323     	 * otherwise the DS12887 (popular MC146818A clone with integrated
324     	 * battery and quartz) will not reset the oscillator and will not
325     	 * update precisely 500 ms later. You won't find this mentioned in
326     	 * the Dallas Semiconductor data sheets, but who believes data
327     	 * sheets anyway ...                           -- Markus Kuhn
328     	 */
329     	CMOS_WRITE(save_control, RTC_CONTROL);
330     	CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
331     
332     	return retval;
333     }
334     
335     /* last time the cmos clock got updated */
336     static long last_rtc_update;
337     
338     /*
339      * timer_interrupt() needs to keep up the real-time clock,
340      * as well as call the "do_timer()" routine every clocktick
341      */
342     static void inline
343     timer_interrupt(int irq, void *dev_id, struct pt_regs * regs)
344     {
345     #ifdef CONFIG_DDB5074
346     	static unsigned cnt, period, dist;
347     
348     	if (cnt == 0 || cnt == dist)
349     	    ddb5074_led_d2(1);
350     	else if (cnt == 7 || cnt == dist+7)
351     	    ddb5074_led_d2(0);
352     	
353     	if (++cnt > period) {
354     	    cnt = 0;
355     	    /* The hyperbolic function below modifies the heartbeat period
356     	     * length in dependency of the current (5min) load. It goes
357     	     * through the points f(0)=126, f(1)=86, f(5)=51,
358     	     * f(inf)->30. */
359     	     period = ((672<<FSHIFT)/(5*avenrun[0]+(7<<FSHIFT))) + 30;
360     	     dist = period / 4;
361     	}
362     #endif
363     	if(!user_mode(regs)) {
364     		if (prof_buffer && current->pid) {
365     			extern int _stext;
366     			unsigned long pc = regs->cp0_epc;
367     
368     			pc -= (unsigned long) &_stext;
369     			pc >>= prof_shift;
370     			/*
371     			 * Dont ignore out-of-bounds pc values silently,
372     			 * put them into the last histogram slot, so if
373     			 * present, they will show up as a sharp peak.
374     			 */
375     			if (pc > prof_len-1)
376     				pc = prof_len-1;
377     			atomic_inc((atomic_t *)&prof_buffer[pc]);
378     		}
379     	}
380     	do_timer(regs);
381     
382     	/*
383     	 * If we have an externally synchronized Linux clock, then update
384     	 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
385     	 * called as close as possible to 500 ms before the new second starts.
386     	 */
387     	read_lock (&xtime_lock); 
388     	if ((time_status & STA_UNSYNC) == 0 &&
389     	    xtime.tv_sec > last_rtc_update + 660 &&
390     	    xtime.tv_usec >= 500000 - ((unsigned) tick) / 2 &&
391     	    xtime.tv_usec <= 500000 + ((unsigned) tick) / 2) {
392     	  if (set_rtc_mmss(xtime.tv_sec) == 0)
393     	    last_rtc_update = xtime.tv_sec;
394     	  else
395     	    last_rtc_update = xtime.tv_sec - 600; /* do it again in 60 s */
396     	}
397     	/* As we return to user mode fire off the other CPU schedulers.. this is 
398     	   basically because we don't yet share IRQ's around. This message is
399     	   rigged to be safe on the 386 - basically it's a hack, so don't look
400     	   closely for now.. */
401     	/*smp_message_pass(MSG_ALL_BUT_SELF, MSG_RESCHEDULE, 0L, 0); */
402     	read_unlock (&xtime_lock); 
403     }
404     
405     static inline void 
406     r4k_timer_interrupt(int irq, void *dev_id, struct pt_regs * regs)
407     {
408     	unsigned int count;
409     
410     	/*
411     	 * The cycle counter is only 32 bit which is good for about
412     	 * a minute at current count rates of upto 150MHz or so.
413     	 */
414     	count = read_32bit_cp0_register(CP0_COUNT);
415     	timerhi += (count < timerlo);	/* Wrap around */
416     	timerlo = count;
417     
418     #ifdef CONFIG_SGI_IP22
419     	/* Since we don't get anything but r4k timer interrupts, we need to
420     	 * set this up so that we'll get one next time. Fortunately since we
421     	 * have timerhi/timerlo, we don't care so much if we miss one. So
422     	 * we need only ask for the next in r4k_interval counts. On other
423     	 * archs we have a real timer, so we don't want this.
424     	 */
425     	write_32bit_cp0_register (CP0_COMPARE, 
426     				  (unsigned long) (count + r4k_interval));
427             kstat.irqs[0][irq]++;
428     #endif
429     
430     	timer_interrupt(irq, dev_id, regs);
431     
432     	if (!jiffies)
433     	{
434     		/*
435     		 * If jiffies has overflowed in this timer_interrupt we must
436     		 * update the timer[hi]/[lo] to make do_fast_gettimeoffset()
437     		 * quotient calc still valid. -arca
438     		 */
439     		timerhi = timerlo = 0;
440     	}
441     }
442     
443     void indy_r4k_timer_interrupt (struct pt_regs *regs)
444     {
445     	static const int INDY_R4K_TIMER_IRQ = 7;
446     	int cpu = smp_processor_id();
447     
448     	r4k_timer_interrupt (INDY_R4K_TIMER_IRQ, NULL, regs);
449     
450     	if (softirq_pending(cpu))
451     		do_softirq();
452     }
453     
454     struct irqaction irq0  = { timer_interrupt, SA_INTERRUPT, 0,
455                                       "timer", NULL, NULL};
456     
457     
458     void (*board_time_init)(struct irqaction *irq);
459     
460     void __init time_init(void)
461     {
462     	unsigned int epoch = 0, year, mon, day, hour, min, sec;
463     	int i;
464     
465     	/* The Linux interpretation of the CMOS clock register contents:
466     	 * When the Update-In-Progress (UIP) flag goes from 1 to 0, the
467     	 * RTC registers show the second which has precisely just started.
468     	 * Let's hope other operating systems interpret the RTC the same way.
469     	 */
470     	/* read RTC exactly on falling edge of update flag */
471     	for (i = 0 ; i < 1000000 ; i++)	/* may take up to 1 second... */
472     		if (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP)
473     			break;
474     	for (i = 0 ; i < 1000000 ; i++)	/* must try at least 2.228 ms */
475     		if (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP))
476     			break;
477     	do { /* Isn't this overkill ? UIP above should guarantee consistency */
478     		sec = CMOS_READ(RTC_SECONDS);
479     		min = CMOS_READ(RTC_MINUTES);
480     		hour = CMOS_READ(RTC_HOURS);
481     		day = CMOS_READ(RTC_DAY_OF_MONTH);
482     		mon = CMOS_READ(RTC_MONTH);
483     		year = CMOS_READ(RTC_YEAR);
484     	} while (sec != CMOS_READ(RTC_SECONDS));
485     	if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
486     	  {
487     	    BCD_TO_BIN(sec);
488     	    BCD_TO_BIN(min);
489     	    BCD_TO_BIN(hour);
490     	    BCD_TO_BIN(day);
491     	    BCD_TO_BIN(mon);
492     	    BCD_TO_BIN(year);
493     	  }
494     
495     	/* Attempt to guess the epoch.  This is the same heuristic as in rtc.c so
496     	   no stupid things will happen to timekeeping.  Who knows, maybe Ultrix
497       	   also uses 1952 as epoch ...  */
498     	if (year > 10 && year < 44) {
499     		epoch = 1980;
500     	} else if (year < 96) {
501     		epoch = 1952;
502     	}
503     	year += epoch;
504     
505     	write_lock_irq (&xtime_lock);
506     	xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
507     	xtime.tv_usec = 0;
508     	write_unlock_irq (&xtime_lock);
509     
510     	if (mips_cpu.options & MIPS_CPU_COUNTER) {
511     		write_32bit_cp0_register(CP0_COUNT, 0);
512     		do_gettimeoffset = do_fast_gettimeoffset;
513     		irq0.handler = r4k_timer_interrupt;
514     	}
515     
516     	board_time_init(&irq0);
517     }
518