1 /*
2  * Common time routines among all ppc machines.
3  *
4  * Written by Cort Dougan (cort@cs.nmt.edu) to merge
5  * Paul Mackerras' version and mine for PReP and Pmac.
6  * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
7  *
8  * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
9  * to make clock more stable (2.4.0-test5). The only thing
10  * that this code assumes is that the timebases have been synchronized
11  * by firmware on SMP and are never stopped (never do sleep
12  * on SMP then, nap and doze are OK).
13  *
14  * TODO (not necessarily in this file):
15  * - improve precision and reproducibility of timebase frequency
16  * measurement at boot time.
17  * - get rid of xtime_lock for gettimeofday (generic kernel problem
18  * to be implemented on all architectures for SMP scalability and
19  * eventually implementing gettimeofday without entering the kernel).
20  * - put all time/clock related variables in a single structure
21  * to minimize number of cache lines touched by gettimeofday()
22  * - for astronomical applications: add a new function to get
23  * non ambiguous timestamps even around leap seconds. This needs
24  * a new timestamp format and a good name.
25  *
26  *
27  * The following comment is partially obsolete (at least the long wait
28  * is no more a valid reason):
29  * Since the MPC8xx has a programmable interrupt timer, I decided to
30  * use that rather than the decrementer.  Two reasons: 1.) the clock
31  * frequency is low, causing 2.) a long wait in the timer interrupt
32  *		while ((d = get_dec()) == dval)
33  * loop.  The MPC8xx can be driven from a variety of input clocks,
34  * so a number of assumptions have been made here because the kernel
35  * parameter HZ is a constant.  We assume (correctly, today :-) that
36  * the MPC8xx on the MBX board is driven from a 32.768 kHz crystal.
37  * This is then divided by 4, providing a 8192 Hz clock into the PIT.
38  * Since it is not possible to get a nice 100 Hz clock out of this, without
39  * creating a software PLL, I have set HZ to 128.  -- Dan
40  *
41  * 1997-09-10  Updated NTP code according to technical memorandum Jan '96
42  *             "A Kernel Model for Precision Timekeeping" by Dave Mills
43  */
44 
45 #include <linux/config.h>
46 #include <linux/errno.h>
47 #include <linux/sched.h>
48 #include <linux/kernel.h>
49 #include <linux/param.h>
50 #include <linux/string.h>
51 #include <linux/mm.h>
52 #include <linux/module.h>
53 #include <linux/interrupt.h>
54 #include <linux/timex.h>
55 #include <linux/kernel_stat.h>
56 #include <linux/mc146818rtc.h>
57 #include <linux/time.h>
58 #include <linux/init.h>
59 
60 #include <asm/segment.h>
61 #include <asm/io.h>
62 #include <asm/processor.h>
63 #include <asm/nvram.h>
64 #include <asm/cache.h>
65 #include <asm/8xx_immap.h>
66 #include <asm/machdep.h>
67 
68 #include <asm/time.h>
69 
70 unsigned long disarm_decr[NR_CPUS];
71 
72 extern int do_sys_settimeofday(struct timeval *tv, struct timezone *tz);
73 
74 /* keep track of when we need to update the rtc */
75 time_t last_rtc_update;
76 extern rwlock_t xtime_lock;
77 
78 /* The decrementer counts down by 128 every 128ns on a 601. */
79 #define DECREMENTER_COUNT_601	(1000000000 / HZ)
80 
81 unsigned tb_ticks_per_jiffy;
82 unsigned tb_to_us;
83 unsigned tb_last_stamp;
84 
85 extern unsigned long wall_jiffies;
86 
87 static long timezone_offset;
88 
89 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
90 
91 EXPORT_SYMBOL(rtc_lock);
92 
93 /* Timer interrupt helper function */
tb_delta(unsigned * jiffy_stamp)94 static inline int tb_delta(unsigned *jiffy_stamp) {
95 	int delta;
96 	if (__USE_RTC()) {
97 		delta = get_rtcl();
98 		if (delta < *jiffy_stamp) *jiffy_stamp -= 1000000000;
99 		delta -= *jiffy_stamp;
100 	} else {
101 		delta = get_tbl() - *jiffy_stamp;
102 	}
103 	return delta;
104 }
105 
106 extern unsigned long prof_cpu_mask;
107 extern unsigned int * prof_buffer;
108 extern unsigned long prof_len;
109 extern unsigned long prof_shift;
110 extern char _stext;
111 
ppc_do_profile(unsigned long nip)112 static inline void ppc_do_profile (unsigned long nip)
113 {
114 	if (!prof_buffer)
115 		return;
116 
117 	/*
118 	 * Only measure the CPUs specified by /proc/irq/prof_cpu_mask.
119 	 * (default is all CPUs.)
120 	 */
121 	if (!((1<<smp_processor_id()) & prof_cpu_mask))
122 		return;
123 
124 	nip -= (unsigned long) &_stext;
125 	nip >>= prof_shift;
126 	/*
127 	 * Don't ignore out-of-bounds EIP values silently,
128 	 * put them into the last histogram slot, so if
129 	 * present, they will show up as a sharp peak.
130 	 */
131 	if (nip > prof_len-1)
132 		nip = prof_len-1;
133 	atomic_inc((atomic_t *)&prof_buffer[nip]);
134 }
135 
136 /*
137  * timer_interrupt - gets called when the decrementer overflows,
138  * with interrupts disabled.
139  * We set it up to overflow again in 1/HZ seconds.
140  */
timer_interrupt(struct pt_regs * regs)141 int timer_interrupt(struct pt_regs * regs)
142 {
143 	int next_dec;
144 	unsigned long cpu = smp_processor_id();
145 	unsigned jiffy_stamp = last_jiffy_stamp(cpu);
146 	extern void do_IRQ(struct pt_regs *);
147 
148 	if (atomic_read(&ppc_n_lost_interrupts) != 0)
149 		do_IRQ(regs);
150 
151 	hardirq_enter(cpu);
152 
153 	while ((next_dec = tb_ticks_per_jiffy - tb_delta(&jiffy_stamp)) <= 0) {
154 		jiffy_stamp += tb_ticks_per_jiffy;
155 		if (!user_mode(regs))
156 			ppc_do_profile(instruction_pointer(regs));
157 		if (unlikely(!heartbeat_count(cpu)--)
158 				&& heartbeat_reset(cpu)) {
159 			ppc_md.heartbeat();
160 			heartbeat_count(cpu) = heartbeat_reset(cpu);
161 		}
162 	  	if (cpu)
163 			continue;
164 
165 		/* We are in an interrupt, no need to save/restore flags */
166 		write_lock(&xtime_lock);
167 		tb_last_stamp = jiffy_stamp;
168 		do_timer(regs);
169 
170 		/*
171 		 * update the rtc when needed, this should be performed on the
172 		 * right fraction of a second. Half or full second ?
173 		 * Full second works on mk48t59 clocks, others need testing.
174 		 * Note that this update is basically only used through
175 		 * the adjtimex system calls. Setting the HW clock in
176 		 * any other way is a /dev/rtc and userland business.
177 		 * This is still wrong by -0.5/+1.5 jiffies because of the
178 		 * timer interrupt resolution and possible delay, but here we
179 		 * hit a quantization limit which can only be solved by higher
180 		 * resolution timers and decoupling time management from timer
181 		 * interrupts. This is also wrong on the clocks
182 		 * which require being written at the half second boundary.
183 		 * We should have an rtc call that only sets the minutes and
184 		 * seconds like on Intel to avoid problems with non UTC clocks.
185 		 */
186 		if ( ppc_md.set_rtc_time && (time_status & STA_UNSYNC) == 0 &&
187 		     xtime.tv_sec - last_rtc_update >= 659 &&
188 		     abs(xtime.tv_usec - (1000000-1000000/HZ)) < 500000/HZ &&
189 		     jiffies - wall_jiffies == 1) {
190 		  	if (ppc_md.set_rtc_time(xtime.tv_sec+1 + timezone_offset) == 0)
191 				last_rtc_update = xtime.tv_sec+1;
192 			else
193 				/* Try again one minute later */
194 				last_rtc_update += 60;
195 		}
196 		write_unlock(&xtime_lock);
197 	}
198 	if (!disarm_decr[cpu])
199 		set_dec(next_dec);
200 	last_jiffy_stamp(cpu) = jiffy_stamp;
201 
202 #ifdef CONFIG_SMP
203 	smp_local_timer_interrupt(regs);
204 #endif /* CONFIG_SMP */
205 
206 	hardirq_exit(cpu);
207 
208 	if (softirq_pending(cpu))
209 		do_softirq();
210 
211 	return 1; /* lets ret_from_int know we can do checks */
212 }
213 
214 /*
215  * This version of gettimeofday has microsecond resolution.
216  */
do_gettimeofday(struct timeval * tv)217 void do_gettimeofday(struct timeval *tv)
218 {
219 	unsigned long flags;
220 	unsigned delta, lost_ticks, usec, sec;
221 
222 	read_lock_irqsave(&xtime_lock, flags);
223 	sec = xtime.tv_sec;
224 	usec = xtime.tv_usec;
225 	delta = tb_ticks_since(tb_last_stamp);
226 #ifdef CONFIG_SMP
227 	/* As long as timebases are not in sync, gettimeofday can only
228 	 * have jiffy resolution on SMP.
229 	 */
230 	if (!smp_tb_synchronized)
231 		delta = 0;
232 #endif /* CONFIG_SMP */
233 	lost_ticks = jiffies - wall_jiffies;
234 	read_unlock_irqrestore(&xtime_lock, flags);
235 
236 	usec += mulhwu(tb_to_us, tb_ticks_per_jiffy * lost_ticks + delta);
237 	while (usec >= 1000000) {
238 	  	sec++;
239 		usec -= 1000000;
240 	}
241 	tv->tv_sec = sec;
242 	tv->tv_usec = usec;
243 }
244 
do_settimeofday(struct timeval * tv)245 void do_settimeofday(struct timeval *tv)
246 {
247 	unsigned long flags;
248 	int tb_delta, new_usec, new_sec;
249 
250 	write_lock_irqsave(&xtime_lock, flags);
251 	/* Updating the RTC is not the job of this code. If the time is
252 	 * stepped under NTP, the RTC will be update after STA_UNSYNC
253 	 * is cleared. Tool like clock/hwclock either copy the RTC
254 	 * to the system time, in which case there is no point in writing
255 	 * to the RTC again, or write to the RTC but then they don't call
256 	 * settimeofday to perform this operation. Note also that
257 	 * we don't touch the decrementer since:
258 	 * a) it would lose timer interrupt synchronization on SMP
259 	 * (if it is working one day)
260 	 * b) it could make one jiffy spuriously shorter or longer
261 	 * which would introduce another source of uncertainty potentially
262 	 * harmful to relatively short timers.
263 	 */
264 
265 	/* This works perfectly on SMP only if the tb are in sync but
266 	 * guarantees an error < 1 jiffy even if they are off by eons,
267 	 * still reasonable when gettimeofday resolution is 1 jiffy.
268 	 */
269 	tb_delta = tb_ticks_since(last_jiffy_stamp(smp_processor_id()));
270 	tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
271 	new_sec = tv->tv_sec;
272 	new_usec = tv->tv_usec - mulhwu(tb_to_us, tb_delta);
273 	while (new_usec <0) {
274 		new_sec--;
275 		new_usec += 1000000;
276 	}
277 	xtime.tv_usec = new_usec;
278 	xtime.tv_sec = new_sec;
279 
280 	/* In case of a large backwards jump in time with NTP, we want the
281 	 * clock to be updated as soon as the PLL is again in lock.
282 	 */
283 	last_rtc_update = new_sec - 658;
284 
285 	time_adjust = 0;                /* stop active adjtime() */
286 	time_status |= STA_UNSYNC;
287 	time_state = TIME_ERROR;        /* p. 24, (a) */
288 	time_maxerror = NTP_PHASE_LIMIT;
289 	time_esterror = NTP_PHASE_LIMIT;
290 	write_unlock_irqrestore(&xtime_lock, flags);
291 }
292 
293 /* This function is only called on the boot processor */
time_init(void)294 void __init time_init(void)
295 {
296 	time_t sec, old_sec;
297 	unsigned old_stamp, stamp, elapsed;
298 
299         if (ppc_md.time_init != NULL)
300                 timezone_offset = ppc_md.time_init();
301 
302 	if (__USE_RTC()) {
303 		/* 601 processor: dec counts down by 128 every 128ns */
304 		tb_ticks_per_jiffy = DECREMENTER_COUNT_601;
305 		/* mulhwu_scale_factor(1000000000, 1000000) is 0x418937 */
306 		tb_to_us = 0x418937;
307         } else {
308                 ppc_md.calibrate_decr();
309 	}
310 
311 	/* Now that the decrementer is calibrated, it can be used in case the
312 	 * clock is stuck, but the fact that we have to handle the 601
313 	 * makes things more complex. Repeatedly read the RTC until the
314 	 * next second boundary to try to achieve some precision.  If there
315 	 * is no RTC, we still need to set tb_last_stamp and
316 	 * last_jiffy_stamp(cpu 0) to the current stamp.
317 	 */
318 	stamp = get_native_tbl();
319 	if (ppc_md.get_rtc_time) {
320 		sec = ppc_md.get_rtc_time();
321 		elapsed = 0;
322 		do {
323 			old_stamp = stamp;
324 			old_sec = sec;
325 			stamp = get_native_tbl();
326 			if (__USE_RTC() && stamp < old_stamp)
327 				old_stamp -= 1000000000;
328 			elapsed += stamp - old_stamp;
329 			sec = ppc_md.get_rtc_time();
330 		} while ( sec == old_sec && elapsed < 2*HZ*tb_ticks_per_jiffy);
331 		if (sec == old_sec)
332 			printk("Warning: real time clock seems stuck!\n");
333 		xtime.tv_sec = sec;
334 		xtime.tv_usec = 0;
335 		/* No update now, we just read the time from the RTC ! */
336 		last_rtc_update = xtime.tv_sec;
337 	}
338 
339 	last_jiffy_stamp(0) = tb_last_stamp = stamp;
340 
341 	/* Not exact, but the timer interrupt takes care of this */
342 	set_dec(tb_ticks_per_jiffy);
343 
344 	/* If platform provided a timezone (pmac), we correct the time
345 	 * using do_sys_settimeofday() which in turn calls warp_clock()
346 	 */
347         if (timezone_offset) {
348         	struct timezone tz;
349         	tz.tz_minuteswest = -timezone_offset / 60;
350         	tz.tz_dsttime = 0;
351         	do_sys_settimeofday(NULL, &tz);
352         }
353 }
354 
355 #define FEBRUARY		2
356 #define	STARTOFTIME		1970
357 #define SECDAY			86400L
358 #define SECYR			(SECDAY * 365)
359 #define	leapyear(y)		((!(y % 4) && (y % 100)) || !(y % 400))
360 #define	days_in_year(a) 	(leapyear(a) ? 366 : 365)
361 #define	days_in_month(a) 	(month_days[(a) - 1])
362 
363 static int month_days[12] = {
364 	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
365 };
366 
to_tm(int tim,struct rtc_time * tm)367 void to_tm(int tim, struct rtc_time * tm)
368 {
369 	register int i;
370 	register long hms, day, gday;
371 
372 	gday = day = tim / SECDAY;
373 	hms = tim % SECDAY;
374 
375 	/* Hours, minutes, seconds are easy */
376 	tm->tm_hour = hms / 3600;
377 	tm->tm_min = (hms % 3600) / 60;
378 	tm->tm_sec = (hms % 3600) % 60;
379 
380 	/* Number of years in days */
381 	for (i = STARTOFTIME; day >= days_in_year(i); i++)
382 		day -= days_in_year(i);
383 	tm->tm_year = i;
384 
385 	/* Number of months in days left */
386 	if (leapyear(tm->tm_year))
387 		days_in_month(FEBRUARY) = 29;
388 	for (i = 1; day >= days_in_month(i); i++)
389 		day -= days_in_month(i);
390 	days_in_month(FEBRUARY) = 28;
391 	tm->tm_mon = i;
392 
393 	/* Days are what is left over (+1) from all that. */
394 	tm->tm_mday = day + 1;
395 
396 	/*
397 	 * Determine the day of week. Jan. 1, 1970 was a Thursday.
398 	 */
399 	tm->tm_wday = (gday + 4) % 7;
400 }
401 
402 /* Auxiliary function to compute scaling factors */
403 /* Actually the choice of a timebase running at 1/4 the of the bus
404  * frequency giving resolution of a few tens of nanoseconds is quite nice.
405  * It makes this computation very precise (27-28 bits typically) which
406  * is optimistic considering the stability of most processor clock
407  * oscillators and the precision with which the timebase frequency
408  * is measured but does not harm.
409  */
mulhwu_scale_factor(unsigned inscale,unsigned outscale)410 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
411 	unsigned mlt=0, tmp, err;
412 	/* No concern for performance, it's done once: use a stupid
413 	 * but safe and compact method to find the multiplier.
414 	 */
415 	for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
416 		if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
417 	}
418 	/* We might still be off by 1 for the best approximation.
419 	 * A side effect of this is that if outscale is too large
420 	 * the returned value will be zero.
421 	 * Many corner cases have been checked and seem to work,
422 	 * some might have been forgotten in the test however.
423 	 */
424 	err = inscale*(mlt+1);
425 	if (err <= inscale/2) mlt++;
426 	return mlt;
427 }
428 
429