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