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