3 * Common time routines among all ppc machines.
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)
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).
16 * Speeded up do_gettimeofday by getting rid of references to
17 * xtime (which required locks for consistency). (mikejc@us.ibm.com)
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.
27 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
28 * "A Kernel Model for Precision Timekeeping" by Dave Mills
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.
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>
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>
55 #include <asm/processor.h>
56 #include <asm/nvram.h>
57 #include <asm/cache.h>
58 #include <asm/machdep.h>
59 #ifdef CONFIG_PPC_ISERIES
60 #include <asm/iSeries/ItLpQueue.h>
61 #include <asm/iSeries/HvCallXm.h>
63 #include <asm/uaccess.h>
65 #include <asm/ppcdebug.h>
67 #include <asm/sections.h>
68 #include <asm/systemcfg.h>
69 #include <asm/firmware.h>
71 /* keep track of when we need to update the rtc */
72 time_t last_rtc_update;
73 extern int piranha_simulator;
74 #ifdef CONFIG_PPC_ISERIES
75 unsigned long iSeries_recal_titan = 0;
76 unsigned long iSeries_recal_tb = 0;
77 static unsigned long first_settimeofday = 1;
80 #define XSEC_PER_SEC (1024*1024)
82 unsigned long tb_ticks_per_jiffy;
83 unsigned long tb_ticks_per_usec = 100; /* sane default */
84 EXPORT_SYMBOL(tb_ticks_per_usec);
85 unsigned long tb_ticks_per_sec;
86 unsigned long tb_to_xs;
88 unsigned long processor_freq;
89 DEFINE_SPINLOCK(rtc_lock);
90 EXPORT_SYMBOL_GPL(rtc_lock);
92 unsigned long tb_to_ns_scale;
93 unsigned long tb_to_ns_shift;
95 struct gettimeofday_struct do_gtod;
97 extern unsigned long wall_jiffies;
98 extern int smp_tb_synchronized;
100 extern struct timezone sys_tz;
102 void ppc_adjtimex(void);
104 static unsigned adjusting_time = 0;
106 unsigned long ppc_proc_freq;
107 unsigned long ppc_tb_freq;
109 static __inline__ void timer_check_rtc(void)
112 * update the rtc when needed, this should be performed on the
113 * right fraction of a second. Half or full second ?
114 * Full second works on mk48t59 clocks, others need testing.
115 * Note that this update is basically only used through
116 * the adjtimex system calls. Setting the HW clock in
117 * any other way is a /dev/rtc and userland business.
118 * This is still wrong by -0.5/+1.5 jiffies because of the
119 * timer interrupt resolution and possible delay, but here we
120 * hit a quantization limit which can only be solved by higher
121 * resolution timers and decoupling time management from timer
122 * interrupts. This is also wrong on the clocks
123 * which require being written at the half second boundary.
124 * We should have an rtc call that only sets the minutes and
125 * seconds like on Intel to avoid problems with non UTC clocks.
128 xtime.tv_sec - last_rtc_update >= 659 &&
129 abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ &&
130 jiffies - wall_jiffies == 1) {
132 to_tm(xtime.tv_sec+1, &tm);
135 if (ppc_md.set_rtc_time(&tm) == 0)
136 last_rtc_update = xtime.tv_sec+1;
138 /* Try again one minute later */
139 last_rtc_update += 60;
144 * This version of gettimeofday has microsecond resolution.
146 static inline void __do_gettimeofday(struct timeval *tv, unsigned long tb_val)
148 unsigned long sec, usec, tb_ticks;
149 unsigned long xsec, tb_xsec;
150 struct gettimeofday_vars * temp_varp;
151 unsigned long temp_tb_to_xs, temp_stamp_xsec;
154 * These calculations are faster (gets rid of divides)
155 * if done in units of 1/2^20 rather than microseconds.
156 * The conversion to microseconds at the end is done
157 * without a divide (and in fact, without a multiply)
159 temp_varp = do_gtod.varp;
160 tb_ticks = tb_val - temp_varp->tb_orig_stamp;
161 temp_tb_to_xs = temp_varp->tb_to_xs;
162 temp_stamp_xsec = temp_varp->stamp_xsec;
163 tb_xsec = mulhdu( tb_ticks, temp_tb_to_xs );
164 xsec = temp_stamp_xsec + tb_xsec;
165 sec = xsec / XSEC_PER_SEC;
166 xsec -= sec * XSEC_PER_SEC;
167 usec = (xsec * USEC_PER_SEC)/XSEC_PER_SEC;
173 void do_gettimeofday(struct timeval *tv)
175 __do_gettimeofday(tv, get_tb());
178 EXPORT_SYMBOL(do_gettimeofday);
180 /* Synchronize xtime with do_gettimeofday */
182 static inline void timer_sync_xtime(unsigned long cur_tb)
184 struct timeval my_tv;
186 __do_gettimeofday(&my_tv, cur_tb);
188 if (xtime.tv_sec <= my_tv.tv_sec) {
189 xtime.tv_sec = my_tv.tv_sec;
190 xtime.tv_nsec = my_tv.tv_usec * 1000;
195 * When the timebase - tb_orig_stamp gets too big, we do a manipulation
196 * between tb_orig_stamp and stamp_xsec. The goal here is to keep the
197 * difference tb - tb_orig_stamp small enough to always fit inside a
198 * 32 bits number. This is a requirement of our fast 32 bits userland
199 * implementation in the vdso. If we "miss" a call to this function
200 * (interrupt latency, CPU locked in a spinlock, ...) and we end up
201 * with a too big difference, then the vdso will fallback to calling
204 static __inline__ void timer_recalc_offset(unsigned long cur_tb)
206 struct gettimeofday_vars * temp_varp;
208 unsigned long offset, new_stamp_xsec, new_tb_orig_stamp;
210 if (((cur_tb - do_gtod.varp->tb_orig_stamp) & 0x80000000u) == 0)
213 temp_idx = (do_gtod.var_idx == 0);
214 temp_varp = &do_gtod.vars[temp_idx];
216 new_tb_orig_stamp = cur_tb;
217 offset = new_tb_orig_stamp - do_gtod.varp->tb_orig_stamp;
218 new_stamp_xsec = do_gtod.varp->stamp_xsec + mulhdu(offset, do_gtod.varp->tb_to_xs);
220 temp_varp->tb_to_xs = do_gtod.varp->tb_to_xs;
221 temp_varp->tb_orig_stamp = new_tb_orig_stamp;
222 temp_varp->stamp_xsec = new_stamp_xsec;
224 do_gtod.varp = temp_varp;
225 do_gtod.var_idx = temp_idx;
227 ++(systemcfg->tb_update_count);
229 systemcfg->tb_orig_stamp = new_tb_orig_stamp;
230 systemcfg->stamp_xsec = new_stamp_xsec;
232 ++(systemcfg->tb_update_count);
236 unsigned long profile_pc(struct pt_regs *regs)
238 unsigned long pc = instruction_pointer(regs);
240 if (in_lock_functions(pc))
245 EXPORT_SYMBOL(profile_pc);
248 #ifdef CONFIG_PPC_ISERIES
251 * This function recalibrates the timebase based on the 49-bit time-of-day
252 * value in the Titan chip. The Titan is much more accurate than the value
253 * returned by the service processor for the timebase frequency.
256 static void iSeries_tb_recal(void)
258 struct div_result divres;
259 unsigned long titan, tb;
261 titan = HvCallXm_loadTod();
262 if ( iSeries_recal_titan ) {
263 unsigned long tb_ticks = tb - iSeries_recal_tb;
264 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
265 unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
266 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
267 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
269 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
270 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
272 if ( tick_diff < 0 ) {
273 tick_diff = -tick_diff;
277 if ( tick_diff < tb_ticks_per_jiffy/25 ) {
278 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
279 new_tb_ticks_per_jiffy, sign, tick_diff );
280 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
281 tb_ticks_per_sec = new_tb_ticks_per_sec;
282 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
283 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
284 tb_to_xs = divres.result_low;
285 do_gtod.varp->tb_to_xs = tb_to_xs;
286 systemcfg->tb_ticks_per_sec = tb_ticks_per_sec;
287 systemcfg->tb_to_xs = tb_to_xs;
290 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
291 " new tb_ticks_per_jiffy = %lu\n"
292 " old tb_ticks_per_jiffy = %lu\n",
293 new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
297 iSeries_recal_titan = titan;
298 iSeries_recal_tb = tb;
303 * For iSeries shared processors, we have to let the hypervisor
304 * set the hardware decrementer. We set a virtual decrementer
305 * in the lppaca and call the hypervisor if the virtual
306 * decrementer is less than the current value in the hardware
307 * decrementer. (almost always the new decrementer value will
308 * be greater than the current hardware decementer so the hypervisor
309 * call will not be needed)
312 unsigned long tb_last_stamp __cacheline_aligned_in_smp;
315 * timer_interrupt - gets called when the decrementer overflows,
316 * with interrupts disabled.
318 int timer_interrupt(struct pt_regs * regs)
321 unsigned long cur_tb;
322 struct paca_struct *lpaca = get_paca();
323 unsigned long cpu = smp_processor_id();
327 profile_tick(CPU_PROFILING, regs);
329 lpaca->lppaca.int_dword.fields.decr_int = 0;
331 while (lpaca->next_jiffy_update_tb <= (cur_tb = get_tb())) {
333 * We cannot disable the decrementer, so in the period
334 * between this cpu's being marked offline in cpu_online_map
335 * and calling stop-self, it is taking timer interrupts.
336 * Avoid calling into the scheduler rebalancing code if this
339 if (!cpu_is_offline(cpu))
340 update_process_times(user_mode(regs));
342 * No need to check whether cpu is offline here; boot_cpuid
343 * should have been fixed up by now.
345 if (cpu == boot_cpuid) {
346 write_seqlock(&xtime_lock);
347 tb_last_stamp = lpaca->next_jiffy_update_tb;
348 timer_recalc_offset(lpaca->next_jiffy_update_tb);
350 timer_sync_xtime(lpaca->next_jiffy_update_tb);
352 write_sequnlock(&xtime_lock);
353 if ( adjusting_time && (time_adjust == 0) )
356 lpaca->next_jiffy_update_tb += tb_ticks_per_jiffy;
359 next_dec = lpaca->next_jiffy_update_tb - cur_tb;
360 if (next_dec > lpaca->default_decr)
361 next_dec = lpaca->default_decr;
364 #ifdef CONFIG_PPC_ISERIES
365 if (hvlpevent_is_pending())
366 process_hvlpevents(regs);
369 /* collect purr register values often, for accurate calculations */
370 if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
371 struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
372 cu->current_tb = mfspr(SPRN_PURR);
381 * Scheduler clock - returns current time in nanosec units.
383 * Note: mulhdu(a, b) (multiply high double unsigned) returns
384 * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
385 * are 64-bit unsigned numbers.
387 unsigned long long sched_clock(void)
389 return mulhdu(get_tb(), tb_to_ns_scale) << tb_to_ns_shift;
392 int do_settimeofday(struct timespec *tv)
394 time_t wtm_sec, new_sec = tv->tv_sec;
395 long wtm_nsec, new_nsec = tv->tv_nsec;
397 unsigned long delta_xsec;
399 unsigned long new_xsec;
401 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
404 write_seqlock_irqsave(&xtime_lock, flags);
405 /* Updating the RTC is not the job of this code. If the time is
406 * stepped under NTP, the RTC will be update after STA_UNSYNC
407 * is cleared. Tool like clock/hwclock either copy the RTC
408 * to the system time, in which case there is no point in writing
409 * to the RTC again, or write to the RTC but then they don't call
410 * settimeofday to perform this operation.
412 #ifdef CONFIG_PPC_ISERIES
413 if ( first_settimeofday ) {
415 first_settimeofday = 0;
418 tb_delta = tb_ticks_since(tb_last_stamp);
419 tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
421 new_nsec -= tb_delta / tb_ticks_per_usec / 1000;
423 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
424 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
426 set_normalized_timespec(&xtime, new_sec, new_nsec);
427 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
429 /* In case of a large backwards jump in time with NTP, we want the
430 * clock to be updated as soon as the PLL is again in lock.
432 last_rtc_update = new_sec - 658;
436 delta_xsec = mulhdu( (tb_last_stamp-do_gtod.varp->tb_orig_stamp),
437 do_gtod.varp->tb_to_xs );
439 new_xsec = (new_nsec * XSEC_PER_SEC) / NSEC_PER_SEC;
440 new_xsec += new_sec * XSEC_PER_SEC;
441 if ( new_xsec > delta_xsec ) {
442 do_gtod.varp->stamp_xsec = new_xsec - delta_xsec;
443 systemcfg->stamp_xsec = new_xsec - delta_xsec;
446 /* This is only for the case where the user is setting the time
447 * way back to a time such that the boot time would have been
448 * before 1970 ... eg. we booted ten days ago, and we are setting
449 * the time to Jan 5, 1970 */
450 do_gtod.varp->stamp_xsec = new_xsec;
451 do_gtod.varp->tb_orig_stamp = tb_last_stamp;
452 systemcfg->stamp_xsec = new_xsec;
453 systemcfg->tb_orig_stamp = tb_last_stamp;
456 systemcfg->tz_minuteswest = sys_tz.tz_minuteswest;
457 systemcfg->tz_dsttime = sys_tz.tz_dsttime;
459 write_sequnlock_irqrestore(&xtime_lock, flags);
464 EXPORT_SYMBOL(do_settimeofday);
466 #if defined(CONFIG_PPC_PSERIES) || defined(CONFIG_PPC_MAPLE) || defined(CONFIG_PPC_BPA)
467 void __init generic_calibrate_decr(void)
469 struct device_node *cpu;
470 struct div_result divres;
475 * The cpu node should have a timebase-frequency property
476 * to tell us the rate at which the decrementer counts.
478 cpu = of_find_node_by_type(NULL, "cpu");
480 ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
483 fp = (unsigned int *)get_property(cpu, "timebase-frequency",
491 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
494 ppc_proc_freq = DEFAULT_PROC_FREQ;
497 fp = (unsigned int *)get_property(cpu, "clock-frequency",
505 printk(KERN_ERR "WARNING: Estimating processor frequency "
510 printk(KERN_INFO "time_init: decrementer frequency = %lu.%.6lu MHz\n",
511 ppc_tb_freq/1000000, ppc_tb_freq%1000000);
512 printk(KERN_INFO "time_init: processor frequency = %lu.%.6lu MHz\n",
513 ppc_proc_freq/1000000, ppc_proc_freq%1000000);
515 tb_ticks_per_jiffy = ppc_tb_freq / HZ;
516 tb_ticks_per_sec = tb_ticks_per_jiffy * HZ;
517 tb_ticks_per_usec = ppc_tb_freq / 1000000;
518 tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
519 div128_by_32(1024*1024, 0, tb_ticks_per_sec, &divres);
520 tb_to_xs = divres.result_low;
522 setup_default_decr();
526 void __init time_init(void)
528 /* This function is only called on the boot processor */
531 struct div_result res;
532 unsigned long scale, shift;
534 ppc_md.calibrate_decr();
537 * Compute scale factor for sched_clock.
538 * The calibrate_decr() function has set tb_ticks_per_sec,
539 * which is the timebase frequency.
540 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
541 * the 128-bit result as a 64.64 fixed-point number.
542 * We then shift that number right until it is less than 1.0,
543 * giving us the scale factor and shift count to use in
546 div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
547 scale = res.result_low;
548 for (shift = 0; res.result_high != 0; ++shift) {
549 scale = (scale >> 1) | (res.result_high << 63);
550 res.result_high >>= 1;
552 tb_to_ns_scale = scale;
553 tb_to_ns_shift = shift;
555 #ifdef CONFIG_PPC_ISERIES
556 if (!piranha_simulator)
558 ppc_md.get_boot_time(&tm);
560 write_seqlock_irqsave(&xtime_lock, flags);
561 xtime.tv_sec = mktime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
562 tm.tm_hour, tm.tm_min, tm.tm_sec);
563 tb_last_stamp = get_tb();
564 do_gtod.varp = &do_gtod.vars[0];
566 do_gtod.varp->tb_orig_stamp = tb_last_stamp;
567 get_paca()->next_jiffy_update_tb = tb_last_stamp + tb_ticks_per_jiffy;
568 do_gtod.varp->stamp_xsec = xtime.tv_sec * XSEC_PER_SEC;
569 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
570 do_gtod.varp->tb_to_xs = tb_to_xs;
571 do_gtod.tb_to_us = tb_to_us;
572 systemcfg->tb_orig_stamp = tb_last_stamp;
573 systemcfg->tb_update_count = 0;
574 systemcfg->tb_ticks_per_sec = tb_ticks_per_sec;
575 systemcfg->stamp_xsec = xtime.tv_sec * XSEC_PER_SEC;
576 systemcfg->tb_to_xs = tb_to_xs;
581 last_rtc_update = xtime.tv_sec;
582 set_normalized_timespec(&wall_to_monotonic,
583 -xtime.tv_sec, -xtime.tv_nsec);
584 write_sequnlock_irqrestore(&xtime_lock, flags);
586 /* Not exact, but the timer interrupt takes care of this */
587 set_dec(tb_ticks_per_jiffy);
591 * After adjtimex is called, adjust the conversion of tb ticks
592 * to microseconds to keep do_gettimeofday synchronized
595 * Use the time_adjust, time_freq and time_offset computed by adjtimex to
596 * adjust the frequency.
599 /* #define DEBUG_PPC_ADJTIMEX 1 */
601 void ppc_adjtimex(void)
603 unsigned long den, new_tb_ticks_per_sec, tb_ticks, old_xsec, new_tb_to_xs, new_xsec, new_stamp_xsec;
604 unsigned long tb_ticks_per_sec_delta;
605 long delta_freq, ltemp;
606 struct div_result divres;
608 struct gettimeofday_vars * temp_varp;
610 long singleshot_ppm = 0;
612 /* Compute parts per million frequency adjustment to accomplish the time adjustment
613 implied by time_offset to be applied over the elapsed time indicated by time_constant.
614 Use SHIFT_USEC to get it into the same units as time_freq. */
615 if ( time_offset < 0 ) {
616 ltemp = -time_offset;
617 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
618 ltemp >>= SHIFT_KG + time_constant;
623 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
624 ltemp >>= SHIFT_KG + time_constant;
627 /* If there is a single shot time adjustment in progress */
629 #ifdef DEBUG_PPC_ADJTIMEX
630 printk("ppc_adjtimex: ");
631 if ( adjusting_time == 0 )
633 printk("single shot time_adjust = %ld\n", time_adjust);
638 /* Compute parts per million frequency adjustment to match time_adjust */
639 singleshot_ppm = tickadj * HZ;
641 * The adjustment should be tickadj*HZ to match the code in
642 * linux/kernel/timer.c, but experiments show that this is too
643 * large. 3/4 of tickadj*HZ seems about right
645 singleshot_ppm -= singleshot_ppm / 4;
646 /* Use SHIFT_USEC to get it into the same units as time_freq */
647 singleshot_ppm <<= SHIFT_USEC;
648 if ( time_adjust < 0 )
649 singleshot_ppm = -singleshot_ppm;
652 #ifdef DEBUG_PPC_ADJTIMEX
653 if ( adjusting_time )
654 printk("ppc_adjtimex: ending single shot time_adjust\n");
659 /* Add up all of the frequency adjustments */
660 delta_freq = time_freq + ltemp + singleshot_ppm;
662 /* Compute a new value for tb_ticks_per_sec based on the frequency adjustment */
663 den = 1000000 * (1 << (SHIFT_USEC - 8));
664 if ( delta_freq < 0 ) {
665 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( (-delta_freq) >> (SHIFT_USEC - 8))) / den;
666 new_tb_ticks_per_sec = tb_ticks_per_sec + tb_ticks_per_sec_delta;
669 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( delta_freq >> (SHIFT_USEC - 8))) / den;
670 new_tb_ticks_per_sec = tb_ticks_per_sec - tb_ticks_per_sec_delta;
673 #ifdef DEBUG_PPC_ADJTIMEX
674 printk("ppc_adjtimex: ltemp = %ld, time_freq = %ld, singleshot_ppm = %ld\n", ltemp, time_freq, singleshot_ppm);
675 printk("ppc_adjtimex: tb_ticks_per_sec - base = %ld new = %ld\n", tb_ticks_per_sec, new_tb_ticks_per_sec);
678 /* Compute a new value of tb_to_xs (used to convert tb to microseconds and a new value of
679 stamp_xsec which is the time (in 1/2^20 second units) corresponding to tb_orig_stamp. This
680 new value of stamp_xsec compensates for the change in frequency (implied by the new tb_to_xs)
681 which guarantees that the current time remains the same */
682 write_seqlock_irqsave( &xtime_lock, flags );
683 tb_ticks = get_tb() - do_gtod.varp->tb_orig_stamp;
684 div128_by_32( 1024*1024, 0, new_tb_ticks_per_sec, &divres );
685 new_tb_to_xs = divres.result_low;
686 new_xsec = mulhdu( tb_ticks, new_tb_to_xs );
688 old_xsec = mulhdu( tb_ticks, do_gtod.varp->tb_to_xs );
689 new_stamp_xsec = do_gtod.varp->stamp_xsec + old_xsec - new_xsec;
691 /* There are two copies of tb_to_xs and stamp_xsec so that no lock is needed to access and use these
692 values in do_gettimeofday. We alternate the copies and as long as a reasonable time elapses between
693 changes, there will never be inconsistent values. ntpd has a minimum of one minute between updates */
695 temp_idx = (do_gtod.var_idx == 0);
696 temp_varp = &do_gtod.vars[temp_idx];
698 temp_varp->tb_to_xs = new_tb_to_xs;
699 temp_varp->stamp_xsec = new_stamp_xsec;
700 temp_varp->tb_orig_stamp = do_gtod.varp->tb_orig_stamp;
702 do_gtod.varp = temp_varp;
703 do_gtod.var_idx = temp_idx;
706 * tb_update_count is used to allow the problem state gettimeofday code
707 * to assure itself that it sees a consistent view of the tb_to_xs and
708 * stamp_xsec variables. It reads the tb_update_count, then reads
709 * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
710 * the two values of tb_update_count match and are even then the
711 * tb_to_xs and stamp_xsec values are consistent. If not, then it
712 * loops back and reads them again until this criteria is met.
714 ++(systemcfg->tb_update_count);
716 systemcfg->tb_to_xs = new_tb_to_xs;
717 systemcfg->stamp_xsec = new_stamp_xsec;
719 ++(systemcfg->tb_update_count);
721 write_sequnlock_irqrestore( &xtime_lock, flags );
726 #define TICK_SIZE tick
728 #define STARTOFTIME 1970
729 #define SECDAY 86400L
730 #define SECYR (SECDAY * 365)
731 #define leapyear(year) ((year) % 4 == 0)
732 #define days_in_year(a) (leapyear(a) ? 366 : 365)
733 #define days_in_month(a) (month_days[(a) - 1])
735 static int month_days[12] = {
736 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
740 * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
742 void GregorianDay(struct rtc_time * tm)
747 int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
749 lastYear=tm->tm_year-1;
752 * Number of leap corrections to apply up to end of last year
754 leapsToDate = lastYear/4 - lastYear/100 + lastYear/400;
757 * This year is a leap year if it is divisible by 4 except when it is
758 * divisible by 100 unless it is divisible by 400
760 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
762 if((tm->tm_year%4==0) &&
763 ((tm->tm_year%100!=0) || (tm->tm_year%400==0)) &&
767 * We are past Feb. 29 in a leap year
776 day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
782 void to_tm(int tim, struct rtc_time * tm)
785 register long hms, day;
790 /* Hours, minutes, seconds are easy */
791 tm->tm_hour = hms / 3600;
792 tm->tm_min = (hms % 3600) / 60;
793 tm->tm_sec = (hms % 3600) % 60;
795 /* Number of years in days */
796 for (i = STARTOFTIME; day >= days_in_year(i); i++)
797 day -= days_in_year(i);
800 /* Number of months in days left */
801 if (leapyear(tm->tm_year))
802 days_in_month(FEBRUARY) = 29;
803 for (i = 1; day >= days_in_month(i); i++)
804 day -= days_in_month(i);
805 days_in_month(FEBRUARY) = 28;
808 /* Days are what is left over (+1) from all that. */
809 tm->tm_mday = day + 1;
812 * Determine the day of week
817 /* Auxiliary function to compute scaling factors */
818 /* Actually the choice of a timebase running at 1/4 the of the bus
819 * frequency giving resolution of a few tens of nanoseconds is quite nice.
820 * It makes this computation very precise (27-28 bits typically) which
821 * is optimistic considering the stability of most processor clock
822 * oscillators and the precision with which the timebase frequency
823 * is measured but does not harm.
825 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
826 unsigned mlt=0, tmp, err;
827 /* No concern for performance, it's done once: use a stupid
828 * but safe and compact method to find the multiplier.
831 for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
832 if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
835 /* We might still be off by 1 for the best approximation.
836 * A side effect of this is that if outscale is too large
837 * the returned value will be zero.
838 * Many corner cases have been checked and seem to work,
839 * some might have been forgotten in the test however.
842 err = inscale*(mlt+1);
843 if (err <= inscale/2) mlt++;
848 * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
852 void div128_by_32( unsigned long dividend_high, unsigned long dividend_low,
853 unsigned divisor, struct div_result *dr )
855 unsigned long a,b,c,d, w,x,y,z, ra,rb,rc;
857 a = dividend_high >> 32;
858 b = dividend_high & 0xffffffff;
859 c = dividend_low >> 32;
860 d = dividend_low & 0xffffffff;
863 ra = (a - (w * divisor)) << 32;
865 x = (ra + b)/divisor;
866 rb = ((ra + b) - (x * divisor)) << 32;
868 y = (rb + c)/divisor;
869 rc = ((rb + c) - (y * divisor)) << 32;
871 z = (rc + d)/divisor;
873 dr->result_high = (w << 32) + x;
874 dr->result_low = (y << 32) + z;