]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - arch/powerpc/kernel/time.c
[PATCH] powerpc: native atomic_add_unless
[mirror_ubuntu-zesty-kernel.git] / arch / powerpc / kernel / time.c
CommitLineData
1da177e4 1/*
1da177e4
LT
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>
1da177e4
LT
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>
f2783c15
PM
51#include <linux/percpu.h>
52#include <linux/rtc.h>
092b8f34 53#include <linux/jiffies.h>
c6622f63 54#include <linux/posix-timers.h>
1da177e4 55
1da177e4
LT
56#include <asm/io.h>
57#include <asm/processor.h>
58#include <asm/nvram.h>
59#include <asm/cache.h>
60#include <asm/machdep.h>
1da177e4
LT
61#include <asm/uaccess.h>
62#include <asm/time.h>
1da177e4 63#include <asm/prom.h>
f2783c15
PM
64#include <asm/irq.h>
65#include <asm/div64.h>
2249ca9d 66#include <asm/smp.h>
a7f290da 67#include <asm/vdso_datapage.h>
f2783c15 68#ifdef CONFIG_PPC64
1ababe11 69#include <asm/firmware.h>
f2783c15
PM
70#endif
71#ifdef CONFIG_PPC_ISERIES
8875ccfb 72#include <asm/iseries/it_lp_queue.h>
8021b8a7 73#include <asm/iseries/hv_call_xm.h>
f2783c15 74#endif
732ee21f 75#include <asm/smp.h>
1da177e4 76
1da177e4
LT
77/* keep track of when we need to update the rtc */
78time_t last_rtc_update;
79extern int piranha_simulator;
80#ifdef CONFIG_PPC_ISERIES
81unsigned long iSeries_recal_titan = 0;
82unsigned long iSeries_recal_tb = 0;
83static unsigned long first_settimeofday = 1;
84#endif
85
f2783c15
PM
86/* The decrementer counts down by 128 every 128ns on a 601. */
87#define DECREMENTER_COUNT_601 (1000000000 / HZ)
88
1da177e4
LT
89#define XSEC_PER_SEC (1024*1024)
90
f2783c15
PM
91#ifdef CONFIG_PPC64
92#define SCALE_XSEC(xsec, max) (((xsec) * max) / XSEC_PER_SEC)
93#else
94/* compute ((xsec << 12) * max) >> 32 */
95#define SCALE_XSEC(xsec, max) mulhwu((xsec) << 12, max)
96#endif
97
1da177e4
LT
98unsigned long tb_ticks_per_jiffy;
99unsigned long tb_ticks_per_usec = 100; /* sane default */
100EXPORT_SYMBOL(tb_ticks_per_usec);
101unsigned long tb_ticks_per_sec;
f2783c15
PM
102u64 tb_to_xs;
103unsigned tb_to_us;
092b8f34
PM
104
105#define TICKLEN_SCALE (SHIFT_SCALE - 10)
106u64 last_tick_len; /* units are ns / 2^TICKLEN_SCALE */
107u64 ticklen_to_xs; /* 0.64 fraction */
108
109/* If last_tick_len corresponds to about 1/HZ seconds, then
110 last_tick_len << TICKLEN_SHIFT will be about 2^63. */
111#define TICKLEN_SHIFT (63 - 30 - TICKLEN_SCALE + SHIFT_HZ)
112
1da177e4 113DEFINE_SPINLOCK(rtc_lock);
6ae3db11 114EXPORT_SYMBOL_GPL(rtc_lock);
1da177e4 115
f2783c15
PM
116u64 tb_to_ns_scale;
117unsigned tb_to_ns_shift;
1da177e4
LT
118
119struct gettimeofday_struct do_gtod;
120
121extern unsigned long wall_jiffies;
1da177e4
LT
122
123extern struct timezone sys_tz;
f2783c15 124static long timezone_offset;
1da177e4 125
10f7e7c1
AB
126unsigned long ppc_proc_freq;
127unsigned long ppc_tb_freq;
128
96c44507
PM
129u64 tb_last_jiffy __cacheline_aligned_in_smp;
130unsigned long tb_last_stamp;
131
132/*
133 * Note that on ppc32 this only stores the bottom 32 bits of
134 * the timebase value, but that's enough to tell when a jiffy
135 * has passed.
136 */
137DEFINE_PER_CPU(unsigned long, last_jiffy);
138
c6622f63
PM
139#ifdef CONFIG_VIRT_CPU_ACCOUNTING
140/*
141 * Factors for converting from cputime_t (timebase ticks) to
142 * jiffies, milliseconds, seconds, and clock_t (1/USER_HZ seconds).
143 * These are all stored as 0.64 fixed-point binary fractions.
144 */
145u64 __cputime_jiffies_factor;
146u64 __cputime_msec_factor;
147u64 __cputime_sec_factor;
148u64 __cputime_clockt_factor;
149
150static void calc_cputime_factors(void)
151{
152 struct div_result res;
153
154 div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
155 __cputime_jiffies_factor = res.result_low;
156 div128_by_32(1000, 0, tb_ticks_per_sec, &res);
157 __cputime_msec_factor = res.result_low;
158 div128_by_32(1, 0, tb_ticks_per_sec, &res);
159 __cputime_sec_factor = res.result_low;
160 div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
161 __cputime_clockt_factor = res.result_low;
162}
163
164/*
165 * Read the PURR on systems that have it, otherwise the timebase.
166 */
167static u64 read_purr(void)
168{
169 if (cpu_has_feature(CPU_FTR_PURR))
170 return mfspr(SPRN_PURR);
171 return mftb();
172}
173
174/*
175 * Account time for a transition between system, hard irq
176 * or soft irq state.
177 */
178void account_system_vtime(struct task_struct *tsk)
179{
180 u64 now, delta;
181 unsigned long flags;
182
183 local_irq_save(flags);
184 now = read_purr();
185 delta = now - get_paca()->startpurr;
186 get_paca()->startpurr = now;
187 if (!in_interrupt()) {
188 delta += get_paca()->system_time;
189 get_paca()->system_time = 0;
190 }
191 account_system_time(tsk, 0, delta);
192 local_irq_restore(flags);
193}
194
195/*
196 * Transfer the user and system times accumulated in the paca
197 * by the exception entry and exit code to the generic process
198 * user and system time records.
199 * Must be called with interrupts disabled.
200 */
201void account_process_vtime(struct task_struct *tsk)
202{
203 cputime_t utime;
204
205 utime = get_paca()->user_time;
206 get_paca()->user_time = 0;
207 account_user_time(tsk, utime);
208}
209
210static void account_process_time(struct pt_regs *regs)
211{
212 int cpu = smp_processor_id();
213
214 account_process_vtime(current);
215 run_local_timers();
216 if (rcu_pending(cpu))
217 rcu_check_callbacks(cpu, user_mode(regs));
218 scheduler_tick();
219 run_posix_cpu_timers(current);
220}
221
222#ifdef CONFIG_PPC_SPLPAR
223/*
224 * Stuff for accounting stolen time.
225 */
226struct cpu_purr_data {
227 int initialized; /* thread is running */
228 u64 tb0; /* timebase at origin time */
229 u64 purr0; /* PURR at origin time */
230 u64 tb; /* last TB value read */
231 u64 purr; /* last PURR value read */
232 u64 stolen; /* stolen time so far */
233 spinlock_t lock;
234};
235
236static DEFINE_PER_CPU(struct cpu_purr_data, cpu_purr_data);
237
238static void snapshot_tb_and_purr(void *data)
239{
240 struct cpu_purr_data *p = &__get_cpu_var(cpu_purr_data);
241
242 p->tb0 = mftb();
243 p->purr0 = mfspr(SPRN_PURR);
244 p->tb = p->tb0;
245 p->purr = 0;
246 wmb();
247 p->initialized = 1;
248}
249
250/*
251 * Called during boot when all cpus have come up.
252 */
253void snapshot_timebases(void)
254{
255 int cpu;
256
257 if (!cpu_has_feature(CPU_FTR_PURR))
258 return;
259 for_each_cpu(cpu)
260 spin_lock_init(&per_cpu(cpu_purr_data, cpu).lock);
261 on_each_cpu(snapshot_tb_and_purr, NULL, 0, 1);
262}
263
264void calculate_steal_time(void)
265{
266 u64 tb, purr, t0;
267 s64 stolen;
268 struct cpu_purr_data *p0, *pme, *phim;
269 int cpu;
270
271 if (!cpu_has_feature(CPU_FTR_PURR))
272 return;
273 cpu = smp_processor_id();
274 pme = &per_cpu(cpu_purr_data, cpu);
275 if (!pme->initialized)
276 return; /* this can happen in early boot */
277 p0 = &per_cpu(cpu_purr_data, cpu & ~1);
278 phim = &per_cpu(cpu_purr_data, cpu ^ 1);
279 spin_lock(&p0->lock);
280 tb = mftb();
281 purr = mfspr(SPRN_PURR) - pme->purr0;
282 if (!phim->initialized || !cpu_online(cpu ^ 1)) {
283 stolen = (tb - pme->tb) - (purr - pme->purr);
284 } else {
285 t0 = pme->tb0;
286 if (phim->tb0 < t0)
287 t0 = phim->tb0;
288 stolen = phim->tb - t0 - phim->purr - purr - p0->stolen;
289 }
290 if (stolen > 0) {
291 account_steal_time(current, stolen);
292 p0->stolen += stolen;
293 }
294 pme->tb = tb;
295 pme->purr = purr;
296 spin_unlock(&p0->lock);
297}
298
299/*
300 * Must be called before the cpu is added to the online map when
301 * a cpu is being brought up at runtime.
302 */
303static void snapshot_purr(void)
304{
305 int cpu;
306 u64 purr;
307 struct cpu_purr_data *p0, *pme, *phim;
308 unsigned long flags;
309
310 if (!cpu_has_feature(CPU_FTR_PURR))
311 return;
312 cpu = smp_processor_id();
313 pme = &per_cpu(cpu_purr_data, cpu);
314 p0 = &per_cpu(cpu_purr_data, cpu & ~1);
315 phim = &per_cpu(cpu_purr_data, cpu ^ 1);
316 spin_lock_irqsave(&p0->lock, flags);
317 pme->tb = pme->tb0 = mftb();
318 purr = mfspr(SPRN_PURR);
319 if (!phim->initialized) {
320 pme->purr = 0;
321 pme->purr0 = purr;
322 } else {
323 /* set p->purr and p->purr0 for no change in p0->stolen */
324 pme->purr = phim->tb - phim->tb0 - phim->purr - p0->stolen;
325 pme->purr0 = purr - pme->purr;
326 }
327 pme->initialized = 1;
328 spin_unlock_irqrestore(&p0->lock, flags);
329}
330
331#endif /* CONFIG_PPC_SPLPAR */
332
333#else /* ! CONFIG_VIRT_CPU_ACCOUNTING */
334#define calc_cputime_factors()
335#define account_process_time(regs) update_process_times(user_mode(regs))
336#define calculate_steal_time() do { } while (0)
337#endif
338
339#if !(defined(CONFIG_VIRT_CPU_ACCOUNTING) && defined(CONFIG_PPC_SPLPAR))
340#define snapshot_purr() do { } while (0)
341#endif
342
343/*
344 * Called when a cpu comes up after the system has finished booting,
345 * i.e. as a result of a hotplug cpu action.
346 */
347void snapshot_timebase(void)
348{
349 __get_cpu_var(last_jiffy) = get_tb();
350 snapshot_purr();
351}
352
6defa38b
PM
353void __delay(unsigned long loops)
354{
355 unsigned long start;
356 int diff;
357
358 if (__USE_RTC()) {
359 start = get_rtcl();
360 do {
361 /* the RTCL register wraps at 1000000000 */
362 diff = get_rtcl() - start;
363 if (diff < 0)
364 diff += 1000000000;
365 } while (diff < loops);
366 } else {
367 start = get_tbl();
368 while (get_tbl() - start < loops)
369 HMT_low();
370 HMT_medium();
371 }
372}
373EXPORT_SYMBOL(__delay);
374
375void udelay(unsigned long usecs)
376{
377 __delay(tb_ticks_per_usec * usecs);
378}
379EXPORT_SYMBOL(udelay);
380
1da177e4
LT
381static __inline__ void timer_check_rtc(void)
382{
383 /*
384 * update the rtc when needed, this should be performed on the
385 * right fraction of a second. Half or full second ?
386 * Full second works on mk48t59 clocks, others need testing.
387 * Note that this update is basically only used through
388 * the adjtimex system calls. Setting the HW clock in
389 * any other way is a /dev/rtc and userland business.
390 * This is still wrong by -0.5/+1.5 jiffies because of the
391 * timer interrupt resolution and possible delay, but here we
392 * hit a quantization limit which can only be solved by higher
393 * resolution timers and decoupling time management from timer
394 * interrupts. This is also wrong on the clocks
395 * which require being written at the half second boundary.
396 * We should have an rtc call that only sets the minutes and
397 * seconds like on Intel to avoid problems with non UTC clocks.
398 */
d2e61512 399 if (ppc_md.set_rtc_time && ntp_synced() &&
f2783c15 400 xtime.tv_sec - last_rtc_update >= 659 &&
092b8f34 401 abs((xtime.tv_nsec/1000) - (1000000-1000000/HZ)) < 500000/HZ) {
f2783c15
PM
402 struct rtc_time tm;
403 to_tm(xtime.tv_sec + 1 + timezone_offset, &tm);
404 tm.tm_year -= 1900;
405 tm.tm_mon -= 1;
406 if (ppc_md.set_rtc_time(&tm) == 0)
407 last_rtc_update = xtime.tv_sec + 1;
408 else
409 /* Try again one minute later */
410 last_rtc_update += 60;
1da177e4
LT
411 }
412}
413
414/*
415 * This version of gettimeofday has microsecond resolution.
416 */
f2783c15 417static inline void __do_gettimeofday(struct timeval *tv, u64 tb_val)
1da177e4 418{
f2783c15
PM
419 unsigned long sec, usec;
420 u64 tb_ticks, xsec;
421 struct gettimeofday_vars *temp_varp;
422 u64 temp_tb_to_xs, temp_stamp_xsec;
1da177e4
LT
423
424 /*
425 * These calculations are faster (gets rid of divides)
426 * if done in units of 1/2^20 rather than microseconds.
427 * The conversion to microseconds at the end is done
428 * without a divide (and in fact, without a multiply)
429 */
430 temp_varp = do_gtod.varp;
431 tb_ticks = tb_val - temp_varp->tb_orig_stamp;
432 temp_tb_to_xs = temp_varp->tb_to_xs;
433 temp_stamp_xsec = temp_varp->stamp_xsec;
f2783c15 434 xsec = temp_stamp_xsec + mulhdu(tb_ticks, temp_tb_to_xs);
1da177e4 435 sec = xsec / XSEC_PER_SEC;
f2783c15
PM
436 usec = (unsigned long)xsec & (XSEC_PER_SEC - 1);
437 usec = SCALE_XSEC(usec, 1000000);
1da177e4
LT
438
439 tv->tv_sec = sec;
440 tv->tv_usec = usec;
441}
442
443void do_gettimeofday(struct timeval *tv)
444{
96c44507
PM
445 if (__USE_RTC()) {
446 /* do this the old way */
447 unsigned long flags, seq;
092b8f34 448 unsigned int sec, nsec, usec;
96c44507
PM
449
450 do {
451 seq = read_seqbegin_irqsave(&xtime_lock, flags);
452 sec = xtime.tv_sec;
453 nsec = xtime.tv_nsec + tb_ticks_since(tb_last_stamp);
96c44507 454 } while (read_seqretry_irqrestore(&xtime_lock, seq, flags));
092b8f34 455 usec = nsec / 1000;
96c44507
PM
456 while (usec >= 1000000) {
457 usec -= 1000000;
458 ++sec;
459 }
460 tv->tv_sec = sec;
461 tv->tv_usec = usec;
462 return;
463 }
1da177e4
LT
464 __do_gettimeofday(tv, get_tb());
465}
466
467EXPORT_SYMBOL(do_gettimeofday);
468
1da177e4 469/*
f2783c15
PM
470 * There are two copies of tb_to_xs and stamp_xsec so that no
471 * lock is needed to access and use these values in
472 * do_gettimeofday. We alternate the copies and as long as a
473 * reasonable time elapses between changes, there will never
474 * be inconsistent values. ntpd has a minimum of one minute
475 * between updates.
1da177e4 476 */
f2783c15 477static inline void update_gtod(u64 new_tb_stamp, u64 new_stamp_xsec,
5d14a18d 478 u64 new_tb_to_xs)
1da177e4 479{
1da177e4 480 unsigned temp_idx;
f2783c15 481 struct gettimeofday_vars *temp_varp;
1da177e4
LT
482
483 temp_idx = (do_gtod.var_idx == 0);
484 temp_varp = &do_gtod.vars[temp_idx];
485
f2783c15
PM
486 temp_varp->tb_to_xs = new_tb_to_xs;
487 temp_varp->tb_orig_stamp = new_tb_stamp;
1da177e4 488 temp_varp->stamp_xsec = new_stamp_xsec;
0d8d4d42 489 smp_mb();
1da177e4
LT
490 do_gtod.varp = temp_varp;
491 do_gtod.var_idx = temp_idx;
492
f2783c15
PM
493 /*
494 * tb_update_count is used to allow the userspace gettimeofday code
495 * to assure itself that it sees a consistent view of the tb_to_xs and
496 * stamp_xsec variables. It reads the tb_update_count, then reads
497 * tb_to_xs and stamp_xsec and then reads tb_update_count again. If
498 * the two values of tb_update_count match and are even then the
499 * tb_to_xs and stamp_xsec values are consistent. If not, then it
500 * loops back and reads them again until this criteria is met.
501 */
a7f290da 502 ++(vdso_data->tb_update_count);
0d8d4d42 503 smp_wmb();
a7f290da
BH
504 vdso_data->tb_orig_stamp = new_tb_stamp;
505 vdso_data->stamp_xsec = new_stamp_xsec;
506 vdso_data->tb_to_xs = new_tb_to_xs;
507 vdso_data->wtom_clock_sec = wall_to_monotonic.tv_sec;
508 vdso_data->wtom_clock_nsec = wall_to_monotonic.tv_nsec;
0d8d4d42 509 smp_wmb();
a7f290da 510 ++(vdso_data->tb_update_count);
f2783c15
PM
511}
512
513/*
514 * When the timebase - tb_orig_stamp gets too big, we do a manipulation
515 * between tb_orig_stamp and stamp_xsec. The goal here is to keep the
516 * difference tb - tb_orig_stamp small enough to always fit inside a
517 * 32 bits number. This is a requirement of our fast 32 bits userland
518 * implementation in the vdso. If we "miss" a call to this function
519 * (interrupt latency, CPU locked in a spinlock, ...) and we end up
520 * with a too big difference, then the vdso will fallback to calling
521 * the syscall
522 */
523static __inline__ void timer_recalc_offset(u64 cur_tb)
524{
525 unsigned long offset;
526 u64 new_stamp_xsec;
092b8f34 527 u64 tlen, t2x;
f2783c15 528
96c44507
PM
529 if (__USE_RTC())
530 return;
092b8f34 531 tlen = current_tick_length();
f2783c15 532 offset = cur_tb - do_gtod.varp->tb_orig_stamp;
092b8f34
PM
533 if (tlen == last_tick_len && offset < 0x80000000u) {
534 /* check that we're still in sync; if not, resync */
535 struct timeval tv;
536 __do_gettimeofday(&tv, cur_tb);
537 if (tv.tv_sec <= xtime.tv_sec &&
538 (tv.tv_sec < xtime.tv_sec ||
539 tv.tv_usec * 1000 <= xtime.tv_nsec))
540 return;
541 }
542 if (tlen != last_tick_len) {
543 t2x = mulhdu(tlen << TICKLEN_SHIFT, ticklen_to_xs);
544 last_tick_len = tlen;
545 } else
546 t2x = do_gtod.varp->tb_to_xs;
547 new_stamp_xsec = (u64) xtime.tv_nsec * XSEC_PER_SEC;
548 do_div(new_stamp_xsec, 1000000000);
549 new_stamp_xsec += (u64) xtime.tv_sec * XSEC_PER_SEC;
550 update_gtod(cur_tb, new_stamp_xsec, t2x);
1da177e4
LT
551}
552
553#ifdef CONFIG_SMP
554unsigned long profile_pc(struct pt_regs *regs)
555{
556 unsigned long pc = instruction_pointer(regs);
557
558 if (in_lock_functions(pc))
559 return regs->link;
560
561 return pc;
562}
563EXPORT_SYMBOL(profile_pc);
564#endif
565
566#ifdef CONFIG_PPC_ISERIES
567
568/*
569 * This function recalibrates the timebase based on the 49-bit time-of-day
570 * value in the Titan chip. The Titan is much more accurate than the value
571 * returned by the service processor for the timebase frequency.
572 */
573
574static void iSeries_tb_recal(void)
575{
576 struct div_result divres;
577 unsigned long titan, tb;
578 tb = get_tb();
579 titan = HvCallXm_loadTod();
580 if ( iSeries_recal_titan ) {
581 unsigned long tb_ticks = tb - iSeries_recal_tb;
582 unsigned long titan_usec = (titan - iSeries_recal_titan) >> 12;
583 unsigned long new_tb_ticks_per_sec = (tb_ticks * USEC_PER_SEC)/titan_usec;
584 unsigned long new_tb_ticks_per_jiffy = (new_tb_ticks_per_sec+(HZ/2))/HZ;
585 long tick_diff = new_tb_ticks_per_jiffy - tb_ticks_per_jiffy;
586 char sign = '+';
587 /* make sure tb_ticks_per_sec and tb_ticks_per_jiffy are consistent */
588 new_tb_ticks_per_sec = new_tb_ticks_per_jiffy * HZ;
589
590 if ( tick_diff < 0 ) {
591 tick_diff = -tick_diff;
592 sign = '-';
593 }
594 if ( tick_diff ) {
595 if ( tick_diff < tb_ticks_per_jiffy/25 ) {
596 printk( "Titan recalibrate: new tb_ticks_per_jiffy = %lu (%c%ld)\n",
597 new_tb_ticks_per_jiffy, sign, tick_diff );
598 tb_ticks_per_jiffy = new_tb_ticks_per_jiffy;
599 tb_ticks_per_sec = new_tb_ticks_per_sec;
c6622f63 600 calc_cputime_factors();
1da177e4
LT
601 div128_by_32( XSEC_PER_SEC, 0, tb_ticks_per_sec, &divres );
602 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
603 tb_to_xs = divres.result_low;
604 do_gtod.varp->tb_to_xs = tb_to_xs;
a7f290da
BH
605 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
606 vdso_data->tb_to_xs = tb_to_xs;
1da177e4
LT
607 }
608 else {
609 printk( "Titan recalibrate: FAILED (difference > 4 percent)\n"
610 " new tb_ticks_per_jiffy = %lu\n"
611 " old tb_ticks_per_jiffy = %lu\n",
612 new_tb_ticks_per_jiffy, tb_ticks_per_jiffy );
613 }
614 }
615 }
616 iSeries_recal_titan = titan;
617 iSeries_recal_tb = tb;
618}
619#endif
620
621/*
622 * For iSeries shared processors, we have to let the hypervisor
623 * set the hardware decrementer. We set a virtual decrementer
624 * in the lppaca and call the hypervisor if the virtual
625 * decrementer is less than the current value in the hardware
626 * decrementer. (almost always the new decrementer value will
627 * be greater than the current hardware decementer so the hypervisor
628 * call will not be needed)
629 */
630
1da177e4
LT
631/*
632 * timer_interrupt - gets called when the decrementer overflows,
633 * with interrupts disabled.
634 */
c7aeffc4 635void timer_interrupt(struct pt_regs * regs)
1da177e4
LT
636{
637 int next_dec;
f2783c15
PM
638 int cpu = smp_processor_id();
639 unsigned long ticks;
640
641#ifdef CONFIG_PPC32
642 if (atomic_read(&ppc_n_lost_interrupts) != 0)
643 do_IRQ(regs);
644#endif
1da177e4
LT
645
646 irq_enter();
647
1da177e4 648 profile_tick(CPU_PROFILING, regs);
c6622f63 649 calculate_steal_time();
1da177e4 650
f2783c15 651#ifdef CONFIG_PPC_ISERIES
3356bb9f 652 get_lppaca()->int_dword.fields.decr_int = 0;
f2783c15
PM
653#endif
654
655 while ((ticks = tb_ticks_since(per_cpu(last_jiffy, cpu)))
656 >= tb_ticks_per_jiffy) {
657 /* Update last_jiffy */
658 per_cpu(last_jiffy, cpu) += tb_ticks_per_jiffy;
659 /* Handle RTCL overflow on 601 */
660 if (__USE_RTC() && per_cpu(last_jiffy, cpu) >= 1000000000)
661 per_cpu(last_jiffy, cpu) -= 1000000000;
1da177e4 662
1da177e4
LT
663 /*
664 * We cannot disable the decrementer, so in the period
665 * between this cpu's being marked offline in cpu_online_map
666 * and calling stop-self, it is taking timer interrupts.
667 * Avoid calling into the scheduler rebalancing code if this
668 * is the case.
669 */
670 if (!cpu_is_offline(cpu))
c6622f63 671 account_process_time(regs);
f2783c15 672
1da177e4
LT
673 /*
674 * No need to check whether cpu is offline here; boot_cpuid
675 * should have been fixed up by now.
676 */
f2783c15
PM
677 if (cpu != boot_cpuid)
678 continue;
679
680 write_seqlock(&xtime_lock);
96c44507
PM
681 tb_last_jiffy += tb_ticks_per_jiffy;
682 tb_last_stamp = per_cpu(last_jiffy, cpu);
f2783c15 683 do_timer(regs);
092b8f34 684 timer_recalc_offset(tb_last_jiffy);
f2783c15
PM
685 timer_check_rtc();
686 write_sequnlock(&xtime_lock);
1da177e4
LT
687 }
688
f2783c15 689 next_dec = tb_ticks_per_jiffy - ticks;
1da177e4
LT
690 set_dec(next_dec);
691
692#ifdef CONFIG_PPC_ISERIES
937b31b1 693 if (hvlpevent_is_pending())
74889802 694 process_hvlpevents(regs);
1da177e4
LT
695#endif
696
f2783c15 697#ifdef CONFIG_PPC64
8d15a3e5 698 /* collect purr register values often, for accurate calculations */
1ababe11 699 if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
1da177e4
LT
700 struct cpu_usage *cu = &__get_cpu_var(cpu_usage_array);
701 cu->current_tb = mfspr(SPRN_PURR);
702 }
f2783c15 703#endif
1da177e4
LT
704
705 irq_exit();
1da177e4
LT
706}
707
f2783c15
PM
708void wakeup_decrementer(void)
709{
092b8f34 710 unsigned long ticks;
f2783c15 711
f2783c15 712 /*
092b8f34
PM
713 * The timebase gets saved on sleep and restored on wakeup,
714 * so all we need to do is to reset the decrementer.
f2783c15 715 */
092b8f34
PM
716 ticks = tb_ticks_since(__get_cpu_var(last_jiffy));
717 if (ticks < tb_ticks_per_jiffy)
718 ticks = tb_ticks_per_jiffy - ticks;
719 else
720 ticks = 1;
721 set_dec(ticks);
f2783c15
PM
722}
723
a5b518ed 724#ifdef CONFIG_SMP
f2783c15
PM
725void __init smp_space_timers(unsigned int max_cpus)
726{
727 int i;
c6622f63 728 unsigned long half = tb_ticks_per_jiffy / 2;
f2783c15
PM
729 unsigned long offset = tb_ticks_per_jiffy / max_cpus;
730 unsigned long previous_tb = per_cpu(last_jiffy, boot_cpuid);
731
cbe62e2b
PM
732 /* make sure tb > per_cpu(last_jiffy, cpu) for all cpus always */
733 previous_tb -= tb_ticks_per_jiffy;
c6622f63
PM
734 /*
735 * The stolen time calculation for POWER5 shared-processor LPAR
736 * systems works better if the two threads' timebase interrupts
737 * are staggered by half a jiffy with respect to each other.
738 */
f2783c15 739 for_each_cpu(i) {
c6622f63
PM
740 if (i == boot_cpuid)
741 continue;
742 if (i == (boot_cpuid ^ 1))
743 per_cpu(last_jiffy, i) =
744 per_cpu(last_jiffy, boot_cpuid) - half;
745 else if (i & 1)
746 per_cpu(last_jiffy, i) =
747 per_cpu(last_jiffy, i ^ 1) + half;
748 else {
f2783c15
PM
749 previous_tb += offset;
750 per_cpu(last_jiffy, i) = previous_tb;
751 }
752 }
753}
754#endif
755
1da177e4
LT
756/*
757 * Scheduler clock - returns current time in nanosec units.
758 *
759 * Note: mulhdu(a, b) (multiply high double unsigned) returns
760 * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
761 * are 64-bit unsigned numbers.
762 */
763unsigned long long sched_clock(void)
764{
96c44507
PM
765 if (__USE_RTC())
766 return get_rtc();
1da177e4
LT
767 return mulhdu(get_tb(), tb_to_ns_scale) << tb_to_ns_shift;
768}
769
770int do_settimeofday(struct timespec *tv)
771{
772 time_t wtm_sec, new_sec = tv->tv_sec;
773 long wtm_nsec, new_nsec = tv->tv_nsec;
774 unsigned long flags;
092b8f34
PM
775 u64 new_xsec;
776 unsigned long tb_delta;
1da177e4
LT
777
778 if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
779 return -EINVAL;
780
781 write_seqlock_irqsave(&xtime_lock, flags);
f2783c15
PM
782
783 /*
784 * Updating the RTC is not the job of this code. If the time is
785 * stepped under NTP, the RTC will be updated after STA_UNSYNC
786 * is cleared. Tools like clock/hwclock either copy the RTC
1da177e4
LT
787 * to the system time, in which case there is no point in writing
788 * to the RTC again, or write to the RTC but then they don't call
789 * settimeofday to perform this operation.
790 */
791#ifdef CONFIG_PPC_ISERIES
f2783c15 792 if (first_settimeofday) {
1da177e4
LT
793 iSeries_tb_recal();
794 first_settimeofday = 0;
795 }
796#endif
092b8f34
PM
797
798 /*
799 * Subtract off the number of nanoseconds since the
800 * beginning of the last tick.
801 * Note that since we don't increment jiffies_64 anywhere other
802 * than in do_timer (since we don't have a lost tick problem),
803 * wall_jiffies will always be the same as jiffies,
804 * and therefore the (jiffies - wall_jiffies) computation
805 * has been removed.
806 */
1da177e4 807 tb_delta = tb_ticks_since(tb_last_stamp);
092b8f34
PM
808 tb_delta = mulhdu(tb_delta, do_gtod.varp->tb_to_xs); /* in xsec */
809 new_nsec -= SCALE_XSEC(tb_delta, 1000000000);
1da177e4
LT
810
811 wtm_sec = wall_to_monotonic.tv_sec + (xtime.tv_sec - new_sec);
812 wtm_nsec = wall_to_monotonic.tv_nsec + (xtime.tv_nsec - new_nsec);
813
814 set_normalized_timespec(&xtime, new_sec, new_nsec);
815 set_normalized_timespec(&wall_to_monotonic, wtm_sec, wtm_nsec);
816
817 /* In case of a large backwards jump in time with NTP, we want the
818 * clock to be updated as soon as the PLL is again in lock.
819 */
820 last_rtc_update = new_sec - 658;
821
b149ee22 822 ntp_clear();
1da177e4 823
092b8f34
PM
824 new_xsec = xtime.tv_nsec;
825 if (new_xsec != 0) {
826 new_xsec *= XSEC_PER_SEC;
5f6b5b97
PM
827 do_div(new_xsec, NSEC_PER_SEC);
828 }
092b8f34 829 new_xsec += (u64)xtime.tv_sec * XSEC_PER_SEC;
96c44507 830 update_gtod(tb_last_jiffy, new_xsec, do_gtod.varp->tb_to_xs);
1da177e4 831
a7f290da
BH
832 vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
833 vdso_data->tz_dsttime = sys_tz.tz_dsttime;
1da177e4
LT
834
835 write_sequnlock_irqrestore(&xtime_lock, flags);
836 clock_was_set();
837 return 0;
838}
839
840EXPORT_SYMBOL(do_settimeofday);
841
10f7e7c1
AB
842void __init generic_calibrate_decr(void)
843{
844 struct device_node *cpu;
10f7e7c1
AB
845 unsigned int *fp;
846 int node_found;
847
848 /*
849 * The cpu node should have a timebase-frequency property
850 * to tell us the rate at which the decrementer counts.
851 */
852 cpu = of_find_node_by_type(NULL, "cpu");
853
854 ppc_tb_freq = DEFAULT_TB_FREQ; /* hardcoded default */
855 node_found = 0;
d8a8188d 856 if (cpu) {
10f7e7c1
AB
857 fp = (unsigned int *)get_property(cpu, "timebase-frequency",
858 NULL);
d8a8188d 859 if (fp) {
10f7e7c1
AB
860 node_found = 1;
861 ppc_tb_freq = *fp;
862 }
863 }
864 if (!node_found)
865 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
866 "(not found)\n");
867
868 ppc_proc_freq = DEFAULT_PROC_FREQ;
869 node_found = 0;
d8a8188d 870 if (cpu) {
10f7e7c1
AB
871 fp = (unsigned int *)get_property(cpu, "clock-frequency",
872 NULL);
d8a8188d 873 if (fp) {
10f7e7c1
AB
874 node_found = 1;
875 ppc_proc_freq = *fp;
876 }
877 }
0fd6f717
KG
878#ifdef CONFIG_BOOKE
879 /* Set the time base to zero */
880 mtspr(SPRN_TBWL, 0);
881 mtspr(SPRN_TBWU, 0);
882
883 /* Clear any pending timer interrupts */
884 mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
885
886 /* Enable decrementer interrupt */
887 mtspr(SPRN_TCR, TCR_DIE);
888#endif
10f7e7c1
AB
889 if (!node_found)
890 printk(KERN_ERR "WARNING: Estimating processor frequency "
891 "(not found)\n");
892
893 of_node_put(cpu);
10f7e7c1 894}
10f7e7c1 895
f2783c15
PM
896unsigned long get_boot_time(void)
897{
898 struct rtc_time tm;
899
900 if (ppc_md.get_boot_time)
901 return ppc_md.get_boot_time();
902 if (!ppc_md.get_rtc_time)
903 return 0;
904 ppc_md.get_rtc_time(&tm);
905 return mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
906 tm.tm_hour, tm.tm_min, tm.tm_sec);
907}
908
909/* This function is only called on the boot processor */
1da177e4
LT
910void __init time_init(void)
911{
1da177e4 912 unsigned long flags;
f2783c15 913 unsigned long tm = 0;
1da177e4 914 struct div_result res;
092b8f34 915 u64 scale, x;
f2783c15
PM
916 unsigned shift;
917
918 if (ppc_md.time_init != NULL)
919 timezone_offset = ppc_md.time_init();
1da177e4 920
96c44507
PM
921 if (__USE_RTC()) {
922 /* 601 processor: dec counts down by 128 every 128ns */
923 ppc_tb_freq = 1000000000;
924 tb_last_stamp = get_rtcl();
925 tb_last_jiffy = tb_last_stamp;
926 } else {
927 /* Normal PowerPC with timebase register */
928 ppc_md.calibrate_decr();
929 printk(KERN_INFO "time_init: decrementer frequency = %lu.%.6lu MHz\n",
930 ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
931 printk(KERN_INFO "time_init: processor frequency = %lu.%.6lu MHz\n",
932 ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
933 tb_last_stamp = tb_last_jiffy = get_tb();
934 }
374e99d4
PM
935
936 tb_ticks_per_jiffy = ppc_tb_freq / HZ;
092b8f34 937 tb_ticks_per_sec = ppc_tb_freq;
374e99d4
PM
938 tb_ticks_per_usec = ppc_tb_freq / 1000000;
939 tb_to_us = mulhwu_scale_factor(ppc_tb_freq, 1000000);
c6622f63 940 calc_cputime_factors();
092b8f34
PM
941
942 /*
943 * Calculate the length of each tick in ns. It will not be
944 * exactly 1e9/HZ unless ppc_tb_freq is divisible by HZ.
945 * We compute 1e9 * tb_ticks_per_jiffy / ppc_tb_freq,
946 * rounded up.
947 */
948 x = (u64) NSEC_PER_SEC * tb_ticks_per_jiffy + ppc_tb_freq - 1;
949 do_div(x, ppc_tb_freq);
950 tick_nsec = x;
951 last_tick_len = x << TICKLEN_SCALE;
952
953 /*
954 * Compute ticklen_to_xs, which is a factor which gets multiplied
955 * by (last_tick_len << TICKLEN_SHIFT) to get a tb_to_xs value.
956 * It is computed as:
957 * ticklen_to_xs = 2^N / (tb_ticks_per_jiffy * 1e9)
958 * where N = 64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT
959 * so as to give the result as a 0.64 fixed-point fraction.
960 */
961 div128_by_32(1ULL << (64 + 20 - TICKLEN_SCALE - TICKLEN_SHIFT), 0,
962 tb_ticks_per_jiffy, &res);
963 div128_by_32(res.result_high, res.result_low, NSEC_PER_SEC, &res);
964 ticklen_to_xs = res.result_low;
965
966 /* Compute tb_to_xs from tick_nsec */
967 tb_to_xs = mulhdu(last_tick_len << TICKLEN_SHIFT, ticklen_to_xs);
374e99d4 968
1da177e4
LT
969 /*
970 * Compute scale factor for sched_clock.
971 * The calibrate_decr() function has set tb_ticks_per_sec,
972 * which is the timebase frequency.
973 * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
974 * the 128-bit result as a 64.64 fixed-point number.
975 * We then shift that number right until it is less than 1.0,
976 * giving us the scale factor and shift count to use in
977 * sched_clock().
978 */
979 div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
980 scale = res.result_low;
981 for (shift = 0; res.result_high != 0; ++shift) {
982 scale = (scale >> 1) | (res.result_high << 63);
983 res.result_high >>= 1;
984 }
985 tb_to_ns_scale = scale;
986 tb_to_ns_shift = shift;
987
988#ifdef CONFIG_PPC_ISERIES
989 if (!piranha_simulator)
990#endif
f2783c15 991 tm = get_boot_time();
1da177e4
LT
992
993 write_seqlock_irqsave(&xtime_lock, flags);
092b8f34
PM
994
995 /* If platform provided a timezone (pmac), we correct the time */
996 if (timezone_offset) {
997 sys_tz.tz_minuteswest = -timezone_offset / 60;
998 sys_tz.tz_dsttime = 0;
999 tm -= timezone_offset;
1000 }
1001
f2783c15
PM
1002 xtime.tv_sec = tm;
1003 xtime.tv_nsec = 0;
1da177e4
LT
1004 do_gtod.varp = &do_gtod.vars[0];
1005 do_gtod.var_idx = 0;
96c44507 1006 do_gtod.varp->tb_orig_stamp = tb_last_jiffy;
f2783c15
PM
1007 __get_cpu_var(last_jiffy) = tb_last_stamp;
1008 do_gtod.varp->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
1da177e4
LT
1009 do_gtod.tb_ticks_per_sec = tb_ticks_per_sec;
1010 do_gtod.varp->tb_to_xs = tb_to_xs;
1011 do_gtod.tb_to_us = tb_to_us;
a7f290da
BH
1012
1013 vdso_data->tb_orig_stamp = tb_last_jiffy;
1014 vdso_data->tb_update_count = 0;
1015 vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
092b8f34 1016 vdso_data->stamp_xsec = (u64) xtime.tv_sec * XSEC_PER_SEC;
a7f290da 1017 vdso_data->tb_to_xs = tb_to_xs;
1da177e4
LT
1018
1019 time_freq = 0;
1020
1da177e4
LT
1021 last_rtc_update = xtime.tv_sec;
1022 set_normalized_timespec(&wall_to_monotonic,
1023 -xtime.tv_sec, -xtime.tv_nsec);
1024 write_sequnlock_irqrestore(&xtime_lock, flags);
1025
1026 /* Not exact, but the timer interrupt takes care of this */
1027 set_dec(tb_ticks_per_jiffy);
1028}
1029
1da177e4 1030
1da177e4
LT
1031#define FEBRUARY 2
1032#define STARTOFTIME 1970
1033#define SECDAY 86400L
1034#define SECYR (SECDAY * 365)
f2783c15
PM
1035#define leapyear(year) ((year) % 4 == 0 && \
1036 ((year) % 100 != 0 || (year) % 400 == 0))
1da177e4
LT
1037#define days_in_year(a) (leapyear(a) ? 366 : 365)
1038#define days_in_month(a) (month_days[(a) - 1])
1039
1040static int month_days[12] = {
1041 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
1042};
1043
1044/*
1045 * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
1046 */
1047void GregorianDay(struct rtc_time * tm)
1048{
1049 int leapsToDate;
1050 int lastYear;
1051 int day;
1052 int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
1053
f2783c15 1054 lastYear = tm->tm_year - 1;
1da177e4
LT
1055
1056 /*
1057 * Number of leap corrections to apply up to end of last year
1058 */
f2783c15 1059 leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
1da177e4
LT
1060
1061 /*
1062 * This year is a leap year if it is divisible by 4 except when it is
1063 * divisible by 100 unless it is divisible by 400
1064 *
f2783c15 1065 * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
1da177e4 1066 */
f2783c15 1067 day = tm->tm_mon > 2 && leapyear(tm->tm_year);
1da177e4
LT
1068
1069 day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
1070 tm->tm_mday;
1071
f2783c15 1072 tm->tm_wday = day % 7;
1da177e4
LT
1073}
1074
1075void to_tm(int tim, struct rtc_time * tm)
1076{
1077 register int i;
1078 register long hms, day;
1079
1080 day = tim / SECDAY;
1081 hms = tim % SECDAY;
1082
1083 /* Hours, minutes, seconds are easy */
1084 tm->tm_hour = hms / 3600;
1085 tm->tm_min = (hms % 3600) / 60;
1086 tm->tm_sec = (hms % 3600) % 60;
1087
1088 /* Number of years in days */
1089 for (i = STARTOFTIME; day >= days_in_year(i); i++)
1090 day -= days_in_year(i);
1091 tm->tm_year = i;
1092
1093 /* Number of months in days left */
1094 if (leapyear(tm->tm_year))
1095 days_in_month(FEBRUARY) = 29;
1096 for (i = 1; day >= days_in_month(i); i++)
1097 day -= days_in_month(i);
1098 days_in_month(FEBRUARY) = 28;
1099 tm->tm_mon = i;
1100
1101 /* Days are what is left over (+1) from all that. */
1102 tm->tm_mday = day + 1;
1103
1104 /*
1105 * Determine the day of week
1106 */
1107 GregorianDay(tm);
1108}
1109
1110/* Auxiliary function to compute scaling factors */
1111/* Actually the choice of a timebase running at 1/4 the of the bus
1112 * frequency giving resolution of a few tens of nanoseconds is quite nice.
1113 * It makes this computation very precise (27-28 bits typically) which
1114 * is optimistic considering the stability of most processor clock
1115 * oscillators and the precision with which the timebase frequency
1116 * is measured but does not harm.
1117 */
f2783c15
PM
1118unsigned mulhwu_scale_factor(unsigned inscale, unsigned outscale)
1119{
1da177e4
LT
1120 unsigned mlt=0, tmp, err;
1121 /* No concern for performance, it's done once: use a stupid
1122 * but safe and compact method to find the multiplier.
1123 */
1124
1125 for (tmp = 1U<<31; tmp != 0; tmp >>= 1) {
f2783c15
PM
1126 if (mulhwu(inscale, mlt|tmp) < outscale)
1127 mlt |= tmp;
1da177e4
LT
1128 }
1129
1130 /* We might still be off by 1 for the best approximation.
1131 * A side effect of this is that if outscale is too large
1132 * the returned value will be zero.
1133 * Many corner cases have been checked and seem to work,
1134 * some might have been forgotten in the test however.
1135 */
1136
f2783c15
PM
1137 err = inscale * (mlt+1);
1138 if (err <= inscale/2)
1139 mlt++;
1da177e4 1140 return mlt;
f2783c15 1141}
1da177e4
LT
1142
1143/*
1144 * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1145 * result.
1146 */
f2783c15
PM
1147void div128_by_32(u64 dividend_high, u64 dividend_low,
1148 unsigned divisor, struct div_result *dr)
1da177e4 1149{
f2783c15
PM
1150 unsigned long a, b, c, d;
1151 unsigned long w, x, y, z;
1152 u64 ra, rb, rc;
1da177e4
LT
1153
1154 a = dividend_high >> 32;
1155 b = dividend_high & 0xffffffff;
1156 c = dividend_low >> 32;
1157 d = dividend_low & 0xffffffff;
1158
f2783c15
PM
1159 w = a / divisor;
1160 ra = ((u64)(a - (w * divisor)) << 32) + b;
1161
f2783c15
PM
1162 rb = ((u64) do_div(ra, divisor) << 32) + c;
1163 x = ra;
1da177e4 1164
f2783c15
PM
1165 rc = ((u64) do_div(rb, divisor) << 32) + d;
1166 y = rb;
1167
1168 do_div(rc, divisor);
1169 z = rc;
1da177e4 1170
f2783c15
PM
1171 dr->result_high = ((u64)w << 32) + x;
1172 dr->result_low = ((u64)y << 32) + z;
1da177e4
LT
1173
1174}