PageRenderTime 45ms CodeModel.GetById 16ms app.highlight 24ms RepoModel.GetById 1ms app.codeStats 0ms

/arch/alpha/kernel/time.c

https://bitbucket.org/evzijst/gittest
C | 591 lines | 341 code | 98 blank | 152 comment | 57 complexity | 33b818b1dbcafa798abbb9a5a4ca4c9e MD5 | raw file
  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/config.h>
 31#include <linux/errno.h>
 32#include <linux/module.h>
 33#include <linux/sched.h>
 34#include <linux/kernel.h>
 35#include <linux/param.h>
 36#include <linux/string.h>
 37#include <linux/mm.h>
 38#include <linux/delay.h>
 39#include <linux/ioport.h>
 40#include <linux/irq.h>
 41#include <linux/interrupt.h>
 42#include <linux/init.h>
 43#include <linux/bcd.h>
 44#include <linux/profile.h>
 45
 46#include <asm/uaccess.h>
 47#include <asm/io.h>
 48#include <asm/hwrpb.h>
 49#include <asm/8253pit.h>
 50
 51#include <linux/mc146818rtc.h>
 52#include <linux/time.h>
 53#include <linux/timex.h>
 54
 55#include "proto.h"
 56#include "irq_impl.h"
 57
 58u64 jiffies_64 = INITIAL_JIFFIES;
 59
 60EXPORT_SYMBOL(jiffies_64);
 61
 62extern unsigned long wall_jiffies;	/* kernel/timer.c */
 63
 64static int set_rtc_mmss(unsigned long);
 65
 66DEFINE_SPINLOCK(rtc_lock);
 67
 68#define TICK_SIZE (tick_nsec / 1000)
 69
 70/*
 71 * Shift amount by which scaled_ticks_per_cycle is scaled.  Shifting
 72 * by 48 gives us 16 bits for HZ while keeping the accuracy good even
 73 * for large CPU clock rates.
 74 */
 75#define FIX_SHIFT	48
 76
 77/* lump static variables together for more efficient access: */
 78static struct {
 79	/* cycle counter last time it got invoked */
 80	__u32 last_time;
 81	/* ticks/cycle * 2^48 */
 82	unsigned long scaled_ticks_per_cycle;
 83	/* last time the CMOS clock got updated */
 84	time_t last_rtc_update;
 85	/* partial unused tick */
 86	unsigned long partial_tick;
 87} state;
 88
 89unsigned long est_cycle_freq;
 90
 91
 92static inline __u32 rpcc(void)
 93{
 94    __u32 result;
 95    asm volatile ("rpcc %0" : "=r"(result));
 96    return result;
 97}
 98
 99/*
100 * Scheduler clock - returns current time in nanosec units.
101 *
102 * Copied from ARM code for expediency... ;-}
103 */
104unsigned long long sched_clock(void)
105{
106        return (unsigned long long)jiffies * (1000000000 / HZ);
107}
108
109
110/*
111 * timer_interrupt() needs to keep up the real-time clock,
112 * as well as call the "do_timer()" routine every clocktick
113 */
114irqreturn_t timer_interrupt(int irq, void *dev, struct pt_regs * regs)
115{
116	unsigned long delta;
117	__u32 now;
118	long nticks;
119
120#ifndef CONFIG_SMP
121	/* Not SMP, do kernel PC profiling here.  */
122	profile_tick(CPU_PROFILING, regs);
123#endif
124
125	write_seqlock(&xtime_lock);
126
127	/*
128	 * Calculate how many ticks have passed since the last update,
129	 * including any previous partial leftover.  Save any resulting
130	 * fraction for the next pass.
131	 */
132	now = rpcc();
133	delta = now - state.last_time;
134	state.last_time = now;
135	delta = delta * state.scaled_ticks_per_cycle + state.partial_tick;
136	state.partial_tick = delta & ((1UL << FIX_SHIFT) - 1); 
137	nticks = delta >> FIX_SHIFT;
138
139	while (nticks > 0) {
140		do_timer(regs);
141#ifndef CONFIG_SMP
142		update_process_times(user_mode(regs));
143#endif
144		nticks--;
145	}
146
147	/*
148	 * If we have an externally synchronized Linux clock, then update
149	 * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
150	 * called as close as possible to 500 ms before the new second starts.
151	 */
152	if ((time_status & STA_UNSYNC) == 0
153	    && xtime.tv_sec > state.last_rtc_update + 660
154	    && xtime.tv_nsec >= 500000 - ((unsigned) TICK_SIZE) / 2
155	    && xtime.tv_nsec <= 500000 + ((unsigned) TICK_SIZE) / 2) {
156		int tmp = set_rtc_mmss(xtime.tv_sec);
157		state.last_rtc_update = xtime.tv_sec - (tmp ? 600 : 0);
158	}
159
160	write_sequnlock(&xtime_lock);
161	return IRQ_HANDLED;
162}
163
164void
165common_init_rtc(void)
166{
167	unsigned char x;
168
169	/* Reset periodic interrupt frequency.  */
170	x = CMOS_READ(RTC_FREQ_SELECT) & 0x3f;
171        /* Test includes known working values on various platforms
172           where 0x26 is wrong; we refuse to change those. */
173	if (x != 0x26 && x != 0x25 && x != 0x19 && x != 0x06) {
174		printk("Setting RTC_FREQ to 1024 Hz (%x)\n", x);
175		CMOS_WRITE(0x26, RTC_FREQ_SELECT);
176	}
177
178	/* Turn on periodic interrupts.  */
179	x = CMOS_READ(RTC_CONTROL);
180	if (!(x & RTC_PIE)) {
181		printk("Turning on RTC interrupts.\n");
182		x |= RTC_PIE;
183		x &= ~(RTC_AIE | RTC_UIE);
184		CMOS_WRITE(x, RTC_CONTROL);
185	}
186	(void) CMOS_READ(RTC_INTR_FLAGS);
187
188	outb(0x36, 0x43);	/* pit counter 0: system timer */
189	outb(0x00, 0x40);
190	outb(0x00, 0x40);
191
192	outb(0xb6, 0x43);	/* pit counter 2: speaker */
193	outb(0x31, 0x42);
194	outb(0x13, 0x42);
195
196	init_rtc_irq();
197}
198
199
200/* Validate a computed cycle counter result against the known bounds for
201   the given processor core.  There's too much brokenness in the way of
202   timing hardware for any one method to work everywhere.  :-(
203
204   Return 0 if the result cannot be trusted, otherwise return the argument.  */
205
206static unsigned long __init
207validate_cc_value(unsigned long cc)
208{
209	static struct bounds {
210		unsigned int min, max;
211	} cpu_hz[] __initdata = {
212		[EV3_CPU]    = {   50000000,  200000000 },	/* guess */
213		[EV4_CPU]    = {  100000000,  300000000 },
214		[LCA4_CPU]   = {  100000000,  300000000 },	/* guess */
215		[EV45_CPU]   = {  200000000,  300000000 },
216		[EV5_CPU]    = {  250000000,  433000000 },
217		[EV56_CPU]   = {  333000000,  667000000 },
218		[PCA56_CPU]  = {  400000000,  600000000 },	/* guess */
219		[PCA57_CPU]  = {  500000000,  600000000 },	/* guess */
220		[EV6_CPU]    = {  466000000,  600000000 },
221		[EV67_CPU]   = {  600000000,  750000000 },
222		[EV68AL_CPU] = {  750000000,  940000000 },
223		[EV68CB_CPU] = { 1000000000, 1333333333 },
224		/* None of the following are shipping as of 2001-11-01.  */
225		[EV68CX_CPU] = { 1000000000, 1700000000 },	/* guess */
226		[EV69_CPU]   = { 1000000000, 1700000000 },	/* guess */
227		[EV7_CPU]    = {  800000000, 1400000000 },	/* guess */
228		[EV79_CPU]   = { 1000000000, 2000000000 },	/* guess */
229	};
230
231	/* Allow for some drift in the crystal.  10MHz is more than enough.  */
232	const unsigned int deviation = 10000000;
233
234	struct percpu_struct *cpu;
235	unsigned int index;
236
237	cpu = (struct percpu_struct *)((char*)hwrpb + hwrpb->processor_offset);
238	index = cpu->type & 0xffffffff;
239
240	/* If index out of bounds, no way to validate.  */
241	if (index >= sizeof(cpu_hz)/sizeof(cpu_hz[0]))
242		return cc;
243
244	/* If index contains no data, no way to validate.  */
245	if (cpu_hz[index].max == 0)
246		return cc;
247
248	if (cc < cpu_hz[index].min - deviation
249	    || cc > cpu_hz[index].max + deviation)
250		return 0;
251
252	return cc;
253}
254
255
256/*
257 * Calibrate CPU clock using legacy 8254 timer/counter. Stolen from
258 * arch/i386/time.c.
259 */
260
261#define CALIBRATE_LATCH	0xffff
262#define TIMEOUT_COUNT	0x100000
263
264static unsigned long __init
265calibrate_cc_with_pit(void)
266{
267	int cc, count = 0;
268
269	/* Set the Gate high, disable speaker */
270	outb((inb(0x61) & ~0x02) | 0x01, 0x61);
271
272	/*
273	 * Now let's take care of CTC channel 2
274	 *
275	 * Set the Gate high, program CTC channel 2 for mode 0,
276	 * (interrupt on terminal count mode), binary count,
277	 * load 5 * LATCH count, (LSB and MSB) to begin countdown.
278	 */
279	outb(0xb0, 0x43);		/* binary, mode 0, LSB/MSB, Ch 2 */
280	outb(CALIBRATE_LATCH & 0xff, 0x42);	/* LSB of count */
281	outb(CALIBRATE_LATCH >> 8, 0x42);	/* MSB of count */
282
283	cc = rpcc();
284	do {
285		count++;
286	} while ((inb(0x61) & 0x20) == 0 && count < TIMEOUT_COUNT);
287	cc = rpcc() - cc;
288
289	/* Error: ECTCNEVERSET or ECPUTOOFAST.  */
290	if (count <= 1 || count == TIMEOUT_COUNT)
291		return 0;
292
293	return ((long)cc * PIT_TICK_RATE) / (CALIBRATE_LATCH + 1);
294}
295
296/* The Linux interpretation of the CMOS clock register contents:
297   When the Update-In-Progress (UIP) flag goes from 1 to 0, the
298   RTC registers show the second which has precisely just started.
299   Let's hope other operating systems interpret the RTC the same way.  */
300
301static unsigned long __init
302rpcc_after_update_in_progress(void)
303{
304	do { } while (!(CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP));
305	do { } while (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
306
307	return rpcc();
308}
309
310void __init
311time_init(void)
312{
313	unsigned int year, mon, day, hour, min, sec, cc1, cc2, epoch;
314	unsigned long cycle_freq, tolerance;
315	long diff;
316
317	/* Calibrate CPU clock -- attempt #1.  */
318	if (!est_cycle_freq)
319		est_cycle_freq = validate_cc_value(calibrate_cc_with_pit());
320
321	cc1 = rpcc_after_update_in_progress();
322
323	/* Calibrate CPU clock -- attempt #2.  */
324	if (!est_cycle_freq) {
325		cc2 = rpcc_after_update_in_progress();
326		est_cycle_freq = validate_cc_value(cc2 - cc1);
327		cc1 = cc2;
328	}
329
330	cycle_freq = hwrpb->cycle_freq;
331	if (est_cycle_freq) {
332		/* If the given value is within 250 PPM of what we calculated,
333		   accept it.  Otherwise, use what we found.  */
334		tolerance = cycle_freq / 4000;
335		diff = cycle_freq - est_cycle_freq;
336		if (diff < 0)
337			diff = -diff;
338		if ((unsigned long)diff > tolerance) {
339			cycle_freq = est_cycle_freq;
340			printk("HWRPB cycle frequency bogus.  "
341			       "Estimated %lu Hz\n", cycle_freq);
342		} else {
343			est_cycle_freq = 0;
344		}
345	} else if (! validate_cc_value (cycle_freq)) {
346		printk("HWRPB cycle frequency bogus, "
347		       "and unable to estimate a proper value!\n");
348	}
349
350	/* From John Bowman <bowman@math.ualberta.ca>: allow the values
351	   to settle, as the Update-In-Progress bit going low isn't good
352	   enough on some hardware.  2ms is our guess; we haven't found 
353	   bogomips yet, but this is close on a 500Mhz box.  */
354	__delay(1000000);
355
356	sec = CMOS_READ(RTC_SECONDS);
357	min = CMOS_READ(RTC_MINUTES);
358	hour = CMOS_READ(RTC_HOURS);
359	day = CMOS_READ(RTC_DAY_OF_MONTH);
360	mon = CMOS_READ(RTC_MONTH);
361	year = CMOS_READ(RTC_YEAR);
362
363	if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
364		BCD_TO_BIN(sec);
365		BCD_TO_BIN(min);
366		BCD_TO_BIN(hour);
367		BCD_TO_BIN(day);
368		BCD_TO_BIN(mon);
369		BCD_TO_BIN(year);
370	}
371
372	/* PC-like is standard; used for year >= 70 */
373	epoch = 1900;
374	if (year < 20)
375		epoch = 2000;
376	else if (year >= 20 && year < 48)
377		/* NT epoch */
378		epoch = 1980;
379	else if (year >= 48 && year < 70)
380		/* Digital UNIX epoch */
381		epoch = 1952;
382
383	printk(KERN_INFO "Using epoch = %d\n", epoch);
384
385	if ((year += epoch) < 1970)
386		year += 100;
387
388	xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
389	xtime.tv_nsec = 0;
390
391        wall_to_monotonic.tv_sec -= xtime.tv_sec;
392        wall_to_monotonic.tv_nsec = 0;
393
394	if (HZ > (1<<16)) {
395		extern void __you_loose (void);
396		__you_loose();
397	}
398
399	state.last_time = cc1;
400	state.scaled_ticks_per_cycle
401		= ((unsigned long) HZ << FIX_SHIFT) / cycle_freq;
402	state.last_rtc_update = 0;
403	state.partial_tick = 0L;
404
405	/* Startup the timer source. */
406	alpha_mv.init_rtc();
407}
408
409/*
410 * Use the cycle counter to estimate an displacement from the last time
411 * tick.  Unfortunately the Alpha designers made only the low 32-bits of
412 * the cycle counter active, so we overflow on 8.2 seconds on a 500MHz
413 * part.  So we can't do the "find absolute time in terms of cycles" thing
414 * that the other ports do.
415 */
416void
417do_gettimeofday(struct timeval *tv)
418{
419	unsigned long flags;
420	unsigned long sec, usec, lost, seq;
421	unsigned long delta_cycles, delta_usec, partial_tick;
422
423	do {
424		seq = read_seqbegin_irqsave(&xtime_lock, flags);
425
426		delta_cycles = rpcc() - state.last_time;
427		sec = xtime.tv_sec;
428		usec = (xtime.tv_nsec / 1000);
429		partial_tick = state.partial_tick;
430		lost = jiffies - wall_jiffies;
431
432	} while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
433
434#ifdef CONFIG_SMP
435	/* Until and unless we figure out how to get cpu cycle counters
436	   in sync and keep them there, we can't use the rpcc tricks.  */
437	delta_usec = lost * (1000000 / HZ);
438#else
439	/*
440	 * usec = cycles * ticks_per_cycle * 2**48 * 1e6 / (2**48 * ticks)
441	 *	= cycles * (s_t_p_c) * 1e6 / (2**48 * ticks)
442	 *	= cycles * (s_t_p_c) * 15625 / (2**42 * ticks)
443	 *
444	 * which, given a 600MHz cycle and a 1024Hz tick, has a
445	 * dynamic range of about 1.7e17, which is less than the
446	 * 1.8e19 in an unsigned long, so we are safe from overflow.
447	 *
448	 * Round, but with .5 up always, since .5 to even is harder
449	 * with no clear gain.
450	 */
451
452	delta_usec = (delta_cycles * state.scaled_ticks_per_cycle 
453		      + partial_tick
454		      + (lost << FIX_SHIFT)) * 15625;
455	delta_usec = ((delta_usec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
456#endif
457
458	usec += delta_usec;
459	if (usec >= 1000000) {
460		sec += 1;
461		usec -= 1000000;
462	}
463
464	tv->tv_sec = sec;
465	tv->tv_usec = usec;
466}
467
468EXPORT_SYMBOL(do_gettimeofday);
469
470int
471do_settimeofday(struct timespec *tv)
472{
473	time_t wtm_sec, sec = tv->tv_sec;
474	long wtm_nsec, nsec = tv->tv_nsec;
475	unsigned long delta_nsec;
476
477	if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
478		return -EINVAL;
479
480	write_seqlock_irq(&xtime_lock);
481
482	/* The offset that is added into time in do_gettimeofday above
483	   must be subtracted out here to keep a coherent view of the
484	   time.  Without this, a full-tick error is possible.  */
485
486#ifdef CONFIG_SMP
487	delta_nsec = (jiffies - wall_jiffies) * (NSEC_PER_SEC / HZ);
488#else
489	delta_nsec = rpcc() - state.last_time;
490	delta_nsec = (delta_nsec * state.scaled_ticks_per_cycle 
491		      + state.partial_tick
492		      + ((jiffies - wall_jiffies) << FIX_SHIFT)) * 15625;
493	delta_nsec = ((delta_nsec / ((1UL << (FIX_SHIFT-6-1)) * HZ)) + 1) / 2;
494	delta_nsec *= 1000;
495#endif
496
497	nsec -= delta_nsec;
498
499	wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - sec);
500	wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - nsec);
501
502	set_normalized_timespec(&xtime, sec, nsec);
503	set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
504
505	time_adjust = 0;		/* stop active adjtime() */
506	time_status |= STA_UNSYNC;
507	time_maxerror = NTP_PHASE_LIMIT;
508	time_esterror = NTP_PHASE_LIMIT;
509
510	write_sequnlock_irq(&xtime_lock);
511	clock_was_set();
512	return 0;
513}
514
515EXPORT_SYMBOL(do_settimeofday);
516
517
518/*
519 * In order to set the CMOS clock precisely, set_rtc_mmss has to be
520 * called 500 ms after the second nowtime has started, because when
521 * nowtime is written into the registers of the CMOS clock, it will
522 * jump to the next second precisely 500 ms later. Check the Motorola
523 * MC146818A or Dallas DS12887 data sheet for details.
524 *
525 * BUG: This routine does not handle hour overflow properly; it just
526 *      sets the minutes. Usually you won't notice until after reboot!
527 */
528
529
530static int
531set_rtc_mmss(unsigned long nowtime)
532{
533	int retval = 0;
534	int real_seconds, real_minutes, cmos_minutes;
535	unsigned char save_control, save_freq_select;
536
537	/* irq are locally disabled here */
538	spin_lock(&rtc_lock);
539	/* Tell the clock it's being set */
540	save_control = CMOS_READ(RTC_CONTROL);
541	CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
542
543	/* Stop and reset prescaler */
544	save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
545	CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
546
547	cmos_minutes = CMOS_READ(RTC_MINUTES);
548	if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
549		BCD_TO_BIN(cmos_minutes);
550
551	/*
552	 * since we're only adjusting minutes and seconds,
553	 * don't interfere with hour overflow. This avoids
554	 * messing with unknown time zones but requires your
555	 * RTC not to be off by more than 15 minutes
556	 */
557	real_seconds = nowtime % 60;
558	real_minutes = nowtime / 60;
559	if (((abs(real_minutes - cmos_minutes) + 15)/30) & 1) {
560		/* correct for half hour time zone */
561		real_minutes += 30;
562	}
563	real_minutes %= 60;
564
565	if (abs(real_minutes - cmos_minutes) < 30) {
566		if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
567			BIN_TO_BCD(real_seconds);
568			BIN_TO_BCD(real_minutes);
569		}
570		CMOS_WRITE(real_seconds,RTC_SECONDS);
571		CMOS_WRITE(real_minutes,RTC_MINUTES);
572	} else {
573		printk(KERN_WARNING
574		       "set_rtc_mmss: can't update from %d to %d\n",
575		       cmos_minutes, real_minutes);
576 		retval = -1;
577	}
578
579	/* The following flags have to be released exactly in this order,
580	 * otherwise the DS12887 (popular MC146818A clone with integrated
581	 * battery and quartz) will not reset the oscillator and will not
582	 * update precisely 500 ms later. You won't find this mentioned in
583	 * the Dallas Semiconductor data sheets, but who believes data
584	 * sheets anyway ...                           -- Markus Kuhn
585	 */
586	CMOS_WRITE(save_control, RTC_CONTROL);
587	CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
588	spin_unlock(&rtc_lock);
589
590	return retval;
591}