commented early_printk patch because of rejects.
[linux-flexiantxendom0-3.2.10.git] / arch / ppc64 / kernel / time.c
1 /*
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/sched.h>
39 #include <linux/kernel.h>
40 #include <linux/param.h>
41 #include <linux/string.h>
42 #include <linux/mm.h>
43 #include <linux/interrupt.h>
44 #include <linux/timex.h>
45 #include <linux/kernel_stat.h>
46 #include <linux/mc146818rtc.h>
47 #include <linux/time.h>
48 #include <linux/init.h>
49 #include <linux/profile.h>
50
51 #include <asm/segment.h>
52 #include <asm/io.h>
53 #include <asm/processor.h>
54 #include <asm/nvram.h>
55 #include <asm/cache.h>
56 #include <asm/machdep.h>
57 #ifdef CONFIG_PPC_ISERIES
58 #include <asm/iSeries/HvCallXm.h>
59 #endif
60 #include <asm/uaccess.h>
61 #include <asm/time.h>
62 #include <asm/ppcdebug.h>
63 #include <asm/prom.h>
64 #include <asm/sections.h>
65
66 void smp_local_timer_interrupt(struct pt_regs *);
67
68 u64 jiffies_64 = INITIAL_JIFFIES;
69
70 /* keep track of when we need to update the rtc */
71 time_t last_rtc_update;
72 extern int piranha_simulator;
73 #ifdef CONFIG_PPC_ISERIES
74 unsigned long iSeries_recal_titan = 0;
75 unsigned long iSeries_recal_tb = 0; 
76 static unsigned long first_settimeofday = 1;
77 #endif
78
79 #define XSEC_PER_SEC (1024*1024)
80
81 unsigned long tb_ticks_per_jiffy;
82 unsigned long tb_ticks_per_usec;
83 unsigned long tb_ticks_per_sec;
84 unsigned long next_xtime_sync_tb;
85 unsigned long xtime_sync_interval;
86 unsigned long tb_to_xs;
87 unsigned      tb_to_us;
88 unsigned long processor_freq;
89 spinlock_t rtc_lock = SPIN_LOCK_UNLOCKED;
90
91 struct gettimeofday_struct do_gtod;
92
93 extern unsigned long wall_jiffies;
94 extern unsigned long lpEvent_count;
95 extern int smp_tb_synchronized;
96
97 void ppc_adjtimex(void);
98
99 static unsigned adjusting_time = 0;
100
101 /*
102  * The profiling function is SMP safe. (nothing can mess
103  * around with "current", and the profiling counters are
104  * updated with atomic operations). This is especially
105  * useful with a profiling multiplier != 1
106  */
107 static inline void ppc64_do_profile(struct pt_regs *regs)
108 {
109         unsigned long nip;
110         extern unsigned long prof_cpu_mask;
111
112         profile_hook(regs);
113
114         if (user_mode(regs))
115                 return;
116
117         if (!prof_buffer)
118                 return;
119
120         nip = instruction_pointer(regs);
121
122         /*
123          * Only measure the CPUs specified by /proc/irq/prof_cpu_mask.
124          * (default is all CPUs.)
125          */
126         if (!((1<<smp_processor_id()) & prof_cpu_mask))
127                 return;
128
129         nip -= (unsigned long)_stext;
130         nip >>= prof_shift;
131         /*
132          * Don't ignore out-of-bounds EIP values silently,
133          * put them into the last histogram slot, so if
134          * present, they will show up as a sharp peak.
135          */
136         if (nip > prof_len-1)
137                 nip = prof_len-1;
138         atomic_inc((atomic_t *)&prof_buffer[nip]);
139 }
140
141 static __inline__ void timer_check_rtc(void)
142 {
143         /*
144          * update the rtc when needed, this should be performed on the
145          * right fraction of a second. Half or full second ?
146          * Full second works on mk48t59 clocks, others need testing.
147          * Note that this update is basically only used through 
148          * the adjtimex system calls. Setting the HW clock in
149          * any other way is a /dev/rtc and userland business.
150          * This is still wrong by -0.5/+1.5 jiffies because of the
151          * timer interrupt resolution and possible delay, but here we 
152          * hit a quantization limit which can only be solved by higher
153          * resolution timers and decoupling time management from timer
154          * interrupts. This is also wrong on the clocks
155          * which require being written at the half second boundary.
156          * We should have an rtc call that only sets the minutes and
157          * seconds like on Intel to avoid problems with non UTC clocks.
158          */
159         if ( (time_status & STA_UNSYNC) == 0 &&
160              xtime.tv_sec - last_rtc_update >= 659 &&
161              abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ &&
162              jiffies - wall_jiffies == 1) {
163             struct rtc_time tm;
164             to_tm(xtime.tv_sec+1, &tm);
165             tm.tm_year -= 1900;
166             tm.tm_mon -= 1;
167             if (ppc_md.set_rtc_time(&tm) == 0)
168                 last_rtc_update = xtime.tv_sec+1;
169             else
170                 /* Try again one minute later */
171                 last_rtc_update += 60;
172         }
173 }
174
175 /* Synchronize xtime with do_gettimeofday */ 
176
177 static __inline__ void timer_sync_xtime( unsigned long cur_tb )
178 {
179         struct timeval my_tv;
180
181         if ( cur_tb > next_xtime_sync_tb ) {
182                 next_xtime_sync_tb = cur_tb + xtime_sync_interval;
183                 do_gettimeofday( &my_tv );
184                 if ( xtime.tv_sec <= my_tv.tv_sec ) {
185                         xtime.tv_sec = my_tv.tv_sec;
186                         xtime.tv_nsec = my_tv.tv_usec * 1000;
187                 }
188         }
189 }
190
191 #ifdef CONFIG_PPC_ISERIES
192
193 /* 
194  * This function recalibrates the timebase based on the 49-bit time-of-day
195  * value in the Titan chip.  The Titan is much more accurate than the value
196  * returned by the service processor for the timebase frequency.  
197  */
198
199 static void iSeries_tb_recal(void)
200 {
201         struct div_result divres;
202         unsigned long titan, tb;
203         tb = get_tb();
204         titan = HvCallXm_loadTod();
205         if ( iSeries_recal_titan ) {
206                 unsigned long tb_ticks = tb - iSeries_recal_tb;
207                 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
208                 unsigned long new_tb_ticks_per_sec   = (tb_ticks * USEC_PER_SEC)/titan_usec;
209                 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
210                 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
211                 char sign = '+';                
212                 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
213                 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
214
215                 if ( tick_diff < 0 ) {
216                         tick_diff = -tick_diff;
217                         sign = '-';
218                 }
219                 if ( tick_diff ) {
220                         if ( tick_diff < tb_ticks_per_jiffy/25 ) {
221                                 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
222                                                 new_tb_ticks_per_jiffy, sign, tick_diff );
223                                 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
224                                 tb_ticks_per_sec   = new_tb_ticks_per_sec;
225                                 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
226                                 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
227                                 tb_to_xs = divres.result_low;
228                                 do_gtod.varp->tb_to_xs = tb_to_xs;
229                         }
230                         else {
231                                 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
232                                         "                   new tb_ticks_per_jiffy = %lu\n"
233                                         "                   old tb_ticks_per_jiffy = %lu\n",
234                                         new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
235                         }
236                 }
237         }
238         iSeries_recal_titan = titan;
239         iSeries_recal_tb = tb;
240 }
241 #endif
242
243 /*
244  * For iSeries shared processors, we have to let the hypervisor
245  * set the hardware decrementer.  We set a virtual decrementer
246  * in the ItLpPaca and call the hypervisor if the virtual
247  * decrementer is less than the current value in the hardware
248  * decrementer. (almost always the new decrementer value will
249  * be greater than the current hardware decementer so the hypervisor
250  * call will not be needed)
251  */
252
253 unsigned long tb_last_stamp=0;
254
255 /*
256  * timer_interrupt - gets called when the decrementer overflows,
257  * with interrupts disabled.
258  */
259 int timer_interrupt(struct pt_regs * regs)
260 {
261         int next_dec;
262         unsigned long cur_tb;
263         struct paca_struct *lpaca = get_paca();
264         unsigned long cpu = lpaca->xPacaIndex;
265
266         irq_enter();
267
268 #ifndef CONFIG_PPC_ISERIES
269         ppc64_do_profile(regs);
270 #endif
271
272         lpaca->xLpPaca.xIntDword.xFields.xDecrInt = 0;
273
274         while (lpaca->next_jiffy_update_tb <= (cur_tb = get_tb())) {
275
276 #ifdef CONFIG_SMP
277                 smp_local_timer_interrupt(regs);
278 #endif
279                 if (cpu == boot_cpuid) {
280                         write_seqlock(&xtime_lock);
281                         tb_last_stamp = lpaca->next_jiffy_update_tb;
282                         do_timer(regs);
283                         timer_sync_xtime( cur_tb );
284                         timer_check_rtc();
285                         write_sequnlock(&xtime_lock);
286                         if ( adjusting_time && (time_adjust == 0) )
287                                 ppc_adjtimex();
288                 }
289                 lpaca->next_jiffy_update_tb += tb_ticks_per_jiffy;
290         }
291         
292         next_dec = lpaca->next_jiffy_update_tb - cur_tb;
293         if (next_dec > lpaca->default_decr)
294                 next_dec = lpaca->default_decr;
295         set_dec(next_dec);
296
297 #ifdef CONFIG_PPC_ISERIES
298         {
299                 struct ItLpQueue *lpq = lpaca->lpQueuePtr;
300                 if (lpq && ItLpQueue_isLpIntPending(lpq))
301                         lpEvent_count += ItLpQueue_process(lpq, regs);
302         }
303 #endif
304
305         irq_exit();
306
307         return 1;
308 }
309
310
311 /*
312  * This version of gettimeofday has microsecond resolution.
313  */
314 void do_gettimeofday(struct timeval *tv)
315 {
316         unsigned long sec, usec, tb_ticks;
317         unsigned long xsec, tb_xsec;
318         struct gettimeofday_vars * temp_varp;
319         unsigned long temp_tb_to_xs, temp_stamp_xsec;
320
321         /* These calculations are faster (gets rid of divides)
322          * if done in units of 1/2^20 rather than microseconds.
323          * The conversion to microseconds at the end is done
324          * without a divide (and in fact, without a multiply) */
325         tb_ticks = get_tb() - do_gtod.tb_orig_stamp;
326         temp_varp = do_gtod.varp;
327         temp_tb_to_xs = temp_varp->tb_to_xs;
328         temp_stamp_xsec = temp_varp->stamp_xsec;
329         tb_xsec = mulhdu( tb_ticks, temp_tb_to_xs );
330         xsec = temp_stamp_xsec + tb_xsec;
331         sec = xsec / XSEC_PER_SEC;
332         xsec -= sec * XSEC_PER_SEC;
333         usec = (xsec * USEC_PER_SEC)/XSEC_PER_SEC;
334
335         tv->tv_sec = sec;
336         tv->tv_usec = usec;
337 }
338
339 int do_settimeofday(struct timespec *tv)
340 {
341         time_t wtm_sec, new_sec = tv->tv_sec;
342         long wtm_nsec, new_nsec = tv->tv_nsec;
343         unsigned long flags;
344         unsigned long delta_xsec;
345         long int tb_delta;
346         unsigned long new_xsec;
347
348         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
349                 return -EINVAL;
350
351         write_seqlock_irqsave(&xtime_lock, flags);
352         /* Updating the RTC is not the job of this code. If the time is
353          * stepped under NTP, the RTC will be update after STA_UNSYNC
354          * is cleared. Tool like clock/hwclock either copy the RTC
355          * to the system time, in which case there is no point in writing
356          * to the RTC again, or write to the RTC but then they don't call
357          * settimeofday to perform this operation.
358          */
359 #ifdef CONFIG_PPC_ISERIES
360         if ( first_settimeofday ) {
361                 iSeries_tb_recal();
362                 first_settimeofday = 0;
363         }
364 #endif
365         tb_delta = tb_ticks_since(tb_last_stamp);
366         tb_delta += (jiffies - wall_jiffies) * tb_ticks_per_jiffy;
367
368         new_nsec -= tb_delta / tb_ticks_per_usec / 1000;
369
370         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
371         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
372
373         set_normalized_timespec(&xtime, new_sec, new_nsec);
374         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
375
376         /* In case of a large backwards jump in time with NTP, we want the 
377          * clock to be updated as soon as the PLL is again in lock.
378          */
379         last_rtc_update = new_sec - 658;
380
381         time_adjust = 0;                /* stop active adjtime() */
382         time_status |= STA_UNSYNC;
383         time_maxerror = NTP_PHASE_LIMIT;
384         time_esterror = NTP_PHASE_LIMIT;
385
386         delta_xsec = mulhdu( (tb_last_stamp-do_gtod.tb_orig_stamp), do_gtod.varp->tb_to_xs );
387         new_xsec = (new_nsec * XSEC_PER_SEC) / NSEC_PER_SEC;
388         new_xsec += new_sec * XSEC_PER_SEC;
389         if ( new_xsec > delta_xsec ) {
390                 do_gtod.varp->stamp_xsec = new_xsec - delta_xsec;
391         }
392         else {
393                 /* This is only for the case where the user is setting the time
394                  * way back to a time such that the boot time would have been
395                  * before 1970 ... eg. we booted ten days ago, and we are setting
396                  * the time to Jan 5, 1970 */
397                 do_gtod.varp->stamp_xsec = new_xsec;
398                 do_gtod.tb_orig_stamp = tb_last_stamp;
399         }
400
401         write_sequnlock_irqrestore(&xtime_lock, flags);
402         return 0;
403 }
404
405 /*
406  * This function is a copy of the architecture independent function
407  * but which calls do_settimeofday rather than setting the xtime
408  * fields itself.  This way, the fields which are used for 
409  * do_settimeofday get updated too.
410  */
411 long ppc64_sys32_stime(int* tptr)
412 {
413         int value;
414         struct timespec myTimeval;
415
416         if (!capable(CAP_SYS_TIME))
417                 return -EPERM;
418
419         if (get_user(value, tptr))
420                 return -EFAULT;
421
422         myTimeval.tv_sec = value;
423         myTimeval.tv_nsec = 0;
424
425         do_settimeofday(&myTimeval);
426
427         return 0;
428 }
429
430 /*
431  * This function is a copy of the architecture independent function
432  * but which calls do_settimeofday rather than setting the xtime
433  * fields itself.  This way, the fields which are used for 
434  * do_settimeofday get updated too.
435  */
436 long ppc64_sys_stime(long* tptr)
437 {
438         long value;
439         struct timespec myTimeval;
440
441         if (!capable(CAP_SYS_TIME))
442                 return -EPERM;
443
444         if (get_user(value, tptr))
445                 return -EFAULT;
446
447         myTimeval.tv_sec = value;
448         myTimeval.tv_nsec = 0;
449
450         do_settimeofday(&myTimeval);
451
452         return 0;
453 }
454
455 void __init time_init(void)
456 {
457         /* This function is only called on the boot processor */
458         unsigned long flags;
459         struct rtc_time tm;
460
461         ppc_md.calibrate_decr();
462
463 #ifdef CONFIG_PPC_ISERIES
464         if (!piranha_simulator)
465 #endif
466                 ppc_md.get_boot_time(&tm);
467
468         write_seqlock_irqsave(&xtime_lock, flags);
469         xtime.tv_sec = mktime(tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
470                               tm.tm_hour, tm.tm_min, tm.tm_sec);
471         tb_last_stamp = get_tb();
472         do_gtod.tb_orig_stamp = tb_last_stamp;
473         do_gtod.varp = &do_gtod.vars[0];
474         do_gtod.var_idx = 0;
475         do_gtod.varp->stamp_xsec = xtime.tv_sec * XSEC_PER_SEC;
476         do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
477         do_gtod.varp->tb_to_xs = tb_to_xs;
478         do_gtod.tb_to_us = tb_to_us;
479
480         xtime_sync_interval = tb_ticks_per_sec - (tb_ticks_per_sec/8);
481         next_xtime_sync_tb = tb_last_stamp + xtime_sync_interval;
482
483         time_freq = 0;
484
485         xtime.tv_nsec = 0;
486         last_rtc_update = xtime.tv_sec;
487         set_normalized_timespec(&wall_to_monotonic,
488                                 -xtime.tv_sec, -xtime.tv_nsec);
489         write_sequnlock_irqrestore(&xtime_lock, flags);
490
491         /* Not exact, but the timer interrupt takes care of this */
492         set_dec(tb_ticks_per_jiffy);
493 }
494
495 /* 
496  * After adjtimex is called, adjust the conversion of tb ticks
497  * to microseconds to keep do_gettimeofday synchronized 
498  * with ntpd.
499  *
500  * Use the time_adjust, time_freq and time_offset computed by adjtimex to 
501  * adjust the frequency.
502  */
503
504 /* #define DEBUG_PPC_ADJTIMEX 1 */
505
506 void ppc_adjtimex(void)
507 {
508         unsigned long den, new_tb_ticks_per_sec, tb_ticks, old_xsec, new_tb_to_xs, new_xsec, new_stamp_xsec;
509         unsigned long tb_ticks_per_sec_delta;
510         long delta_freq, ltemp;
511         struct div_result divres; 
512         unsigned long flags;
513         struct gettimeofday_vars * temp_varp;
514         unsigned temp_idx;
515         long singleshot_ppm = 0;
516
517         /* Compute parts per million frequency adjustment to accomplish the time adjustment
518            implied by time_offset to be applied over the elapsed time indicated by time_constant.
519            Use SHIFT_USEC to get it into the same units as time_freq. */
520         if ( time_offset < 0 ) {
521                 ltemp = -time_offset;
522                 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
523                 ltemp >>= SHIFT_KG + time_constant;
524                 ltemp = -ltemp;
525         }
526         else {
527                 ltemp = time_offset;
528                 ltemp <<= SHIFT_USEC - SHIFT_UPDATE;
529                 ltemp >>= SHIFT_KG + time_constant;
530         }
531         
532         /* If there is a single shot time adjustment in progress */
533         if ( time_adjust ) {
534 #ifdef DEBUG_PPC_ADJTIMEX
535                 printk("ppc_adjtimex: ");
536                 if ( adjusting_time == 0 )
537                         printk("starting ");
538                 printk("single shot time_adjust = %ld\n", time_adjust);
539 #endif  
540         
541                 adjusting_time = 1;
542                 
543                 /* Compute parts per million frequency adjustment to match time_adjust */
544                 singleshot_ppm = tickadj * HZ;  
545                 /*
546                  * The adjustment should be tickadj*HZ to match the code in
547                  * linux/kernel/timer.c, but experiments show that this is too
548                  * large. 3/4 of tickadj*HZ seems about right
549                  */
550                 singleshot_ppm -= singleshot_ppm / 4;
551                 /* Use SHIFT_USEC to get it into the same units as time_freq */ 
552                 singleshot_ppm <<= SHIFT_USEC;
553                 if ( time_adjust < 0 )
554                         singleshot_ppm = -singleshot_ppm;
555         }
556         else {
557 #ifdef DEBUG_PPC_ADJTIMEX
558                 if ( adjusting_time )
559                         printk("ppc_adjtimex: ending single shot time_adjust\n");
560 #endif
561                 adjusting_time = 0;
562         }
563         
564         /* Add up all of the frequency adjustments */
565         delta_freq = time_freq + ltemp + singleshot_ppm;
566         
567         /* Compute a new value for tb_ticks_per_sec based on the frequency adjustment */
568         den = 1000000 * (1 << (SHIFT_USEC - 8));
569         if ( delta_freq < 0 ) {
570                 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( (-delta_freq) >> (SHIFT_USEC - 8))) / den;
571                 new_tb_ticks_per_sec = tb_ticks_per_sec + tb_ticks_per_sec_delta;
572         }
573         else {
574                 tb_ticks_per_sec_delta = ( tb_ticks_per_sec * ( delta_freq >> (SHIFT_USEC - 8))) / den;
575                 new_tb_ticks_per_sec = tb_ticks_per_sec - tb_ticks_per_sec_delta;
576         }
577         
578 #ifdef DEBUG_PPC_ADJTIMEX
579         printk("ppc_adjtimex: ltemp = %ld, time_freq = %ld, singleshot_ppm = %ld\n", ltemp, time_freq, singleshot_ppm);
580         printk("ppc_adjtimex: tb_ticks_per_sec - base = %ld  new = %ld\n", tb_ticks_per_sec, new_tb_ticks_per_sec);
581 #endif
582                                 
583         /* Compute a new value of tb_to_xs (used to convert tb to microseconds and a new value of 
584            stamp_xsec which is the time (in 1/2^20 second units) corresponding to tb_orig_stamp.  This 
585            new value of stamp_xsec compensates for the change in frequency (implied by the new tb_to_xs)
586            which guarantees that the current time remains the same */ 
587         tb_ticks = get_tb() - do_gtod.tb_orig_stamp;
588         div128_by_32( 1024*1024, 0, new_tb_ticks_per_sec, &divres );
589         new_tb_to_xs = divres.result_low;
590         new_xsec = mulhdu( tb_ticks, new_tb_to_xs );
591
592         write_seqlock_irqsave( &xtime_lock, flags );
593         old_xsec = mulhdu( tb_ticks, do_gtod.varp->tb_to_xs );
594         new_stamp_xsec = do_gtod.varp->stamp_xsec + old_xsec - new_xsec;
595
596         /* There are two copies of tb_to_xs and stamp_xsec so that no lock is needed to access and use these
597            values in do_gettimeofday.  We alternate the copies and as long as a reasonable time elapses between
598            changes, there will never be inconsistent values.  ntpd has a minimum of one minute between updates */
599
600         if (do_gtod.var_idx == 0) {
601                 temp_varp = &do_gtod.vars[1];
602                 temp_idx  = 1;
603         }
604         else {
605                 temp_varp = &do_gtod.vars[0];
606                 temp_idx  = 0;
607         }
608         temp_varp->tb_to_xs = new_tb_to_xs;
609         temp_varp->stamp_xsec = new_stamp_xsec;
610         mb();
611         do_gtod.varp = temp_varp;
612         do_gtod.var_idx = temp_idx;
613
614         write_sequnlock_irqrestore( &xtime_lock, flags );
615
616 }
617
618
619 #define TICK_SIZE tick
620 #define FEBRUARY        2
621 #define STARTOFTIME     1970
622 #define SECDAY          86400L
623 #define SECYR           (SECDAY * 365)
624 #define leapyear(year)          ((year) % 4 == 0)
625 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
626 #define days_in_month(a)        (month_days[(a) - 1])
627
628 static int month_days[12] = {
629         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
630 };
631
632 /*
633  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
634  */
635 void GregorianDay(struct rtc_time * tm)
636 {
637         int leapsToDate;
638         int lastYear;
639         int day;
640         int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
641
642         lastYear=tm->tm_year-1;
643
644         /*
645          * Number of leap corrections to apply up to end of last year
646          */
647         leapsToDate = lastYear/4 - lastYear/100 + lastYear/400;
648
649         /*
650          * This year is a leap year if it is divisible by 4 except when it is
651          * divisible by 100 unless it is divisible by 400
652          *
653          * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
654          */
655         if((tm->tm_year%4==0) &&
656            ((tm->tm_year%100!=0) || (tm->tm_year%400==0)) &&
657            (tm->tm_mon>2))
658         {
659                 /*
660                  * We are past Feb. 29 in a leap year
661                  */
662                 day=1;
663         }
664         else
665         {
666                 day=0;
667         }
668
669         day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
670                    tm->tm_mday;
671
672         tm->tm_wday=day%7;
673 }
674
675 void to_tm(int tim, struct rtc_time * tm)
676 {
677         register int    i;
678         register long   hms, day;
679
680         day = tim / SECDAY;
681         hms = tim % SECDAY;
682
683         /* Hours, minutes, seconds are easy */
684         tm->tm_hour = hms / 3600;
685         tm->tm_min = (hms % 3600) / 60;
686         tm->tm_sec = (hms % 3600) % 60;
687
688         /* Number of years in days */
689         for (i = STARTOFTIME; day >= days_in_year(i); i++)
690                 day -= days_in_year(i);
691         tm->tm_year = i;
692
693         /* Number of months in days left */
694         if (leapyear(tm->tm_year))
695                 days_in_month(FEBRUARY) = 29;
696         for (i = 1; day >= days_in_month(i); i++)
697                 day -= days_in_month(i);
698         days_in_month(FEBRUARY) = 28;
699         tm->tm_mon = i;
700
701         /* Days are what is left over (+1) from all that. */
702         tm->tm_mday = day + 1;
703
704         /*
705          * Determine the day of week
706          */
707         GregorianDay(tm);
708 }
709
710 /* Auxiliary function to compute scaling factors */
711 /* Actually the choice of a timebase running at 1/4 the of the bus
712  * frequency giving resolution of a few tens of nanoseconds is quite nice.
713  * It makes this computation very precise (27-28 bits typically) which
714  * is optimistic considering the stability of most processor clock
715  * oscillators and the precision with which the timebase frequency
716  * is measured but does not harm.
717  */
718 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale) {
719         unsigned mlt=0, tmp, err;
720         /* No concern for performance, it's done once: use a stupid
721          * but safe and compact method to find the multiplier.
722          */
723   
724         for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
725                 if (mulhwu(inscale, mlt|tmp) < outscale) mlt|=tmp;
726         }
727   
728         /* We might still be off by 1 for the best approximation.
729          * A side effect of this is that if outscale is too large
730          * the returned value will be zero.
731          * Many corner cases have been checked and seem to work,
732          * some might have been forgotten in the test however.
733          */
734   
735         err = inscale*(mlt+1);
736         if (err <= inscale/2) mlt++;
737         return mlt;
738   }
739
740 /*
741  * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
742  * result.
743  */
744
745 void div128_by_32( unsigned long dividend_high, unsigned long dividend_low,
746                    unsigned divisor, struct div_result *dr )
747 {
748         unsigned long a,b,c,d, w,x,y,z, ra,rb,rc;
749
750         a = dividend_high >> 32;
751         b = dividend_high & 0xffffffff;
752         c = dividend_low >> 32;
753         d = dividend_low & 0xffffffff;
754
755         w = a/divisor;
756         ra = (a - (w * divisor)) << 32;
757
758         x = (ra + b)/divisor;
759         rb = ((ra + b) - (x * divisor)) << 32;
760
761         y = (rb + c)/divisor;
762         rc = ((rb + b) - (y * divisor)) << 32;
763
764         z = (rc + d)/divisor;
765
766         dr->result_high = (w << 32) + x;
767         dr->result_low  = (y << 32) + z;
768
769 }
770