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