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