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