blob: 2348a75e050dc4fe523105b049fd80f44f35d428 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
2 *
3 * Common time routines among all ppc machines.
4 *
5 * Written by Cort Dougan (cort@cs.nmt.edu) to merge
6 * Paul Mackerras' version and mine for PReP and Pmac.
7 * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
8 * Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
9 *
10 * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
11 * to make clock more stable (2.4.0-test5). The only thing
12 * that this code assumes is that the timebases have been synchronized
13 * by firmware on SMP and are never stopped (never do sleep
14 * on SMP then, nap and doze are OK).
15 *
16 * Speeded up do_gettimeofday by getting rid of references to
17 * xtime (which required locks for consistency). (mikejc@us.ibm.com)
18 *
19 * TODO (not necessarily in this file):
20 * - improve precision and reproducibility of timebase frequency
21 * measurement at boot time. (for iSeries, we calibrate the timebase
22 * against the Titan chip's clock.)
23 * - for astronomical applications: add a new function to get
24 * non ambiguous timestamps even around leap seconds. This needs
25 * a new timestamp format and a good name.
26 *
27 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
28 * "A Kernel Model for Precision Timekeeping" by Dave Mills
29 *
30 * This program is free software; you can redistribute it and/or
31 * modify it under the terms of the GNU General Public License
32 * as published by the Free Software Foundation; either version
33 * 2 of the License, or (at your option) any later version.
34 */
35
36#include <linux/config.h>
37#include <linux/errno.h>
38#include <linux/module.h>
39#include <linux/sched.h>
40#include <linux/kernel.h>
41#include <linux/param.h>
42#include <linux/string.h>
43#include <linux/mm.h>
44#include <linux/interrupt.h>
45#include <linux/timex.h>
46#include <linux/kernel_stat.h>
47#include <linux/mc146818rtc.h>
48#include <linux/time.h>
49#include <linux/init.h>
50#include <linux/profile.h>
51#include <linux/cpu.h>
52#include <linux/security.h>
53
54#include <asm/segment.h>
55#include <asm/io.h>
56#include <asm/processor.h>
57#include <asm/nvram.h>
58#include <asm/cache.h>
59#include <asm/machdep.h>
60#ifdef CONFIG_PPC_ISERIES
61#include <asm/iSeries/ItLpQueue.h>
62#include <asm/iSeries/HvCallXm.h>
63#endif
64#include <asm/uaccess.h>
65#include <asm/time.h>
66#include <asm/ppcdebug.h>
67#include <asm/prom.h>
68#include <asm/sections.h>
69#include <asm/systemcfg.h>
70
71u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
72
73EXPORT_SYMBOL(jiffies_64);
74
75/* keep track of when we need to update the rtc */
76time_t last_rtc_update;
77extern int piranha_simulator;
78#ifdef CONFIG_PPC_ISERIES
79unsigned long iSeries_recal_titan = 0;
80unsigned long iSeries_recal_tb = 0;
81static unsigned long first_settimeofday = 1;
82#endif
83
84#define XSEC_PER_SEC (1024*1024)
85
86unsigned long tb_ticks_per_jiffy;
87unsigned long tb_ticks_per_usec = 100; /* sane default */
88EXPORT_SYMBOL(tb_ticks_per_usec);
89unsigned long tb_ticks_per_sec;
90unsigned long tb_to_xs;
91unsigned tb_to_us;
92unsigned long processor_freq;
93DEFINE_SPINLOCK(rtc_lock);
94
95unsigned long tb_to_ns_scale;
96unsigned long tb_to_ns_shift;
97
98struct gettimeofday_struct do_gtod;
99
100extern unsigned long wall_jiffies;
101extern unsigned long lpevent_count;
102extern int smp_tb_synchronized;
103
104extern struct timezone sys_tz;
105
106void ppc_adjtimex(void);
107
108static unsigned adjusting_time = 0;
109
Arnd Bergmann10f7e7c2005-06-23 09:43:07 +1000110unsigned long ppc_proc_freq;
111unsigned long ppc_tb_freq;
112
Linus Torvalds1da177e2005-04-16 15:20:36 -0700113static __inline__ void timer_check_rtc(void)
114{
115 /*
116 * update the rtc when needed, this should be performed on the
117 * right fraction of a second. Half or full second ?
118 * Full second works on mk48t59 clocks, others need testing.
119 * Note that this update is basically only used through
120 * the adjtimex system calls. Setting the HW clock in
121 * any other way is a /dev/rtc and userland business.
122 * This is still wrong by -0.5/+1.5 jiffies because of the
123 * timer interrupt resolution and possible delay, but here we
124 * hit a quantization limit which can only be solved by higher
125 * resolution timers and decoupling time management from timer
126 * interrupts. This is also wrong on the clocks
127 * which require being written at the half second boundary.
128 * We should have an rtc call that only sets the minutes and
129 * seconds like on Intel to avoid problems with non UTC clocks.
130 */
131 if ( (time_status & STA_UNSYNC) == 0 &&
132 xtime.tv_sec - last_rtc_update >= 659 &&
133 abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ &&
134 jiffies - wall_jiffies == 1) {
135 struct rtc_time tm;
136 to_tm(xtime.tv_sec+1, &tm);
137 tm.tm_year -= 1900;
138 tm.tm_mon -= 1;
139 if (ppc_md.set_rtc_time(&tm) == 0)
140 last_rtc_update = xtime.tv_sec+1;
141 else
142 /* Try again one minute later */
143 last_rtc_update += 60;
144 }
145}
146
147/*
148 * This version of gettimeofday has microsecond resolution.
149 */
150static inline void __do_gettimeofday(struct timeval *tv, unsigned long tb_val)
151{
152 unsigned long sec, usec, tb_ticks;
153 unsigned long xsec, tb_xsec;
154 struct gettimeofday_vars * temp_varp;
155 unsigned long temp_tb_to_xs, temp_stamp_xsec;
156
157 /*
158 * These calculations are faster (gets rid of divides)
159 * if done in units of 1/2^20 rather than microseconds.
160 * The conversion to microseconds at the end is done
161 * without a divide (and in fact, without a multiply)
162 */
163 temp_varp = do_gtod.varp;
164 tb_ticks = tb_val - temp_varp->tb_orig_stamp;
165 temp_tb_to_xs = temp_varp->tb_to_xs;
166 temp_stamp_xsec = temp_varp->stamp_xsec;
167 tb_xsec = mulhdu( tb_ticks, temp_tb_to_xs );
168 xsec = temp_stamp_xsec + tb_xsec;
169 sec = xsec / XSEC_PER_SEC;
170 xsec -= sec * XSEC_PER_SEC;
171 usec = (xsec * USEC_PER_SEC)/XSEC_PER_SEC;
172
173 tv->tv_sec = sec;
174 tv->tv_usec = usec;
175}
176
177void do_gettimeofday(struct timeval *tv)
178{
179 __do_gettimeofday(tv, get_tb());
180}
181
182EXPORT_SYMBOL(do_gettimeofday);
183
184/* Synchronize xtime with do_gettimeofday */
185
186static inline void timer_sync_xtime(unsigned long cur_tb)
187{
188 struct timeval my_tv;
189
190 __do_gettimeofday(&my_tv, cur_tb);
191
192 if (xtime.tv_sec <= my_tv.tv_sec) {
193 xtime.tv_sec = my_tv.tv_sec;
194 xtime.tv_nsec = my_tv.tv_usec * 1000;
195 }
196}
197
198/*
199 * When the timebase - tb_orig_stamp gets too big, we do a manipulation
200 * between tb_orig_stamp and stamp_xsec. The goal here is to keep the
201 * difference tb - tb_orig_stamp small enough to always fit inside a
202 * 32 bits number. This is a requirement of our fast 32 bits userland
203 * implementation in the vdso. If we "miss" a call to this function
204 * (interrupt latency, CPU locked in a spinlock, ...) and we end up
205 * with a too big difference, then the vdso will fallback to calling
206 * the syscall
207 */
208static __inline__ void timer_recalc_offset(unsigned long cur_tb)
209{
210 struct gettimeofday_vars * temp_varp;
211 unsigned temp_idx;
212 unsigned long offset, new_stamp_xsec, new_tb_orig_stamp;
213
214 if (((cur_tb - do_gtod.varp->tb_orig_stamp) & 0x80000000u) == 0)
215 return;
216
217 temp_idx = (do_gtod.var_idx == 0);
218 temp_varp = &do_gtod.vars[temp_idx];
219
220 new_tb_orig_stamp = cur_tb;
221 offset = new_tb_orig_stamp - do_gtod.varp->tb_orig_stamp;
222 new_stamp_xsec = do_gtod.varp->stamp_xsec + mulhdu(offset, do_gtod.varp->tb_to_xs);
223
224 temp_varp->tb_to_xs = do_gtod.varp->tb_to_xs;
225 temp_varp->tb_orig_stamp = new_tb_orig_stamp;
226 temp_varp->stamp_xsec = new_stamp_xsec;
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700227 smp_mb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700228 do_gtod.varp = temp_varp;
229 do_gtod.var_idx = temp_idx;
230
231 ++(systemcfg->tb_update_count);
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700232 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700233 systemcfg->tb_orig_stamp = new_tb_orig_stamp;
234 systemcfg->stamp_xsec = new_stamp_xsec;
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700235 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700236 ++(systemcfg->tb_update_count);
237}
238
239#ifdef CONFIG_SMP
240unsigned long profile_pc(struct pt_regs *regs)
241{
242 unsigned long pc = instruction_pointer(regs);
243
244 if (in_lock_functions(pc))
245 return regs->link;
246
247 return pc;
248}
249EXPORT_SYMBOL(profile_pc);
250#endif
251
252#ifdef CONFIG_PPC_ISERIES
253
254/*
255 * This function recalibrates the timebase based on the 49-bit time-of-day
256 * value in the Titan chip. The Titan is much more accurate than the value
257 * returned by the service processor for the timebase frequency.
258 */
259
260static void iSeries_tb_recal(void)
261{
262 struct div_result divres;
263 unsigned long titan, tb;
264 tb = get_tb();
265 titan = HvCallXm_loadTod();
266 if ( iSeries_recal_titan ) {
267 unsigned long tb_ticks = tb - iSeries_recal_tb;
268 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
269 unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
270 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
271 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
272 char sign = '+';
273 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
274 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
275
276 if ( tick_diff < 0 ) {
277 tick_diff = -tick_diff;
278 sign = '-';
279 }
280 if ( tick_diff ) {
281 if ( tick_diff < tb_ticks_per_jiffy/25 ) {
282 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
283 new_tb_ticks_per_jiffy, sign, tick_diff );
284 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
285 tb_ticks_per_sec = new_tb_ticks_per_sec;
286 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
287 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
288 tb_to_xs = divres.result_low;
289 do_gtod.varp->tb_to_xs = tb_to_xs;
290 systemcfg->tb_ticks_per_sec = tb_ticks_per_sec;
291 systemcfg->tb_to_xs = tb_to_xs;
292 }
293 else {
294 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
295 " new tb_ticks_per_jiffy = %lu\n"
296 " old tb_ticks_per_jiffy = %lu\n",
297 new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
298 }
299 }
300 }
301 iSeries_recal_titan = titan;
302 iSeries_recal_tb = tb;
303}
304#endif
305
306/*
307 * For iSeries shared processors, we have to let the hypervisor
308 * set the hardware decrementer. We set a virtual decrementer
309 * in the lppaca and call the hypervisor if the virtual
310 * decrementer is less than the current value in the hardware
311 * decrementer. (almost always the new decrementer value will
312 * be greater than the current hardware decementer so the hypervisor
313 * call will not be needed)
314 */
315
316unsigned long tb_last_stamp __cacheline_aligned_in_smp;
317
318/*
319 * timer_interrupt - gets called when the decrementer overflows,
320 * with interrupts disabled.
321 */
322int timer_interrupt(struct pt_regs * regs)
323{
324 int next_dec;
325 unsigned long cur_tb;
326 struct paca_struct *lpaca = get_paca();
327 unsigned long cpu = smp_processor_id();
328
329 irq_enter();
330
Linus Torvalds1da177e2005-04-16 15:20:36 -0700331 profile_tick(CPU_PROFILING, regs);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700332
333 lpaca->lppaca.int_dword.fields.decr_int = 0;
334
335 while (lpaca->next_jiffy_update_tb <= (cur_tb = get_tb())) {
336 /*
337 * We cannot disable the decrementer, so in the period
338 * between this cpu's being marked offline in cpu_online_map
339 * and calling stop-self, it is taking timer interrupts.
340 * Avoid calling into the scheduler rebalancing code if this
341 * is the case.
342 */
343 if (!cpu_is_offline(cpu))
344 update_process_times(user_mode(regs));
345 /*
346 * No need to check whether cpu is offline here; boot_cpuid
347 * should have been fixed up by now.
348 */
349 if (cpu == boot_cpuid) {
350 write_seqlock(&xtime_lock);
351 tb_last_stamp = lpaca->next_jiffy_update_tb;
352 timer_recalc_offset(lpaca->next_jiffy_update_tb);
353 do_timer(regs);
354 timer_sync_xtime(lpaca->next_jiffy_update_tb);
355 timer_check_rtc();
356 write_sequnlock(&xtime_lock);
357 if ( adjusting_time && (time_adjust == 0) )
358 ppc_adjtimex();
359 }
360 lpaca->next_jiffy_update_tb += tb_ticks_per_jiffy;
361 }
362
363 next_dec = lpaca->next_jiffy_update_tb - cur_tb;
364 if (next_dec > lpaca->default_decr)
365 next_dec = lpaca->default_decr;
366 set_dec(next_dec);
367
368#ifdef CONFIG_PPC_ISERIES
369 {
370 struct ItLpQueue *lpq = lpaca->lpqueue_ptr;
371 if (lpq && ItLpQueue_isLpIntPending(lpq))
372 lpevent_count += ItLpQueue_process(lpq, regs);
373 }
374#endif
375
376/* collect purr register values often, for accurate calculations */
377#if defined(CONFIG_PPC_PSERIES)
378 if (cur_cpu_spec->firmware_features & FW_FEATURE_SPLPAR) {
379 struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
380 cu->current_tb = mfspr(SPRN_PURR);
381 }
382#endif
383
384 irq_exit();
385
386 return 1;
387}
388
389/*
390 * Scheduler clock - returns current time in nanosec units.
391 *
392 * Note: mulhdu(a, b) (multiply high double unsigned) returns
393 * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
394 * are 64-bit unsigned numbers.
395 */
396unsigned long long sched_clock(void)
397{
398 return mulhdu(get_tb(), tb_to_ns_scale) << tb_to_ns_shift;
399}
400
401int do_settimeofday(struct timespec *tv)
402{
403 time_t wtm_sec, new_sec = tv->tv_sec;
404 long wtm_nsec, new_nsec = tv->tv_nsec;
405 unsigned long flags;
406 unsigned long delta_xsec;
407 long int tb_delta;
408 unsigned long new_xsec;
409
410 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
411 return -EINVAL;
412
413 write_seqlock_irqsave(&xtime_lock, flags);
414 /* Updating the RTC is not the job of this code. If the time is
415 * stepped under NTP, the RTC will be update after STA_UNSYNC
416 * is cleared. Tool like clock/hwclock either copy the RTC
417 * to the system time, in which case there is no point in writing
418 * to the RTC again, or write to the RTC but then they don't call
419 * settimeofday to perform this operation.
420 */
421#ifdef CONFIG_PPC_ISERIES
422 if ( first_settimeofday ) {
423 iSeries_tb_recal();
424 first_settimeofday = 0;
425 }
426#endif
427 tb_delta = tb_ticks_since(tb_last_stamp);
428 tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
429
430 new_nsec -= tb_delta / tb_ticks_per_usec / 1000;
431
432 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
433 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
434
435 set_normalized_timespec(&xtime, new_sec, new_nsec);
436 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
437
438 /* In case of a large backwards jump in time with NTP, we want the
439 * clock to be updated as soon as the PLL is again in lock.
440 */
441 last_rtc_update = new_sec - 658;
442
443 time_adjust = 0; /* stop active adjtime() */
444 time_status |= STA_UNSYNC;
445 time_maxerror = NTP_PHASE_LIMIT;
446 time_esterror = NTP_PHASE_LIMIT;
447
448 delta_xsec = mulhdu( (tb_last_stamp-do_gtod.varp->tb_orig_stamp),
449 do_gtod.varp->tb_to_xs );
450
451 new_xsec = (new_nsec * XSEC_PER_SEC) / NSEC_PER_SEC;
452 new_xsec += new_sec * XSEC_PER_SEC;
453 if ( new_xsec > delta_xsec ) {
454 do_gtod.varp->stamp_xsec = new_xsec - delta_xsec;
455 systemcfg->stamp_xsec = new_xsec - delta_xsec;
456 }
457 else {
458 /* This is only for the case where the user is setting the time
459 * way back to a time such that the boot time would have been
460 * before 1970 ... eg. we booted ten days ago, and we are setting
461 * the time to Jan 5, 1970 */
462 do_gtod.varp->stamp_xsec = new_xsec;
463 do_gtod.varp->tb_orig_stamp = tb_last_stamp;
464 systemcfg->stamp_xsec = new_xsec;
465 systemcfg->tb_orig_stamp = tb_last_stamp;
466 }
467
468 systemcfg->tz_minuteswest = sys_tz.tz_minuteswest;
469 systemcfg->tz_dsttime = sys_tz.tz_dsttime;
470
471 write_sequnlock_irqrestore(&xtime_lock, flags);
472 clock_was_set();
473 return 0;
474}
475
476EXPORT_SYMBOL(do_settimeofday);
477
Arnd Bergmann10f7e7c2005-06-23 09:43:07 +1000478#if defined(CONFIG_PPC_PSERIES) || defined(CONFIG_PPC_MAPLE) || defined(CONFIG_PPC_BPA)
479void __init generic_calibrate_decr(void)
480{
481 struct device_node *cpu;
482 struct div_result divres;
483 unsigned int *fp;
484 int node_found;
485
486 /*
487 * The cpu node should have a timebase-frequency property
488 * to tell us the rate at which the decrementer counts.
489 */
490 cpu = of_find_node_by_type(NULL, "cpu");
491
492 ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
493 node_found = 0;
494 if (cpu != 0) {
495 fp = (unsigned int *)get_property(cpu, "timebase-frequency",
496 NULL);
497 if (fp != 0) {
498 node_found = 1;
499 ppc_tb_freq = *fp;
500 }
501 }
502 if (!node_found)
503 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
504 "(not found)\n");
505
506 ppc_proc_freq = DEFAULT_PROC_FREQ;
507 node_found = 0;
508 if (cpu != 0) {
509 fp = (unsigned int *)get_property(cpu, "clock-frequency",
510 NULL);
511 if (fp != 0) {
512 node_found = 1;
513 ppc_proc_freq = *fp;
514 }
515 }
516 if (!node_found)
517 printk(KERN_ERR "WARNING: Estimating processor frequency "
518 "(not found)\n");
519
520 of_node_put(cpu);
521
522 printk(KERN_INFO "time_init: decrementer frequency = %lu.%.6lu MHz\n",
523 ppc_tb_freq/1000000, ppc_tb_freq%1000000);
524 printk(KERN_INFO "time_init: processor frequency = %lu.%.6lu MHz\n",
525 ppc_proc_freq/1000000, ppc_proc_freq%1000000);
526
527 tb_ticks_per_jiffy = ppc_tb_freq / HZ;
528 tb_ticks_per_sec = tb_ticks_per_jiffy * HZ;
529 tb_ticks_per_usec = ppc_tb_freq / 1000000;
530 tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
531 div128_by_32(1024*1024, 0, tb_ticks_per_sec, &divres);
532 tb_to_xs = divres.result_low;
533
534 setup_default_decr();
535}
536#endif
537
Linus Torvalds1da177e2005-04-16 15:20:36 -0700538void __init time_init(void)
539{
540 /* This function is only called on the boot processor */
541 unsigned long flags;
542 struct rtc_time tm;
543 struct div_result res;
544 unsigned long scale, shift;
545
546 ppc_md.calibrate_decr();
547
548 /*
549 * Compute scale factor for sched_clock.
550 * The calibrate_decr() function has set tb_ticks_per_sec,
551 * which is the timebase frequency.
552 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
553 * the 128-bit result as a 64.64 fixed-point number.
554 * We then shift that number right until it is less than 1.0,
555 * giving us the scale factor and shift count to use in
556 * sched_clock().
557 */
558 div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
559 scale = res.result_low;
560 for (shift = 0; res.result_high != 0; ++shift) {
561 scale = (scale >> 1) | (res.result_high << 63);
562 res.result_high >>= 1;
563 }
564 tb_to_ns_scale = scale;
565 tb_to_ns_shift = shift;
566
567#ifdef CONFIG_PPC_ISERIES
568 if (!piranha_simulator)
569#endif
570 ppc_md.get_boot_time(&tm);
571
572 write_seqlock_irqsave(&xtime_lock, flags);
573 xtime.tv_sec = mktime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
574 tm.tm_hour, tm.tm_min, tm.tm_sec);
575 tb_last_stamp = get_tb();
576 do_gtod.varp = &do_gtod.vars[0];
577 do_gtod.var_idx = 0;
578 do_gtod.varp->tb_orig_stamp = tb_last_stamp;
Stephen Rothwell8f80e5c2005-05-25 13:41:26 +1000579 get_paca()->next_jiffy_update_tb = tb_last_stamp + tb_ticks_per_jiffy;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700580 do_gtod.varp->stamp_xsec = xtime.tv_sec * XSEC_PER_SEC;
581 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
582 do_gtod.varp->tb_to_xs = tb_to_xs;
583 do_gtod.tb_to_us = tb_to_us;
584 systemcfg->tb_orig_stamp = tb_last_stamp;
585 systemcfg->tb_update_count = 0;
586 systemcfg->tb_ticks_per_sec = tb_ticks_per_sec;
587 systemcfg->stamp_xsec = xtime.tv_sec * XSEC_PER_SEC;
588 systemcfg->tb_to_xs = tb_to_xs;
589
590 time_freq = 0;
591
592 xtime.tv_nsec = 0;
593 last_rtc_update = xtime.tv_sec;
594 set_normalized_timespec(&wall_to_monotonic,
595 -xtime.tv_sec, -xtime.tv_nsec);
596 write_sequnlock_irqrestore(&xtime_lock, flags);
597
598 /* Not exact, but the timer interrupt takes care of this */
599 set_dec(tb_ticks_per_jiffy);
600}
601
602/*
603 * After adjtimex is called, adjust the conversion of tb ticks
604 * to microseconds to keep do_gettimeofday synchronized
605 * with ntpd.
606 *
607 * Use the time_adjust, time_freq and time_offset computed by adjtimex to
608 * adjust the frequency.
609 */
610
611/* #define DEBUG_PPC_ADJTIMEX 1 */
612
613void ppc_adjtimex(void)
614{
615 unsigned long den, new_tb_ticks_per_sec, tb_ticks, old_xsec, new_tb_to_xs, new_xsec, new_stamp_xsec;
616 unsigned long tb_ticks_per_sec_delta;
617 long delta_freq, ltemp;
618 struct div_result divres;
619 unsigned long flags;
620 struct gettimeofday_vars * temp_varp;
621 unsigned temp_idx;
622 long singleshot_ppm = 0;
623
624 /* Compute parts per million frequency adjustment to accomplish the time adjustment
625 implied by time_offset to be applied over the elapsed time indicated by time_constant.
626 Use SHIFT_USEC to get it into the same units as time_freq. */
627 if ( time_offset < 0 ) {
628 ltemp = -time_offset;
629 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
630 ltemp >>= SHIFT_KG + time_constant;
631 ltemp = -ltemp;
632 }
633 else {
634 ltemp = time_offset;
635 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
636 ltemp >>= SHIFT_KG + time_constant;
637 }
638
639 /* If there is a single shot time adjustment in progress */
640 if ( time_adjust ) {
641#ifdef DEBUG_PPC_ADJTIMEX
642 printk("ppc_adjtimex: ");
643 if ( adjusting_time == 0 )
644 printk("starting ");
645 printk("single shot time_adjust = %ld\n", time_adjust);
646#endif
647
648 adjusting_time = 1;
649
650 /* Compute parts per million frequency adjustment to match time_adjust */
651 singleshot_ppm = tickadj * HZ;
652 /*
653 * The adjustment should be tickadj*HZ to match the code in
654 * linux/kernel/timer.c, but experiments show that this is too
655 * large. 3/4 of tickadj*HZ seems about right
656 */
657 singleshot_ppm -= singleshot_ppm / 4;
658 /* Use SHIFT_USEC to get it into the same units as time_freq */
659 singleshot_ppm <<= SHIFT_USEC;
660 if ( time_adjust < 0 )
661 singleshot_ppm = -singleshot_ppm;
662 }
663 else {
664#ifdef DEBUG_PPC_ADJTIMEX
665 if ( adjusting_time )
666 printk("ppc_adjtimex: ending single shot time_adjust\n");
667#endif
668 adjusting_time = 0;
669 }
670
671 /* Add up all of the frequency adjustments */
672 delta_freq = time_freq + ltemp + singleshot_ppm;
673
674 /* Compute a new value for tb_ticks_per_sec based on the frequency adjustment */
675 den = 1000000 * (1 << (SHIFT_USEC - 8));
676 if ( delta_freq < 0 ) {
677 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( (-delta_freq) >> (SHIFT_USEC - 8))) / den;
678 new_tb_ticks_per_sec = tb_ticks_per_sec + tb_ticks_per_sec_delta;
679 }
680 else {
681 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( delta_freq >> (SHIFT_USEC - 8))) / den;
682 new_tb_ticks_per_sec = tb_ticks_per_sec - tb_ticks_per_sec_delta;
683 }
684
685#ifdef DEBUG_PPC_ADJTIMEX
686 printk("ppc_adjtimex: ltemp = %ld, time_freq = %ld, singleshot_ppm = %ld\n", ltemp, time_freq, singleshot_ppm);
687 printk("ppc_adjtimex: tb_ticks_per_sec - base = %ld new = %ld\n", tb_ticks_per_sec, new_tb_ticks_per_sec);
688#endif
689
690 /* Compute a new value of tb_to_xs (used to convert tb to microseconds and a new value of
691 stamp_xsec which is the time (in 1/2^20 second units) corresponding to tb_orig_stamp. This
692 new value of stamp_xsec compensates for the change in frequency (implied by the new tb_to_xs)
693 which guarantees that the current time remains the same */
694 write_seqlock_irqsave( &xtime_lock, flags );
695 tb_ticks = get_tb() - do_gtod.varp->tb_orig_stamp;
696 div128_by_32( 1024*1024, 0, new_tb_ticks_per_sec, &divres );
697 new_tb_to_xs = divres.result_low;
698 new_xsec = mulhdu( tb_ticks, new_tb_to_xs );
699
700 old_xsec = mulhdu( tb_ticks, do_gtod.varp->tb_to_xs );
701 new_stamp_xsec = do_gtod.varp->stamp_xsec + old_xsec - new_xsec;
702
703 /* There are two copies of tb_to_xs and stamp_xsec so that no lock is needed to access and use these
704 values in do_gettimeofday. We alternate the copies and as long as a reasonable time elapses between
705 changes, there will never be inconsistent values. ntpd has a minimum of one minute between updates */
706
707 temp_idx = (do_gtod.var_idx == 0);
708 temp_varp = &do_gtod.vars[temp_idx];
709
710 temp_varp->tb_to_xs = new_tb_to_xs;
711 temp_varp->stamp_xsec = new_stamp_xsec;
712 temp_varp->tb_orig_stamp = do_gtod.varp->tb_orig_stamp;
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700713 smp_mb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714 do_gtod.varp = temp_varp;
715 do_gtod.var_idx = temp_idx;
716
717 /*
718 * tb_update_count is used to allow the problem state gettimeofday code
719 * to assure itself that it sees a consistent view of the tb_to_xs and
720 * stamp_xsec variables. It reads the tb_update_count, then reads
721 * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
722 * the two values of tb_update_count match and are even then the
723 * tb_to_xs and stamp_xsec values are consistent. If not, then it
724 * loops back and reads them again until this criteria is met.
725 */
726 ++(systemcfg->tb_update_count);
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700727 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700728 systemcfg->tb_to_xs = new_tb_to_xs;
729 systemcfg->stamp_xsec = new_stamp_xsec;
Anton Blanchard0d8d4d42005-05-01 08:58:47 -0700730 smp_wmb();
Linus Torvalds1da177e2005-04-16 15:20:36 -0700731 ++(systemcfg->tb_update_count);
732
733 write_sequnlock_irqrestore( &xtime_lock, flags );
734
735}
736
737
738#define TICK_SIZE tick
739#define FEBRUARY 2
740#define STARTOFTIME 1970
741#define SECDAY 86400L
742#define SECYR (SECDAY * 365)
743#define leapyear(year) ((year) % 4 == 0)
744#define days_in_year(a) (leapyear(a) ? 366 : 365)
745#define days_in_month(a) (month_days[(a) - 1])
746
747static int month_days[12] = {
748 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
749};
750
751/*
752 * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
753 */
754void GregorianDay(struct rtc_time * tm)
755{
756 int leapsToDate;
757 int lastYear;
758 int day;
759 int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
760
761 lastYear=tm->tm_year-1;
762
763 /*
764 * Number of leap corrections to apply up to end of last year
765 */
766 leapsToDate = lastYear/4 - lastYear/100 + lastYear/400;
767
768 /*
769 * This year is a leap year if it is divisible by 4 except when it is
770 * divisible by 100 unless it is divisible by 400
771 *
772 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
773 */
774 if((tm->tm_year%4==0) &&
775 ((tm->tm_year%100!=0) || (tm->tm_year%400==0)) &&
776 (tm->tm_mon>2))
777 {
778 /*
779 * We are past Feb. 29 in a leap year
780 */
781 day=1;
782 }
783 else
784 {
785 day=0;
786 }
787
788 day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
789 tm->tm_mday;
790
791 tm->tm_wday=day%7;
792}
793
794void to_tm(int tim, struct rtc_time * tm)
795{
796 register int i;
797 register long hms, day;
798
799 day = tim / SECDAY;
800 hms = tim % SECDAY;
801
802 /* Hours, minutes, seconds are easy */
803 tm->tm_hour = hms / 3600;
804 tm->tm_min = (hms % 3600) / 60;
805 tm->tm_sec = (hms % 3600) % 60;
806
807 /* Number of years in days */
808 for (i = STARTOFTIME; day >= days_in_year(i); i++)
809 day -= days_in_year(i);
810 tm->tm_year = i;
811
812 /* Number of months in days left */
813 if (leapyear(tm->tm_year))
814 days_in_month(FEBRUARY) = 29;
815 for (i = 1; day >= days_in_month(i); i++)
816 day -= days_in_month(i);
817 days_in_month(FEBRUARY) = 28;
818 tm->tm_mon = i;
819
820 /* Days are what is left over (+1) from all that. */
821 tm->tm_mday = day + 1;
822
823 /*
824 * Determine the day of week
825 */
826 GregorianDay(tm);
827}
828
829/* Auxiliary function to compute scaling factors */
830/* Actually the choice of a timebase running at 1/4 the of the bus
831 * frequency giving resolution of a few tens of nanoseconds is quite nice.
832 * It makes this computation very precise (27-28 bits typically) which
833 * is optimistic considering the stability of most processor clock
834 * oscillators and the precision with which the timebase frequency
835 * is measured but does not harm.
836 */
837unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
838 unsigned mlt=0, tmp, err;
839 /* No concern for performance, it's done once: use a stupid
840 * but safe and compact method to find the multiplier.
841 */
842
843 for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
844 if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
845 }
846
847 /* We might still be off by 1 for the best approximation.
848 * A side effect of this is that if outscale is too large
849 * the returned value will be zero.
850 * Many corner cases have been checked and seem to work,
851 * some might have been forgotten in the test however.
852 */
853
854 err = inscale*(mlt+1);
855 if (err <= inscale/2) mlt++;
856 return mlt;
857 }
858
859/*
860 * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
861 * result.
862 */
863
864void div128_by_32( unsigned long dividend_high, unsigned long dividend_low,
865 unsigned divisor, struct div_result *dr )
866{
867 unsigned long a,b,c,d, w,x,y,z, ra,rb,rc;
868
869 a = dividend_high >> 32;
870 b = dividend_high & 0xffffffff;
871 c = dividend_low >> 32;
872 d = dividend_low & 0xffffffff;
873
874 w = a/divisor;
875 ra = (a - (w * divisor)) << 32;
876
877 x = (ra + b)/divisor;
878 rb = ((ra + b) - (x * divisor)) << 32;
879
880 y = (rb + c)/divisor;
881 rc = ((rb + b) - (y * divisor)) << 32;
882
883 z = (rc + d)/divisor;
884
885 dr->result_high = (w << 32) + x;
886 dr->result_low = (y << 32) + z;
887
888}
889