]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - arch/powerpc/kernel/time.c
powerpc: Fix problem with time going backwards
[linux-2.6-omap-h63xx.git] / arch / powerpc / kernel / time.c
1 /*
2  * Common time routines among all ppc machines.
3  *
4  * Written by Cort Dougan (cort@cs.nmt.edu) to merge
5  * Paul Mackerras' version and mine for PReP and Pmac.
6  * MPC8xx/MBX changes by Dan Malek (dmalek@jlc.net).
7  * Converted for 64-bit by Mike Corrigan (mikejc@us.ibm.com)
8  *
9  * First round of bugfixes by Gabriel Paubert (paubert@iram.es)
10  * to make clock more stable (2.4.0-test5). The only thing
11  * that this code assumes is that the timebases have been synchronized
12  * by firmware on SMP and are never stopped (never do sleep
13  * on SMP then, nap and doze are OK).
14  * 
15  * Speeded up do_gettimeofday by getting rid of references to
16  * xtime (which required locks for consistency). (mikejc@us.ibm.com)
17  *
18  * TODO (not necessarily in this file):
19  * - improve precision and reproducibility of timebase frequency
20  * measurement at boot time. (for iSeries, we calibrate the timebase
21  * against the Titan chip's clock.)
22  * - for astronomical applications: add a new function to get
23  * non ambiguous timestamps even around leap seconds. This needs
24  * a new timestamp format and a good name.
25  *
26  * 1997-09-10  Updated NTP code according to technical memorandum Jan '96
27  *             "A Kernel Model for Precision Timekeeping" by Dave Mills
28  *
29  *      This program is free software; you can redistribute it and/or
30  *      modify it under the terms of the GNU General Public License
31  *      as published by the Free Software Foundation; either version
32  *      2 of the License, or (at your option) any later version.
33  */
34
35 #include <linux/config.h>
36 #include <linux/errno.h>
37 #include <linux/module.h>
38 #include <linux/sched.h>
39 #include <linux/kernel.h>
40 #include <linux/param.h>
41 #include <linux/string.h>
42 #include <linux/mm.h>
43 #include <linux/interrupt.h>
44 #include <linux/timex.h>
45 #include <linux/kernel_stat.h>
46 #include <linux/time.h>
47 #include <linux/init.h>
48 #include <linux/profile.h>
49 #include <linux/cpu.h>
50 #include <linux/security.h>
51 #include <linux/percpu.h>
52 #include <linux/rtc.h>
53 #include <linux/jiffies.h>
54
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 #include <asm/uaccess.h>
61 #include <asm/time.h>
62 #include <asm/prom.h>
63 #include <asm/irq.h>
64 #include <asm/div64.h>
65 #include <asm/smp.h>
66 #include <asm/vdso_datapage.h>
67 #ifdef CONFIG_PPC64
68 #include <asm/firmware.h>
69 #endif
70 #ifdef CONFIG_PPC_ISERIES
71 #include <asm/iseries/it_lp_queue.h>
72 #include <asm/iseries/hv_call_xm.h>
73 #endif
74 #include <asm/smp.h>
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 /* The decrementer counts down by 128 every 128ns on a 601. */
86 #define DECREMENTER_COUNT_601   (1000000000 / HZ)
87
88 #define XSEC_PER_SEC (1024*1024)
89
90 #ifdef CONFIG_PPC64
91 #define SCALE_XSEC(xsec, max)   (((xsec) * max) / XSEC_PER_SEC)
92 #else
93 /* compute ((xsec << 12) * max) >> 32 */
94 #define SCALE_XSEC(xsec, max)   mulhwu((xsec) << 12, max)
95 #endif
96
97 unsigned long tb_ticks_per_jiffy;
98 unsigned long tb_ticks_per_usec = 100; /* sane default */
99 EXPORT_SYMBOL(tb_ticks_per_usec);
100 unsigned long tb_ticks_per_sec;
101 u64 tb_to_xs;
102 unsigned tb_to_us;
103
104 #define TICKLEN_SCALE   (SHIFT_SCALE - 10)
105 u64 last_tick_len;      /* units are ns / 2^TICKLEN_SCALE */
106 u64 ticklen_to_xs;      /* 0.64 fraction */
107
108 /* If last_tick_len corresponds to about 1/HZ seconds, then
109    last_tick_len << TICKLEN_SHIFT will be about 2^63. */
110 #define TICKLEN_SHIFT   (63 - 30 - TICKLEN_SCALE + SHIFT_HZ)
111
112 DEFINE_SPINLOCK(rtc_lock);
113 EXPORT_SYMBOL_GPL(rtc_lock);
114
115 u64 tb_to_ns_scale;
116 unsigned tb_to_ns_shift;
117
118 struct gettimeofday_struct do_gtod;
119
120 extern unsigned long wall_jiffies;
121
122 extern struct timezone sys_tz;
123 static long timezone_offset;
124
125 unsigned long ppc_proc_freq;
126 unsigned long ppc_tb_freq;
127
128 u64 tb_last_jiffy __cacheline_aligned_in_smp;
129 unsigned long tb_last_stamp;
130
131 /*
132  * Note that on ppc32 this only stores the bottom 32 bits of
133  * the timebase value, but that's enough to tell when a jiffy
134  * has passed.
135  */
136 DEFINE_PER_CPU(unsigned long, last_jiffy);
137
138 void __delay(unsigned long loops)
139 {
140         unsigned long start;
141         int diff;
142
143         if (__USE_RTC()) {
144                 start = get_rtcl();
145                 do {
146                         /* the RTCL register wraps at 1000000000 */
147                         diff = get_rtcl() - start;
148                         if (diff < 0)
149                                 diff += 1000000000;
150                 } while (diff < loops);
151         } else {
152                 start = get_tbl();
153                 while (get_tbl() - start < loops)
154                         HMT_low();
155                 HMT_medium();
156         }
157 }
158 EXPORT_SYMBOL(__delay);
159
160 void udelay(unsigned long usecs)
161 {
162         __delay(tb_ticks_per_usec * usecs);
163 }
164 EXPORT_SYMBOL(udelay);
165
166 static __inline__ void timer_check_rtc(void)
167 {
168         /*
169          * update the rtc when needed, this should be performed on the
170          * right fraction of a second. Half or full second ?
171          * Full second works on mk48t59 clocks, others need testing.
172          * Note that this update is basically only used through 
173          * the adjtimex system calls. Setting the HW clock in
174          * any other way is a /dev/rtc and userland business.
175          * This is still wrong by -0.5/+1.5 jiffies because of the
176          * timer interrupt resolution and possible delay, but here we 
177          * hit a quantization limit which can only be solved by higher
178          * resolution timers and decoupling time management from timer
179          * interrupts. This is also wrong on the clocks
180          * which require being written at the half second boundary.
181          * We should have an rtc call that only sets the minutes and
182          * seconds like on Intel to avoid problems with non UTC clocks.
183          */
184         if (ppc_md.set_rtc_time && ntp_synced() &&
185             xtime.tv_sec - last_rtc_update >= 659 &&
186             abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ) {
187                 struct rtc_time tm;
188                 to_tm(xtime.tv_sec + 1 + timezone_offset, &tm);
189                 tm.tm_year -= 1900;
190                 tm.tm_mon -= 1;
191                 if (ppc_md.set_rtc_time(&tm) == 0)
192                         last_rtc_update = xtime.tv_sec + 1;
193                 else
194                         /* Try again one minute later */
195                         last_rtc_update += 60;
196         }
197 }
198
199 /*
200  * This version of gettimeofday has microsecond resolution.
201  */
202 static inline void __do_gettimeofday(struct timeval *tv, u64 tb_val)
203 {
204         unsigned long sec, usec;
205         u64 tb_ticks, xsec;
206         struct gettimeofday_vars *temp_varp;
207         u64 temp_tb_to_xs, temp_stamp_xsec;
208
209         /*
210          * These calculations are faster (gets rid of divides)
211          * if done in units of 1/2^20 rather than microseconds.
212          * The conversion to microseconds at the end is done
213          * without a divide (and in fact, without a multiply)
214          */
215         temp_varp = do_gtod.varp;
216         tb_ticks = tb_val - temp_varp->tb_orig_stamp;
217         temp_tb_to_xs = temp_varp->tb_to_xs;
218         temp_stamp_xsec = temp_varp->stamp_xsec;
219         xsec = temp_stamp_xsec + mulhdu(tb_ticks, temp_tb_to_xs);
220         sec = xsec / XSEC_PER_SEC;
221         usec = (unsigned long)xsec & (XSEC_PER_SEC - 1);
222         usec = SCALE_XSEC(usec, 1000000);
223
224         tv->tv_sec = sec;
225         tv->tv_usec = usec;
226 }
227
228 void do_gettimeofday(struct timeval *tv)
229 {
230         if (__USE_RTC()) {
231                 /* do this the old way */
232                 unsigned long flags, seq;
233                 unsigned int sec, nsec, usec;
234
235                 do {
236                         seq = read_seqbegin_irqsave(&xtime_lock, flags);
237                         sec = xtime.tv_sec;
238                         nsec = xtime.tv_nsec + tb_ticks_since(tb_last_stamp);
239                 } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
240                 usec = nsec / 1000;
241                 while (usec >= 1000000) {
242                         usec -= 1000000;
243                         ++sec;
244                 }
245                 tv->tv_sec = sec;
246                 tv->tv_usec = usec;
247                 return;
248         }
249         __do_gettimeofday(tv, get_tb());
250 }
251
252 EXPORT_SYMBOL(do_gettimeofday);
253
254 /*
255  * There are two copies of tb_to_xs and stamp_xsec so that no
256  * lock is needed to access and use these values in
257  * do_gettimeofday.  We alternate the copies and as long as a
258  * reasonable time elapses between changes, there will never
259  * be inconsistent values.  ntpd has a minimum of one minute
260  * between updates.
261  */
262 static inline void update_gtod(u64 new_tb_stamp, u64 new_stamp_xsec,
263                                u64 new_tb_to_xs)
264 {
265         unsigned temp_idx;
266         struct gettimeofday_vars *temp_varp;
267
268         temp_idx = (do_gtod.var_idx == 0);
269         temp_varp = &do_gtod.vars[temp_idx];
270
271         temp_varp->tb_to_xs = new_tb_to_xs;
272         temp_varp->tb_orig_stamp = new_tb_stamp;
273         temp_varp->stamp_xsec = new_stamp_xsec;
274         smp_mb();
275         do_gtod.varp = temp_varp;
276         do_gtod.var_idx = temp_idx;
277
278         /*
279          * tb_update_count is used to allow the userspace gettimeofday code
280          * to assure itself that it sees a consistent view of the tb_to_xs and
281          * stamp_xsec variables.  It reads the tb_update_count, then reads
282          * tb_to_xs and stamp_xsec and then reads tb_update_count again.  If
283          * the two values of tb_update_count match and are even then the
284          * tb_to_xs and stamp_xsec values are consistent.  If not, then it
285          * loops back and reads them again until this criteria is met.
286          * We expect the caller to have done the first increment of
287          * vdso_data->tb_update_count already.
288          */
289         vdso_data->tb_orig_stamp = new_tb_stamp;
290         vdso_data->stamp_xsec = new_stamp_xsec;
291         vdso_data->tb_to_xs = new_tb_to_xs;
292         vdso_data->wtom_clock_sec = wall_to_monotonic.tv_sec;
293         vdso_data->wtom_clock_nsec = wall_to_monotonic.tv_nsec;
294         smp_wmb();
295         ++(vdso_data->tb_update_count);
296 }
297
298 /*
299  * When the timebase - tb_orig_stamp gets too big, we do a manipulation
300  * between tb_orig_stamp and stamp_xsec. The goal here is to keep the
301  * difference tb - tb_orig_stamp small enough to always fit inside a
302  * 32 bits number. This is a requirement of our fast 32 bits userland
303  * implementation in the vdso. If we "miss" a call to this function
304  * (interrupt latency, CPU locked in a spinlock, ...) and we end up
305  * with a too big difference, then the vdso will fallback to calling
306  * the syscall
307  */
308 static __inline__ void timer_recalc_offset(u64 cur_tb)
309 {
310         unsigned long offset;
311         u64 new_stamp_xsec;
312         u64 tlen, t2x;
313         u64 tb, xsec_old, xsec_new;
314         struct gettimeofday_vars *varp;
315
316         if (__USE_RTC())
317                 return;
318         tlen = current_tick_length();
319         offset = cur_tb - do_gtod.varp->tb_orig_stamp;
320         if (tlen == last_tick_len && offset < 0x80000000u)
321                 return;
322         if (tlen != last_tick_len) {
323                 t2x = mulhdu(tlen << TICKLEN_SHIFT, ticklen_to_xs);
324                 last_tick_len = tlen;
325         } else
326                 t2x = do_gtod.varp->tb_to_xs;
327         new_stamp_xsec = (u64) xtime.tv_nsec * XSEC_PER_SEC;
328         do_div(new_stamp_xsec, 1000000000);
329         new_stamp_xsec += (u64) xtime.tv_sec * XSEC_PER_SEC;
330
331         ++vdso_data->tb_update_count;
332         smp_mb();
333
334         /*
335          * Make sure time doesn't go backwards for userspace gettimeofday.
336          */
337         tb = get_tb();
338         varp = do_gtod.varp;
339         xsec_old = mulhdu(tb - varp->tb_orig_stamp, varp->tb_to_xs)
340                 + varp->stamp_xsec;
341         xsec_new = mulhdu(tb - cur_tb, t2x) + new_stamp_xsec;
342         if (xsec_new < xsec_old)
343                 new_stamp_xsec += xsec_old - xsec_new;
344
345         update_gtod(cur_tb, new_stamp_xsec, t2x);
346 }
347
348 #ifdef CONFIG_SMP
349 unsigned long profile_pc(struct pt_regs *regs)
350 {
351         unsigned long pc = instruction_pointer(regs);
352
353         if (in_lock_functions(pc))
354                 return regs->link;
355
356         return pc;
357 }
358 EXPORT_SYMBOL(profile_pc);
359 #endif
360
361 #ifdef CONFIG_PPC_ISERIES
362
363 /* 
364  * This function recalibrates the timebase based on the 49-bit time-of-day
365  * value in the Titan chip.  The Titan is much more accurate than the value
366  * returned by the service processor for the timebase frequency.  
367  */
368
369 static void iSeries_tb_recal(void)
370 {
371         struct div_result divres;
372         unsigned long titan, tb;
373         tb = get_tb();
374         titan = HvCallXm_loadTod();
375         if ( iSeries_recal_titan ) {
376                 unsigned long tb_ticks = tb - iSeries_recal_tb;
377                 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
378                 unsigned long new_tb_ticks_per_sec   = (tb_ticks * USEC_PER_SEC)/titan_usec;
379                 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
380                 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
381                 char sign = '+';                
382                 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
383                 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
384
385                 if ( tick_diff < 0 ) {
386                         tick_diff = -tick_diff;
387                         sign = '-';
388                 }
389                 if ( tick_diff ) {
390                         if ( tick_diff < tb_ticks_per_jiffy/25 ) {
391                                 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
392                                                 new_tb_ticks_per_jiffy, sign, tick_diff );
393                                 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
394                                 tb_ticks_per_sec   = new_tb_ticks_per_sec;
395                                 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
396                                 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
397                                 tb_to_xs = divres.result_low;
398                                 do_gtod.varp->tb_to_xs = tb_to_xs;
399                                 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
400                                 vdso_data->tb_to_xs = tb_to_xs;
401                         }
402                         else {
403                                 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
404                                         "                   new tb_ticks_per_jiffy = %lu\n"
405                                         "                   old tb_ticks_per_jiffy = %lu\n",
406                                         new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
407                         }
408                 }
409         }
410         iSeries_recal_titan = titan;
411         iSeries_recal_tb = tb;
412 }
413 #endif
414
415 /*
416  * For iSeries shared processors, we have to let the hypervisor
417  * set the hardware decrementer.  We set a virtual decrementer
418  * in the lppaca and call the hypervisor if the virtual
419  * decrementer is less than the current value in the hardware
420  * decrementer. (almost always the new decrementer value will
421  * be greater than the current hardware decementer so the hypervisor
422  * call will not be needed)
423  */
424
425 /*
426  * timer_interrupt - gets called when the decrementer overflows,
427  * with interrupts disabled.
428  */
429 void timer_interrupt(struct pt_regs * regs)
430 {
431         int next_dec;
432         int cpu = smp_processor_id();
433         unsigned long ticks;
434
435 #ifdef CONFIG_PPC32
436         if (atomic_read(&ppc_n_lost_interrupts) != 0)
437                 do_IRQ(regs);
438 #endif
439
440         irq_enter();
441
442         profile_tick(CPU_PROFILING, regs);
443
444 #ifdef CONFIG_PPC_ISERIES
445         get_lppaca()->int_dword.fields.decr_int = 0;
446 #endif
447
448         while ((ticks = tb_ticks_since(per_cpu(last_jiffy, cpu)))
449                >= tb_ticks_per_jiffy) {
450                 /* Update last_jiffy */
451                 per_cpu(last_jiffy, cpu) += tb_ticks_per_jiffy;
452                 /* Handle RTCL overflow on 601 */
453                 if (__USE_RTC() && per_cpu(last_jiffy, cpu) >= 1000000000)
454                         per_cpu(last_jiffy, cpu) -= 1000000000;
455
456                 /*
457                  * We cannot disable the decrementer, so in the period
458                  * between this cpu's being marked offline in cpu_online_map
459                  * and calling stop-self, it is taking timer interrupts.
460                  * Avoid calling into the scheduler rebalancing code if this
461                  * is the case.
462                  */
463                 if (!cpu_is_offline(cpu))
464                         update_process_times(user_mode(regs));
465
466                 /*
467                  * No need to check whether cpu is offline here; boot_cpuid
468                  * should have been fixed up by now.
469                  */
470                 if (cpu != boot_cpuid)
471                         continue;
472
473                 write_seqlock(&xtime_lock);
474                 tb_last_jiffy += tb_ticks_per_jiffy;
475                 tb_last_stamp = per_cpu(last_jiffy, cpu);
476                 do_timer(regs);
477                 timer_recalc_offset(tb_last_jiffy);
478                 timer_check_rtc();
479                 write_sequnlock(&xtime_lock);
480         }
481         
482         next_dec = tb_ticks_per_jiffy - ticks;
483         set_dec(next_dec);
484
485 #ifdef CONFIG_PPC_ISERIES
486         if (hvlpevent_is_pending())
487                 process_hvlpevents(regs);
488 #endif
489
490 #ifdef CONFIG_PPC64
491         /* collect purr register values often, for accurate calculations */
492         if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
493                 struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
494                 cu->current_tb = mfspr(SPRN_PURR);
495         }
496 #endif
497
498         irq_exit();
499 }
500
501 void wakeup_decrementer(void)
502 {
503         unsigned long ticks;
504
505         /*
506          * The timebase gets saved on sleep and restored on wakeup,
507          * so all we need to do is to reset the decrementer.
508          */
509         ticks = tb_ticks_since(__get_cpu_var(last_jiffy));
510         if (ticks < tb_ticks_per_jiffy)
511                 ticks = tb_ticks_per_jiffy - ticks;
512         else
513                 ticks = 1;
514         set_dec(ticks);
515 }
516
517 #ifdef CONFIG_SMP
518 void __init smp_space_timers(unsigned int max_cpus)
519 {
520         int i;
521         unsigned long offset = tb_ticks_per_jiffy / max_cpus;
522         unsigned long previous_tb = per_cpu(last_jiffy, boot_cpuid);
523
524         /* make sure tb > per_cpu(last_jiffy, cpu) for all cpus always */
525         previous_tb -= tb_ticks_per_jiffy;
526         for_each_cpu(i) {
527                 if (i != boot_cpuid) {
528                         previous_tb += offset;
529                         per_cpu(last_jiffy, i) = previous_tb;
530                 }
531         }
532 }
533 #endif
534
535 /*
536  * Scheduler clock - returns current time in nanosec units.
537  *
538  * Note: mulhdu(a, b) (multiply high double unsigned) returns
539  * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
540  * are 64-bit unsigned numbers.
541  */
542 unsigned long long sched_clock(void)
543 {
544         if (__USE_RTC())
545                 return get_rtc();
546         return mulhdu(get_tb(), tb_to_ns_scale) << tb_to_ns_shift;
547 }
548
549 int do_settimeofday(struct timespec *tv)
550 {
551         time_t wtm_sec, new_sec = tv->tv_sec;
552         long wtm_nsec, new_nsec = tv->tv_nsec;
553         unsigned long flags;
554         u64 new_xsec;
555         unsigned long tb_delta;
556
557         if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
558                 return -EINVAL;
559
560         write_seqlock_irqsave(&xtime_lock, flags);
561
562         /*
563          * Updating the RTC is not the job of this code. If the time is
564          * stepped under NTP, the RTC will be updated after STA_UNSYNC
565          * is cleared.  Tools like clock/hwclock either copy the RTC
566          * to the system time, in which case there is no point in writing
567          * to the RTC again, or write to the RTC but then they don't call
568          * settimeofday to perform this operation.
569          */
570 #ifdef CONFIG_PPC_ISERIES
571         if (first_settimeofday) {
572                 iSeries_tb_recal();
573                 first_settimeofday = 0;
574         }
575 #endif
576
577         /* Make userspace gettimeofday spin until we're done. */
578         ++vdso_data->tb_update_count;
579         smp_mb();
580
581         /*
582          * Subtract off the number of nanoseconds since the
583          * beginning of the last tick.
584          * Note that since we don't increment jiffies_64 anywhere other
585          * than in do_timer (since we don't have a lost tick problem),
586          * wall_jiffies will always be the same as jiffies,
587          * and therefore the (jiffies - wall_jiffies) computation
588          * has been removed.
589          */
590         tb_delta = tb_ticks_since(tb_last_stamp);
591         tb_delta = mulhdu(tb_delta, do_gtod.varp->tb_to_xs); /* in xsec */
592         new_nsec -= SCALE_XSEC(tb_delta, 1000000000);
593
594         wtm_sec  = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
595         wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
596
597         set_normalized_timespec(&xtime, new_sec, new_nsec);
598         set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
599
600         /* In case of a large backwards jump in time with NTP, we want the 
601          * clock to be updated as soon as the PLL is again in lock.
602          */
603         last_rtc_update = new_sec - 658;
604
605         ntp_clear();
606
607         new_xsec = xtime.tv_nsec;
608         if (new_xsec != 0) {
609                 new_xsec *= XSEC_PER_SEC;
610                 do_div(new_xsec, NSEC_PER_SEC);
611         }
612         new_xsec += (u64)xtime.tv_sec * XSEC_PER_SEC;
613         update_gtod(tb_last_jiffy, new_xsec, do_gtod.varp->tb_to_xs);
614
615         vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
616         vdso_data->tz_dsttime = sys_tz.tz_dsttime;
617
618         write_sequnlock_irqrestore(&xtime_lock, flags);
619         clock_was_set();
620         return 0;
621 }
622
623 EXPORT_SYMBOL(do_settimeofday);
624
625 void __init generic_calibrate_decr(void)
626 {
627         struct device_node *cpu;
628         unsigned int *fp;
629         int node_found;
630
631         /*
632          * The cpu node should have a timebase-frequency property
633          * to tell us the rate at which the decrementer counts.
634          */
635         cpu = of_find_node_by_type(NULL, "cpu");
636
637         ppc_tb_freq = DEFAULT_TB_FREQ;          /* hardcoded default */
638         node_found = 0;
639         if (cpu) {
640                 fp = (unsigned int *)get_property(cpu, "timebase-frequency",
641                                                   NULL);
642                 if (fp) {
643                         node_found = 1;
644                         ppc_tb_freq = *fp;
645                 }
646         }
647         if (!node_found)
648                 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
649                                 "(not found)\n");
650
651         ppc_proc_freq = DEFAULT_PROC_FREQ;
652         node_found = 0;
653         if (cpu) {
654                 fp = (unsigned int *)get_property(cpu, "clock-frequency",
655                                                   NULL);
656                 if (fp) {
657                         node_found = 1;
658                         ppc_proc_freq = *fp;
659                 }
660         }
661 #ifdef CONFIG_BOOKE
662         /* Set the time base to zero */
663         mtspr(SPRN_TBWL, 0);
664         mtspr(SPRN_TBWU, 0);
665
666         /* Clear any pending timer interrupts */
667         mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
668
669         /* Enable decrementer interrupt */
670         mtspr(SPRN_TCR, TCR_DIE);
671 #endif
672         if (!node_found)
673                 printk(KERN_ERR "WARNING: Estimating processor frequency "
674                                 "(not found)\n");
675
676         of_node_put(cpu);
677 }
678
679 unsigned long get_boot_time(void)
680 {
681         struct rtc_time tm;
682
683         if (ppc_md.get_boot_time)
684                 return ppc_md.get_boot_time();
685         if (!ppc_md.get_rtc_time)
686                 return 0;
687         ppc_md.get_rtc_time(&tm);
688         return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
689                       tm.tm_hour, tm.tm_min, tm.tm_sec);
690 }
691
692 /* This function is only called on the boot processor */
693 void __init time_init(void)
694 {
695         unsigned long flags;
696         unsigned long tm = 0;
697         struct div_result res;
698         u64 scale, x;
699         unsigned shift;
700
701         if (ppc_md.time_init != NULL)
702                 timezone_offset = ppc_md.time_init();
703
704         if (__USE_RTC()) {
705                 /* 601 processor: dec counts down by 128 every 128ns */
706                 ppc_tb_freq = 1000000000;
707                 tb_last_stamp = get_rtcl();
708                 tb_last_jiffy = tb_last_stamp;
709         } else {
710                 /* Normal PowerPC with timebase register */
711                 ppc_md.calibrate_decr();
712                 printk(KERN_INFO "time_init: decrementer frequency = %lu.%.6lu MHz\n",
713                        ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
714                 printk(KERN_INFO "time_init: processor frequency   = %lu.%.6lu MHz\n",
715                        ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
716                 tb_last_stamp = tb_last_jiffy = get_tb();
717         }
718
719         tb_ticks_per_jiffy = ppc_tb_freq / HZ;
720         tb_ticks_per_sec = ppc_tb_freq;
721         tb_ticks_per_usec = ppc_tb_freq / 1000000;
722         tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
723
724         /*
725          * Calculate the length of each tick in ns.  It will not be
726          * exactly 1e9/HZ unless ppc_tb_freq is divisible by HZ.
727          * We compute 1e9 * tb_ticks_per_jiffy / ppc_tb_freq,
728          * rounded up.
729          */
730         x = (u64) NSEC_PER_SEC * tb_ticks_per_jiffy + ppc_tb_freq - 1;
731         do_div(x, ppc_tb_freq);
732         tick_nsec = x;
733         last_tick_len = x << TICKLEN_SCALE;
734
735         /*
736          * Compute ticklen_to_xs, which is a factor which gets multiplied
737          * by (last_tick_len << TICKLEN_SHIFT) to get a tb_to_xs value.
738          * It is computed as:
739          * ticklen_to_xs = 2^N / (tb_ticks_per_jiffy * 1e9)
740          * where N = 64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT
741          * which turns out to be N = 51 - SHIFT_HZ.
742          * This gives the result as a 0.64 fixed-point fraction.
743          * That value is reduced by an offset amounting to 1 xsec per
744          * 2^31 timebase ticks to avoid problems with time going backwards
745          * by 1 xsec when we do timer_recalc_offset due to losing the
746          * fractional xsec.  That offset is equal to ppc_tb_freq/2^51
747          * since there are 2^20 xsec in a second.
748          */
749         div128_by_32((1ULL << 51) - ppc_tb_freq, 0,
750                      tb_ticks_per_jiffy << SHIFT_HZ, &res);
751         div128_by_32(res.result_high, res.result_low, NSEC_PER_SEC, &res);
752         ticklen_to_xs = res.result_low;
753
754         /* Compute tb_to_xs from tick_nsec */
755         tb_to_xs = mulhdu(last_tick_len << TICKLEN_SHIFT, ticklen_to_xs);
756
757         /*
758          * Compute scale factor for sched_clock.
759          * The calibrate_decr() function has set tb_ticks_per_sec,
760          * which is the timebase frequency.
761          * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
762          * the 128-bit result as a 64.64 fixed-point number.
763          * We then shift that number right until it is less than 1.0,
764          * giving us the scale factor and shift count to use in
765          * sched_clock().
766          */
767         div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
768         scale = res.result_low;
769         for (shift = 0; res.result_high != 0; ++shift) {
770                 scale = (scale >> 1) | (res.result_high << 63);
771                 res.result_high >>= 1;
772         }
773         tb_to_ns_scale = scale;
774         tb_to_ns_shift = shift;
775
776 #ifdef CONFIG_PPC_ISERIES
777         if (!piranha_simulator)
778 #endif
779                 tm = get_boot_time();
780
781         write_seqlock_irqsave(&xtime_lock, flags);
782
783         /* If platform provided a timezone (pmac), we correct the time */
784         if (timezone_offset) {
785                 sys_tz.tz_minuteswest = -timezone_offset / 60;
786                 sys_tz.tz_dsttime = 0;
787                 tm -= timezone_offset;
788         }
789
790         xtime.tv_sec = tm;
791         xtime.tv_nsec = 0;
792         do_gtod.varp = &do_gtod.vars[0];
793         do_gtod.var_idx = 0;
794         do_gtod.varp->tb_orig_stamp = tb_last_jiffy;
795         __get_cpu_var(last_jiffy) = tb_last_stamp;
796         do_gtod.varp->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
797         do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
798         do_gtod.varp->tb_to_xs = tb_to_xs;
799         do_gtod.tb_to_us = tb_to_us;
800
801         vdso_data->tb_orig_stamp = tb_last_jiffy;
802         vdso_data->tb_update_count = 0;
803         vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
804         vdso_data->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
805         vdso_data->tb_to_xs = tb_to_xs;
806
807         time_freq = 0;
808
809         last_rtc_update = xtime.tv_sec;
810         set_normalized_timespec(&wall_to_monotonic,
811                                 -xtime.tv_sec, -xtime.tv_nsec);
812         write_sequnlock_irqrestore(&xtime_lock, flags);
813
814         /* Not exact, but the timer interrupt takes care of this */
815         set_dec(tb_ticks_per_jiffy);
816 }
817
818
819 #define FEBRUARY        2
820 #define STARTOFTIME     1970
821 #define SECDAY          86400L
822 #define SECYR           (SECDAY * 365)
823 #define leapyear(year)          ((year) % 4 == 0 && \
824                                  ((year) % 100 != 0 || (year) % 400 == 0))
825 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
826 #define days_in_month(a)        (month_days[(a) - 1])
827
828 static int month_days[12] = {
829         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
830 };
831
832 /*
833  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
834  */
835 void GregorianDay(struct rtc_time * tm)
836 {
837         int leapsToDate;
838         int lastYear;
839         int day;
840         int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
841
842         lastYear = tm->tm_year - 1;
843
844         /*
845          * Number of leap corrections to apply up to end of last year
846          */
847         leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
848
849         /*
850          * This year is a leap year if it is divisible by 4 except when it is
851          * divisible by 100 unless it is divisible by 400
852          *
853          * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
854          */
855         day = tm->tm_mon > 2 && leapyear(tm->tm_year);
856
857         day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
858                    tm->tm_mday;
859
860         tm->tm_wday = day % 7;
861 }
862
863 void to_tm(int tim, struct rtc_time * tm)
864 {
865         register int    i;
866         register long   hms, day;
867
868         day = tim / SECDAY;
869         hms = tim % SECDAY;
870
871         /* Hours, minutes, seconds are easy */
872         tm->tm_hour = hms / 3600;
873         tm->tm_min = (hms % 3600) / 60;
874         tm->tm_sec = (hms % 3600) % 60;
875
876         /* Number of years in days */
877         for (i = STARTOFTIME; day >= days_in_year(i); i++)
878                 day -= days_in_year(i);
879         tm->tm_year = i;
880
881         /* Number of months in days left */
882         if (leapyear(tm->tm_year))
883                 days_in_month(FEBRUARY) = 29;
884         for (i = 1; day >= days_in_month(i); i++)
885                 day -= days_in_month(i);
886         days_in_month(FEBRUARY) = 28;
887         tm->tm_mon = i;
888
889         /* Days are what is left over (+1) from all that. */
890         tm->tm_mday = day + 1;
891
892         /*
893          * Determine the day of week
894          */
895         GregorianDay(tm);
896 }
897
898 /* Auxiliary function to compute scaling factors */
899 /* Actually the choice of a timebase running at 1/4 the of the bus
900  * frequency giving resolution of a few tens of nanoseconds is quite nice.
901  * It makes this computation very precise (27-28 bits typically) which
902  * is optimistic considering the stability of most processor clock
903  * oscillators and the precision with which the timebase frequency
904  * is measured but does not harm.
905  */
906 unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale)
907 {
908         unsigned mlt=0, tmp, err;
909         /* No concern for performance, it's done once: use a stupid
910          * but safe and compact method to find the multiplier.
911          */
912   
913         for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
914                 if (mulhwu(inscale, mlt|tmp) < outscale)
915                         mlt |= tmp;
916         }
917   
918         /* We might still be off by 1 for the best approximation.
919          * A side effect of this is that if outscale is too large
920          * the returned value will be zero.
921          * Many corner cases have been checked and seem to work,
922          * some might have been forgotten in the test however.
923          */
924   
925         err = inscale * (mlt+1);
926         if (err <= inscale/2)
927                 mlt++;
928         return mlt;
929 }
930
931 /*
932  * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
933  * result.
934  */
935 void div128_by_32(u64 dividend_high, u64 dividend_low,
936                   unsigned divisor, struct div_result *dr)
937 {
938         unsigned long a, b, c, d;
939         unsigned long w, x, y, z;
940         u64 ra, rb, rc;
941
942         a = dividend_high >> 32;
943         b = dividend_high & 0xffffffff;
944         c = dividend_low >> 32;
945         d = dividend_low & 0xffffffff;
946
947         w = a / divisor;
948         ra = ((u64)(a - (w * divisor)) << 32) + b;
949
950         rb = ((u64) do_div(ra, divisor) << 32) + c;
951         x = ra;
952
953         rc = ((u64) do_div(rb, divisor) << 32) + d;
954         y = rb;
955
956         do_div(rc, divisor);
957         z = rc;
958
959         dr->result_high = ((u64)w << 32) + x;
960         dr->result_low  = ((u64)y << 32) + z;
961
962 }