Merge tag 'mac80211-for-davem-2015-05-26' of git://git.kernel.org/pub/scm/linux/kerne...
[sfrench/cifs-2.6.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.
21  * - for astronomical applications: add a new function to get
22  * non ambiguous timestamps even around leap seconds. This needs
23  * a new timestamp format and a good name.
24  *
25  * 1997-09-10  Updated NTP code according to technical memorandum Jan '96
26  *             "A Kernel Model for Precision Timekeeping" by Dave Mills
27  *
28  *      This program is free software; you can redistribute it and/or
29  *      modify it under the terms of the GNU General Public License
30  *      as published by the Free Software Foundation; either version
31  *      2 of the License, or (at your option) any later version.
32  */
33
34 #include <linux/errno.h>
35 #include <linux/export.h>
36 #include <linux/sched.h>
37 #include <linux/kernel.h>
38 #include <linux/param.h>
39 #include <linux/string.h>
40 #include <linux/mm.h>
41 #include <linux/interrupt.h>
42 #include <linux/timex.h>
43 #include <linux/kernel_stat.h>
44 #include <linux/time.h>
45 #include <linux/clockchips.h>
46 #include <linux/init.h>
47 #include <linux/profile.h>
48 #include <linux/cpu.h>
49 #include <linux/security.h>
50 #include <linux/percpu.h>
51 #include <linux/rtc.h>
52 #include <linux/jiffies.h>
53 #include <linux/posix-timers.h>
54 #include <linux/irq.h>
55 #include <linux/delay.h>
56 #include <linux/irq_work.h>
57 #include <linux/clk-provider.h>
58 #include <asm/trace.h>
59
60 #include <asm/io.h>
61 #include <asm/processor.h>
62 #include <asm/nvram.h>
63 #include <asm/cache.h>
64 #include <asm/machdep.h>
65 #include <asm/uaccess.h>
66 #include <asm/time.h>
67 #include <asm/prom.h>
68 #include <asm/irq.h>
69 #include <asm/div64.h>
70 #include <asm/smp.h>
71 #include <asm/vdso_datapage.h>
72 #include <asm/firmware.h>
73 #include <asm/cputime.h>
74
75 /* powerpc clocksource/clockevent code */
76
77 #include <linux/clockchips.h>
78 #include <linux/timekeeper_internal.h>
79
80 static cycle_t rtc_read(struct clocksource *);
81 static struct clocksource clocksource_rtc = {
82         .name         = "rtc",
83         .rating       = 400,
84         .flags        = CLOCK_SOURCE_IS_CONTINUOUS,
85         .mask         = CLOCKSOURCE_MASK(64),
86         .read         = rtc_read,
87 };
88
89 static cycle_t timebase_read(struct clocksource *);
90 static struct clocksource clocksource_timebase = {
91         .name         = "timebase",
92         .rating       = 400,
93         .flags        = CLOCK_SOURCE_IS_CONTINUOUS,
94         .mask         = CLOCKSOURCE_MASK(64),
95         .read         = timebase_read,
96 };
97
98 #define DECREMENTER_MAX 0x7fffffff
99
100 static int decrementer_set_next_event(unsigned long evt,
101                                       struct clock_event_device *dev);
102 static void decrementer_set_mode(enum clock_event_mode mode,
103                                  struct clock_event_device *dev);
104
105 struct clock_event_device decrementer_clockevent = {
106         .name           = "decrementer",
107         .rating         = 200,
108         .irq            = 0,
109         .set_next_event = decrementer_set_next_event,
110         .set_mode       = decrementer_set_mode,
111         .features       = CLOCK_EVT_FEAT_ONESHOT | CLOCK_EVT_FEAT_C3STOP,
112 };
113 EXPORT_SYMBOL(decrementer_clockevent);
114
115 DEFINE_PER_CPU(u64, decrementers_next_tb);
116 static DEFINE_PER_CPU(struct clock_event_device, decrementers);
117
118 #define XSEC_PER_SEC (1024*1024)
119
120 #ifdef CONFIG_PPC64
121 #define SCALE_XSEC(xsec, max)   (((xsec) * max) / XSEC_PER_SEC)
122 #else
123 /* compute ((xsec << 12) * max) >> 32 */
124 #define SCALE_XSEC(xsec, max)   mulhwu((xsec) << 12, max)
125 #endif
126
127 unsigned long tb_ticks_per_jiffy;
128 unsigned long tb_ticks_per_usec = 100; /* sane default */
129 EXPORT_SYMBOL(tb_ticks_per_usec);
130 unsigned long tb_ticks_per_sec;
131 EXPORT_SYMBOL(tb_ticks_per_sec);        /* for cputime_t conversions */
132
133 DEFINE_SPINLOCK(rtc_lock);
134 EXPORT_SYMBOL_GPL(rtc_lock);
135
136 static u64 tb_to_ns_scale __read_mostly;
137 static unsigned tb_to_ns_shift __read_mostly;
138 static u64 boot_tb __read_mostly;
139
140 extern struct timezone sys_tz;
141 static long timezone_offset;
142
143 unsigned long ppc_proc_freq;
144 EXPORT_SYMBOL_GPL(ppc_proc_freq);
145 unsigned long ppc_tb_freq;
146 EXPORT_SYMBOL_GPL(ppc_tb_freq);
147
148 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
149 /*
150  * Factors for converting from cputime_t (timebase ticks) to
151  * jiffies, microseconds, seconds, and clock_t (1/USER_HZ seconds).
152  * These are all stored as 0.64 fixed-point binary fractions.
153  */
154 u64 __cputime_jiffies_factor;
155 EXPORT_SYMBOL(__cputime_jiffies_factor);
156 u64 __cputime_usec_factor;
157 EXPORT_SYMBOL(__cputime_usec_factor);
158 u64 __cputime_sec_factor;
159 EXPORT_SYMBOL(__cputime_sec_factor);
160 u64 __cputime_clockt_factor;
161 EXPORT_SYMBOL(__cputime_clockt_factor);
162 DEFINE_PER_CPU(unsigned long, cputime_last_delta);
163 DEFINE_PER_CPU(unsigned long, cputime_scaled_last_delta);
164
165 cputime_t cputime_one_jiffy;
166
167 void (*dtl_consumer)(struct dtl_entry *, u64);
168
169 static void calc_cputime_factors(void)
170 {
171         struct div_result res;
172
173         div128_by_32(HZ, 0, tb_ticks_per_sec, &res);
174         __cputime_jiffies_factor = res.result_low;
175         div128_by_32(1000000, 0, tb_ticks_per_sec, &res);
176         __cputime_usec_factor = res.result_low;
177         div128_by_32(1, 0, tb_ticks_per_sec, &res);
178         __cputime_sec_factor = res.result_low;
179         div128_by_32(USER_HZ, 0, tb_ticks_per_sec, &res);
180         __cputime_clockt_factor = res.result_low;
181 }
182
183 /*
184  * Read the SPURR on systems that have it, otherwise the PURR,
185  * or if that doesn't exist return the timebase value passed in.
186  */
187 static u64 read_spurr(u64 tb)
188 {
189         if (cpu_has_feature(CPU_FTR_SPURR))
190                 return mfspr(SPRN_SPURR);
191         if (cpu_has_feature(CPU_FTR_PURR))
192                 return mfspr(SPRN_PURR);
193         return tb;
194 }
195
196 #ifdef CONFIG_PPC_SPLPAR
197
198 /*
199  * Scan the dispatch trace log and count up the stolen time.
200  * Should be called with interrupts disabled.
201  */
202 static u64 scan_dispatch_log(u64 stop_tb)
203 {
204         u64 i = local_paca->dtl_ridx;
205         struct dtl_entry *dtl = local_paca->dtl_curr;
206         struct dtl_entry *dtl_end = local_paca->dispatch_log_end;
207         struct lppaca *vpa = local_paca->lppaca_ptr;
208         u64 tb_delta;
209         u64 stolen = 0;
210         u64 dtb;
211
212         if (!dtl)
213                 return 0;
214
215         if (i == be64_to_cpu(vpa->dtl_idx))
216                 return 0;
217         while (i < be64_to_cpu(vpa->dtl_idx)) {
218                 dtb = be64_to_cpu(dtl->timebase);
219                 tb_delta = be32_to_cpu(dtl->enqueue_to_dispatch_time) +
220                         be32_to_cpu(dtl->ready_to_enqueue_time);
221                 barrier();
222                 if (i + N_DISPATCH_LOG < be64_to_cpu(vpa->dtl_idx)) {
223                         /* buffer has overflowed */
224                         i = be64_to_cpu(vpa->dtl_idx) - N_DISPATCH_LOG;
225                         dtl = local_paca->dispatch_log + (i % N_DISPATCH_LOG);
226                         continue;
227                 }
228                 if (dtb > stop_tb)
229                         break;
230                 if (dtl_consumer)
231                         dtl_consumer(dtl, i);
232                 stolen += tb_delta;
233                 ++i;
234                 ++dtl;
235                 if (dtl == dtl_end)
236                         dtl = local_paca->dispatch_log;
237         }
238         local_paca->dtl_ridx = i;
239         local_paca->dtl_curr = dtl;
240         return stolen;
241 }
242
243 /*
244  * Accumulate stolen time by scanning the dispatch trace log.
245  * Called on entry from user mode.
246  */
247 void accumulate_stolen_time(void)
248 {
249         u64 sst, ust;
250
251         u8 save_soft_enabled = local_paca->soft_enabled;
252
253         /* We are called early in the exception entry, before
254          * soft/hard_enabled are sync'ed to the expected state
255          * for the exception. We are hard disabled but the PACA
256          * needs to reflect that so various debug stuff doesn't
257          * complain
258          */
259         local_paca->soft_enabled = 0;
260
261         sst = scan_dispatch_log(local_paca->starttime_user);
262         ust = scan_dispatch_log(local_paca->starttime);
263         local_paca->system_time -= sst;
264         local_paca->user_time -= ust;
265         local_paca->stolen_time += ust + sst;
266
267         local_paca->soft_enabled = save_soft_enabled;
268 }
269
270 static inline u64 calculate_stolen_time(u64 stop_tb)
271 {
272         u64 stolen = 0;
273
274         if (get_paca()->dtl_ridx != be64_to_cpu(get_lppaca()->dtl_idx)) {
275                 stolen = scan_dispatch_log(stop_tb);
276                 get_paca()->system_time -= stolen;
277         }
278
279         stolen += get_paca()->stolen_time;
280         get_paca()->stolen_time = 0;
281         return stolen;
282 }
283
284 #else /* CONFIG_PPC_SPLPAR */
285 static inline u64 calculate_stolen_time(u64 stop_tb)
286 {
287         return 0;
288 }
289
290 #endif /* CONFIG_PPC_SPLPAR */
291
292 /*
293  * Account time for a transition between system, hard irq
294  * or soft irq state.
295  */
296 static u64 vtime_delta(struct task_struct *tsk,
297                         u64 *sys_scaled, u64 *stolen)
298 {
299         u64 now, nowscaled, deltascaled;
300         u64 udelta, delta, user_scaled;
301
302         WARN_ON_ONCE(!irqs_disabled());
303
304         now = mftb();
305         nowscaled = read_spurr(now);
306         get_paca()->system_time += now - get_paca()->starttime;
307         get_paca()->starttime = now;
308         deltascaled = nowscaled - get_paca()->startspurr;
309         get_paca()->startspurr = nowscaled;
310
311         *stolen = calculate_stolen_time(now);
312
313         delta = get_paca()->system_time;
314         get_paca()->system_time = 0;
315         udelta = get_paca()->user_time - get_paca()->utime_sspurr;
316         get_paca()->utime_sspurr = get_paca()->user_time;
317
318         /*
319          * Because we don't read the SPURR on every kernel entry/exit,
320          * deltascaled includes both user and system SPURR ticks.
321          * Apportion these ticks to system SPURR ticks and user
322          * SPURR ticks in the same ratio as the system time (delta)
323          * and user time (udelta) values obtained from the timebase
324          * over the same interval.  The system ticks get accounted here;
325          * the user ticks get saved up in paca->user_time_scaled to be
326          * used by account_process_tick.
327          */
328         *sys_scaled = delta;
329         user_scaled = udelta;
330         if (deltascaled != delta + udelta) {
331                 if (udelta) {
332                         *sys_scaled = deltascaled * delta / (delta + udelta);
333                         user_scaled = deltascaled - *sys_scaled;
334                 } else {
335                         *sys_scaled = deltascaled;
336                 }
337         }
338         get_paca()->user_time_scaled += user_scaled;
339
340         return delta;
341 }
342
343 void vtime_account_system(struct task_struct *tsk)
344 {
345         u64 delta, sys_scaled, stolen;
346
347         delta = vtime_delta(tsk, &sys_scaled, &stolen);
348         account_system_time(tsk, 0, delta, sys_scaled);
349         if (stolen)
350                 account_steal_time(stolen);
351 }
352 EXPORT_SYMBOL_GPL(vtime_account_system);
353
354 void vtime_account_idle(struct task_struct *tsk)
355 {
356         u64 delta, sys_scaled, stolen;
357
358         delta = vtime_delta(tsk, &sys_scaled, &stolen);
359         account_idle_time(delta + stolen);
360 }
361
362 /*
363  * Transfer the user time accumulated in the paca
364  * by the exception entry and exit code to the generic
365  * process user time records.
366  * Must be called with interrupts disabled.
367  * Assumes that vtime_account_system/idle() has been called
368  * recently (i.e. since the last entry from usermode) so that
369  * get_paca()->user_time_scaled is up to date.
370  */
371 void vtime_account_user(struct task_struct *tsk)
372 {
373         cputime_t utime, utimescaled;
374
375         utime = get_paca()->user_time;
376         utimescaled = get_paca()->user_time_scaled;
377         get_paca()->user_time = 0;
378         get_paca()->user_time_scaled = 0;
379         get_paca()->utime_sspurr = 0;
380         account_user_time(tsk, utime, utimescaled);
381 }
382
383 #else /* ! CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
384 #define calc_cputime_factors()
385 #endif
386
387 void __delay(unsigned long loops)
388 {
389         unsigned long start;
390         int diff;
391
392         if (__USE_RTC()) {
393                 start = get_rtcl();
394                 do {
395                         /* the RTCL register wraps at 1000000000 */
396                         diff = get_rtcl() - start;
397                         if (diff < 0)
398                                 diff += 1000000000;
399                 } while (diff < loops);
400         } else {
401                 start = get_tbl();
402                 while (get_tbl() - start < loops)
403                         HMT_low();
404                 HMT_medium();
405         }
406 }
407 EXPORT_SYMBOL(__delay);
408
409 void udelay(unsigned long usecs)
410 {
411         __delay(tb_ticks_per_usec * usecs);
412 }
413 EXPORT_SYMBOL(udelay);
414
415 #ifdef CONFIG_SMP
416 unsigned long profile_pc(struct pt_regs *regs)
417 {
418         unsigned long pc = instruction_pointer(regs);
419
420         if (in_lock_functions(pc))
421                 return regs->link;
422
423         return pc;
424 }
425 EXPORT_SYMBOL(profile_pc);
426 #endif
427
428 #ifdef CONFIG_IRQ_WORK
429
430 /*
431  * 64-bit uses a byte in the PACA, 32-bit uses a per-cpu variable...
432  */
433 #ifdef CONFIG_PPC64
434 static inline unsigned long test_irq_work_pending(void)
435 {
436         unsigned long x;
437
438         asm volatile("lbz %0,%1(13)"
439                 : "=r" (x)
440                 : "i" (offsetof(struct paca_struct, irq_work_pending)));
441         return x;
442 }
443
444 static inline void set_irq_work_pending_flag(void)
445 {
446         asm volatile("stb %0,%1(13)" : :
447                 "r" (1),
448                 "i" (offsetof(struct paca_struct, irq_work_pending)));
449 }
450
451 static inline void clear_irq_work_pending(void)
452 {
453         asm volatile("stb %0,%1(13)" : :
454                 "r" (0),
455                 "i" (offsetof(struct paca_struct, irq_work_pending)));
456 }
457
458 #else /* 32-bit */
459
460 DEFINE_PER_CPU(u8, irq_work_pending);
461
462 #define set_irq_work_pending_flag()     __this_cpu_write(irq_work_pending, 1)
463 #define test_irq_work_pending()         __this_cpu_read(irq_work_pending)
464 #define clear_irq_work_pending()        __this_cpu_write(irq_work_pending, 0)
465
466 #endif /* 32 vs 64 bit */
467
468 void arch_irq_work_raise(void)
469 {
470         preempt_disable();
471         set_irq_work_pending_flag();
472         set_dec(1);
473         preempt_enable();
474 }
475
476 #else  /* CONFIG_IRQ_WORK */
477
478 #define test_irq_work_pending() 0
479 #define clear_irq_work_pending()
480
481 #endif /* CONFIG_IRQ_WORK */
482
483 static void __timer_interrupt(void)
484 {
485         struct pt_regs *regs = get_irq_regs();
486         u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
487         struct clock_event_device *evt = this_cpu_ptr(&decrementers);
488         u64 now;
489
490         trace_timer_interrupt_entry(regs);
491
492         if (test_irq_work_pending()) {
493                 clear_irq_work_pending();
494                 irq_work_run();
495         }
496
497         now = get_tb_or_rtc();
498         if (now >= *next_tb) {
499                 *next_tb = ~(u64)0;
500                 if (evt->event_handler)
501                         evt->event_handler(evt);
502                 __this_cpu_inc(irq_stat.timer_irqs_event);
503         } else {
504                 now = *next_tb - now;
505                 if (now <= DECREMENTER_MAX)
506                         set_dec((int)now);
507                 /* We may have raced with new irq work */
508                 if (test_irq_work_pending())
509                         set_dec(1);
510                 __this_cpu_inc(irq_stat.timer_irqs_others);
511         }
512
513 #ifdef CONFIG_PPC64
514         /* collect purr register values often, for accurate calculations */
515         if (firmware_has_feature(FW_FEATURE_SPLPAR)) {
516                 struct cpu_usage *cu = this_cpu_ptr(&cpu_usage_array);
517                 cu->current_tb = mfspr(SPRN_PURR);
518         }
519 #endif
520
521         trace_timer_interrupt_exit(regs);
522 }
523
524 /*
525  * timer_interrupt - gets called when the decrementer overflows,
526  * with interrupts disabled.
527  */
528 void timer_interrupt(struct pt_regs * regs)
529 {
530         struct pt_regs *old_regs;
531         u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
532
533         /* Ensure a positive value is written to the decrementer, or else
534          * some CPUs will continue to take decrementer exceptions.
535          */
536         set_dec(DECREMENTER_MAX);
537
538         /* Some implementations of hotplug will get timer interrupts while
539          * offline, just ignore these and we also need to set
540          * decrementers_next_tb as MAX to make sure __check_irq_replay
541          * don't replay timer interrupt when return, otherwise we'll trap
542          * here infinitely :(
543          */
544         if (!cpu_online(smp_processor_id())) {
545                 *next_tb = ~(u64)0;
546                 return;
547         }
548
549         /* Conditionally hard-enable interrupts now that the DEC has been
550          * bumped to its maximum value
551          */
552         may_hard_irq_enable();
553
554
555 #if defined(CONFIG_PPC32) && defined(CONFIG_PPC_PMAC)
556         if (atomic_read(&ppc_n_lost_interrupts) != 0)
557                 do_IRQ(regs);
558 #endif
559
560         old_regs = set_irq_regs(regs);
561         irq_enter();
562
563         __timer_interrupt();
564         irq_exit();
565         set_irq_regs(old_regs);
566 }
567
568 /*
569  * Hypervisor decrementer interrupts shouldn't occur but are sometimes
570  * left pending on exit from a KVM guest.  We don't need to do anything
571  * to clear them, as they are edge-triggered.
572  */
573 void hdec_interrupt(struct pt_regs *regs)
574 {
575 }
576
577 #ifdef CONFIG_SUSPEND
578 static void generic_suspend_disable_irqs(void)
579 {
580         /* Disable the decrementer, so that it doesn't interfere
581          * with suspending.
582          */
583
584         set_dec(DECREMENTER_MAX);
585         local_irq_disable();
586         set_dec(DECREMENTER_MAX);
587 }
588
589 static void generic_suspend_enable_irqs(void)
590 {
591         local_irq_enable();
592 }
593
594 /* Overrides the weak version in kernel/power/main.c */
595 void arch_suspend_disable_irqs(void)
596 {
597         if (ppc_md.suspend_disable_irqs)
598                 ppc_md.suspend_disable_irqs();
599         generic_suspend_disable_irqs();
600 }
601
602 /* Overrides the weak version in kernel/power/main.c */
603 void arch_suspend_enable_irqs(void)
604 {
605         generic_suspend_enable_irqs();
606         if (ppc_md.suspend_enable_irqs)
607                 ppc_md.suspend_enable_irqs();
608 }
609 #endif
610
611 unsigned long long tb_to_ns(unsigned long long ticks)
612 {
613         return mulhdu(ticks, tb_to_ns_scale) << tb_to_ns_shift;
614 }
615 EXPORT_SYMBOL_GPL(tb_to_ns);
616
617 /*
618  * Scheduler clock - returns current time in nanosec units.
619  *
620  * Note: mulhdu(a, b) (multiply high double unsigned) returns
621  * the high 64 bits of a * b, i.e. (a * b) >> 64, where a and b
622  * are 64-bit unsigned numbers.
623  */
624 unsigned long long sched_clock(void)
625 {
626         if (__USE_RTC())
627                 return get_rtc();
628         return mulhdu(get_tb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
629 }
630
631
632 #ifdef CONFIG_PPC_PSERIES
633
634 /*
635  * Running clock - attempts to give a view of time passing for a virtualised
636  * kernels.
637  * Uses the VTB register if available otherwise a next best guess.
638  */
639 unsigned long long running_clock(void)
640 {
641         /*
642          * Don't read the VTB as a host since KVM does not switch in host
643          * timebase into the VTB when it takes a guest off the CPU, reading the
644          * VTB would result in reading 'last switched out' guest VTB.
645          *
646          * Host kernels are often compiled with CONFIG_PPC_PSERIES checked, it
647          * would be unsafe to rely only on the #ifdef above.
648          */
649         if (firmware_has_feature(FW_FEATURE_LPAR) &&
650             cpu_has_feature(CPU_FTR_ARCH_207S))
651                 return mulhdu(get_vtb() - boot_tb, tb_to_ns_scale) << tb_to_ns_shift;
652
653         /*
654          * This is a next best approximation without a VTB.
655          * On a host which is running bare metal there should never be any stolen
656          * time and on a host which doesn't do any virtualisation TB *should* equal
657          * VTB so it makes no difference anyway.
658          */
659         return local_clock() - cputime_to_nsecs(kcpustat_this_cpu->cpustat[CPUTIME_STEAL]);
660 }
661 #endif
662
663 static int __init get_freq(char *name, int cells, unsigned long *val)
664 {
665         struct device_node *cpu;
666         const __be32 *fp;
667         int found = 0;
668
669         /* The cpu node should have timebase and clock frequency properties */
670         cpu = of_find_node_by_type(NULL, "cpu");
671
672         if (cpu) {
673                 fp = of_get_property(cpu, name, NULL);
674                 if (fp) {
675                         found = 1;
676                         *val = of_read_ulong(fp, cells);
677                 }
678
679                 of_node_put(cpu);
680         }
681
682         return found;
683 }
684
685 static void start_cpu_decrementer(void)
686 {
687 #if defined(CONFIG_BOOKE) || defined(CONFIG_40x)
688         /* Clear any pending timer interrupts */
689         mtspr(SPRN_TSR, TSR_ENW | TSR_WIS | TSR_DIS | TSR_FIS);
690
691         /* Enable decrementer interrupt */
692         mtspr(SPRN_TCR, TCR_DIE);
693 #endif /* defined(CONFIG_BOOKE) || defined(CONFIG_40x) */
694 }
695
696 void __init generic_calibrate_decr(void)
697 {
698         ppc_tb_freq = DEFAULT_TB_FREQ;          /* hardcoded default */
699
700         if (!get_freq("ibm,extended-timebase-frequency", 2, &ppc_tb_freq) &&
701             !get_freq("timebase-frequency", 1, &ppc_tb_freq)) {
702
703                 printk(KERN_ERR "WARNING: Estimating decrementer frequency "
704                                 "(not found)\n");
705         }
706
707         ppc_proc_freq = DEFAULT_PROC_FREQ;      /* hardcoded default */
708
709         if (!get_freq("ibm,extended-clock-frequency", 2, &ppc_proc_freq) &&
710             !get_freq("clock-frequency", 1, &ppc_proc_freq)) {
711
712                 printk(KERN_ERR "WARNING: Estimating processor frequency "
713                                 "(not found)\n");
714         }
715 }
716
717 int update_persistent_clock(struct timespec now)
718 {
719         struct rtc_time tm;
720
721         if (!ppc_md.set_rtc_time)
722                 return -ENODEV;
723
724         to_tm(now.tv_sec + 1 + timezone_offset, &tm);
725         tm.tm_year -= 1900;
726         tm.tm_mon -= 1;
727
728         return ppc_md.set_rtc_time(&tm);
729 }
730
731 static void __read_persistent_clock(struct timespec *ts)
732 {
733         struct rtc_time tm;
734         static int first = 1;
735
736         ts->tv_nsec = 0;
737         /* XXX this is a litle fragile but will work okay in the short term */
738         if (first) {
739                 first = 0;
740                 if (ppc_md.time_init)
741                         timezone_offset = ppc_md.time_init();
742
743                 /* get_boot_time() isn't guaranteed to be safe to call late */
744                 if (ppc_md.get_boot_time) {
745                         ts->tv_sec = ppc_md.get_boot_time() - timezone_offset;
746                         return;
747                 }
748         }
749         if (!ppc_md.get_rtc_time) {
750                 ts->tv_sec = 0;
751                 return;
752         }
753         ppc_md.get_rtc_time(&tm);
754
755         ts->tv_sec = mktime(tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday,
756                             tm.tm_hour, tm.tm_min, tm.tm_sec);
757 }
758
759 void read_persistent_clock(struct timespec *ts)
760 {
761         __read_persistent_clock(ts);
762
763         /* Sanitize it in case real time clock is set below EPOCH */
764         if (ts->tv_sec < 0) {
765                 ts->tv_sec = 0;
766                 ts->tv_nsec = 0;
767         }
768                 
769 }
770
771 /* clocksource code */
772 static cycle_t rtc_read(struct clocksource *cs)
773 {
774         return (cycle_t)get_rtc();
775 }
776
777 static cycle_t timebase_read(struct clocksource *cs)
778 {
779         return (cycle_t)get_tb();
780 }
781
782 void update_vsyscall_old(struct timespec *wall_time, struct timespec *wtm,
783                          struct clocksource *clock, u32 mult, cycle_t cycle_last)
784 {
785         u64 new_tb_to_xs, new_stamp_xsec;
786         u32 frac_sec;
787
788         if (clock != &clocksource_timebase)
789                 return;
790
791         /* Make userspace gettimeofday spin until we're done. */
792         ++vdso_data->tb_update_count;
793         smp_mb();
794
795         /* 19342813113834067 ~= 2^(20+64) / 1e9 */
796         new_tb_to_xs = (u64) mult * (19342813113834067ULL >> clock->shift);
797         new_stamp_xsec = (u64) wall_time->tv_nsec * XSEC_PER_SEC;
798         do_div(new_stamp_xsec, 1000000000);
799         new_stamp_xsec += (u64) wall_time->tv_sec * XSEC_PER_SEC;
800
801         BUG_ON(wall_time->tv_nsec >= NSEC_PER_SEC);
802         /* this is tv_nsec / 1e9 as a 0.32 fraction */
803         frac_sec = ((u64) wall_time->tv_nsec * 18446744073ULL) >> 32;
804
805         /*
806          * tb_update_count is used to allow the userspace gettimeofday code
807          * to assure itself that it sees a consistent view of the tb_to_xs and
808          * stamp_xsec variables.  It reads the tb_update_count, then reads
809          * tb_to_xs and stamp_xsec and then reads tb_update_count again.  If
810          * the two values of tb_update_count match and are even then the
811          * tb_to_xs and stamp_xsec values are consistent.  If not, then it
812          * loops back and reads them again until this criteria is met.
813          * We expect the caller to have done the first increment of
814          * vdso_data->tb_update_count already.
815          */
816         vdso_data->tb_orig_stamp = cycle_last;
817         vdso_data->stamp_xsec = new_stamp_xsec;
818         vdso_data->tb_to_xs = new_tb_to_xs;
819         vdso_data->wtom_clock_sec = wtm->tv_sec;
820         vdso_data->wtom_clock_nsec = wtm->tv_nsec;
821         vdso_data->stamp_xtime = *wall_time;
822         vdso_data->stamp_sec_fraction = frac_sec;
823         smp_wmb();
824         ++(vdso_data->tb_update_count);
825 }
826
827 void update_vsyscall_tz(void)
828 {
829         vdso_data->tz_minuteswest = sys_tz.tz_minuteswest;
830         vdso_data->tz_dsttime = sys_tz.tz_dsttime;
831 }
832
833 static void __init clocksource_init(void)
834 {
835         struct clocksource *clock;
836
837         if (__USE_RTC())
838                 clock = &clocksource_rtc;
839         else
840                 clock = &clocksource_timebase;
841
842         if (clocksource_register_hz(clock, tb_ticks_per_sec)) {
843                 printk(KERN_ERR "clocksource: %s is already registered\n",
844                        clock->name);
845                 return;
846         }
847
848         printk(KERN_INFO "clocksource: %s mult[%x] shift[%d] registered\n",
849                clock->name, clock->mult, clock->shift);
850 }
851
852 static int decrementer_set_next_event(unsigned long evt,
853                                       struct clock_event_device *dev)
854 {
855         __this_cpu_write(decrementers_next_tb, get_tb_or_rtc() + evt);
856         set_dec(evt);
857
858         /* We may have raced with new irq work */
859         if (test_irq_work_pending())
860                 set_dec(1);
861
862         return 0;
863 }
864
865 static void decrementer_set_mode(enum clock_event_mode mode,
866                                  struct clock_event_device *dev)
867 {
868         if (mode != CLOCK_EVT_MODE_ONESHOT)
869                 decrementer_set_next_event(DECREMENTER_MAX, dev);
870 }
871
872 /* Interrupt handler for the timer broadcast IPI */
873 void tick_broadcast_ipi_handler(void)
874 {
875         u64 *next_tb = this_cpu_ptr(&decrementers_next_tb);
876
877         *next_tb = get_tb_or_rtc();
878         __timer_interrupt();
879 }
880
881 static void register_decrementer_clockevent(int cpu)
882 {
883         struct clock_event_device *dec = &per_cpu(decrementers, cpu);
884
885         *dec = decrementer_clockevent;
886         dec->cpumask = cpumask_of(cpu);
887
888         printk_once(KERN_DEBUG "clockevent: %s mult[%x] shift[%d] cpu[%d]\n",
889                     dec->name, dec->mult, dec->shift, cpu);
890
891         clockevents_register_device(dec);
892 }
893
894 static void __init init_decrementer_clockevent(void)
895 {
896         int cpu = smp_processor_id();
897
898         clockevents_calc_mult_shift(&decrementer_clockevent, ppc_tb_freq, 4);
899
900         decrementer_clockevent.max_delta_ns =
901                 clockevent_delta2ns(DECREMENTER_MAX, &decrementer_clockevent);
902         decrementer_clockevent.min_delta_ns =
903                 clockevent_delta2ns(2, &decrementer_clockevent);
904
905         register_decrementer_clockevent(cpu);
906 }
907
908 void secondary_cpu_time_init(void)
909 {
910         /* Start the decrementer on CPUs that have manual control
911          * such as BookE
912          */
913         start_cpu_decrementer();
914
915         /* FIME: Should make unrelatred change to move snapshot_timebase
916          * call here ! */
917         register_decrementer_clockevent(smp_processor_id());
918 }
919
920 /* This function is only called on the boot processor */
921 void __init time_init(void)
922 {
923         struct div_result res;
924         u64 scale;
925         unsigned shift;
926
927         if (__USE_RTC()) {
928                 /* 601 processor: dec counts down by 128 every 128ns */
929                 ppc_tb_freq = 1000000000;
930         } else {
931                 /* Normal PowerPC with timebase register */
932                 ppc_md.calibrate_decr();
933                 printk(KERN_DEBUG "time_init: decrementer frequency = %lu.%.6lu MHz\n",
934                        ppc_tb_freq / 1000000, ppc_tb_freq % 1000000);
935                 printk(KERN_DEBUG "time_init: processor frequency   = %lu.%.6lu MHz\n",
936                        ppc_proc_freq / 1000000, ppc_proc_freq % 1000000);
937         }
938
939         tb_ticks_per_jiffy = ppc_tb_freq / HZ;
940         tb_ticks_per_sec = ppc_tb_freq;
941         tb_ticks_per_usec = ppc_tb_freq / 1000000;
942         calc_cputime_factors();
943         setup_cputime_one_jiffy();
944
945         /*
946          * Compute scale factor for sched_clock.
947          * The calibrate_decr() function has set tb_ticks_per_sec,
948          * which is the timebase frequency.
949          * We compute 1e9 * 2^64 / tb_ticks_per_sec and interpret
950          * the 128-bit result as a 64.64 fixed-point number.
951          * We then shift that number right until it is less than 1.0,
952          * giving us the scale factor and shift count to use in
953          * sched_clock().
954          */
955         div128_by_32(1000000000, 0, tb_ticks_per_sec, &res);
956         scale = res.result_low;
957         for (shift = 0; res.result_high != 0; ++shift) {
958                 scale = (scale >> 1) | (res.result_high << 63);
959                 res.result_high >>= 1;
960         }
961         tb_to_ns_scale = scale;
962         tb_to_ns_shift = shift;
963         /* Save the current timebase to pretty up CONFIG_PRINTK_TIME */
964         boot_tb = get_tb_or_rtc();
965
966         /* If platform provided a timezone (pmac), we correct the time */
967         if (timezone_offset) {
968                 sys_tz.tz_minuteswest = -timezone_offset / 60;
969                 sys_tz.tz_dsttime = 0;
970         }
971
972         vdso_data->tb_update_count = 0;
973         vdso_data->tb_ticks_per_sec = tb_ticks_per_sec;
974
975         /* Start the decrementer on CPUs that have manual control
976          * such as BookE
977          */
978         start_cpu_decrementer();
979
980         /* Register the clocksource */
981         clocksource_init();
982
983         init_decrementer_clockevent();
984         tick_setup_hrtimer_broadcast();
985
986 #ifdef CONFIG_COMMON_CLK
987         of_clk_init(NULL);
988 #endif
989 }
990
991
992 #define FEBRUARY        2
993 #define STARTOFTIME     1970
994 #define SECDAY          86400L
995 #define SECYR           (SECDAY * 365)
996 #define leapyear(year)          ((year) % 4 == 0 && \
997                                  ((year) % 100 != 0 || (year) % 400 == 0))
998 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
999 #define days_in_month(a)        (month_days[(a) - 1])
1000
1001 static int month_days[12] = {
1002         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
1003 };
1004
1005 /*
1006  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
1007  */
1008 void GregorianDay(struct rtc_time * tm)
1009 {
1010         int leapsToDate;
1011         int lastYear;
1012         int day;
1013         int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
1014
1015         lastYear = tm->tm_year - 1;
1016
1017         /*
1018          * Number of leap corrections to apply up to end of last year
1019          */
1020         leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
1021
1022         /*
1023          * This year is a leap year if it is divisible by 4 except when it is
1024          * divisible by 100 unless it is divisible by 400
1025          *
1026          * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
1027          */
1028         day = tm->tm_mon > 2 && leapyear(tm->tm_year);
1029
1030         day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
1031                    tm->tm_mday;
1032
1033         tm->tm_wday = day % 7;
1034 }
1035 EXPORT_SYMBOL_GPL(GregorianDay);
1036
1037 void to_tm(int tim, struct rtc_time * tm)
1038 {
1039         register int    i;
1040         register long   hms, day;
1041
1042         day = tim / SECDAY;
1043         hms = tim % SECDAY;
1044
1045         /* Hours, minutes, seconds are easy */
1046         tm->tm_hour = hms / 3600;
1047         tm->tm_min = (hms % 3600) / 60;
1048         tm->tm_sec = (hms % 3600) % 60;
1049
1050         /* Number of years in days */
1051         for (i = STARTOFTIME; day >= days_in_year(i); i++)
1052                 day -= days_in_year(i);
1053         tm->tm_year = i;
1054
1055         /* Number of months in days left */
1056         if (leapyear(tm->tm_year))
1057                 days_in_month(FEBRUARY) = 29;
1058         for (i = 1; day >= days_in_month(i); i++)
1059                 day -= days_in_month(i);
1060         days_in_month(FEBRUARY) = 28;
1061         tm->tm_mon = i;
1062
1063         /* Days are what is left over (+1) from all that. */
1064         tm->tm_mday = day + 1;
1065
1066         /*
1067          * Determine the day of week
1068          */
1069         GregorianDay(tm);
1070 }
1071 EXPORT_SYMBOL(to_tm);
1072
1073 /*
1074  * Divide a 128-bit dividend by a 32-bit divisor, leaving a 128 bit
1075  * result.
1076  */
1077 void div128_by_32(u64 dividend_high, u64 dividend_low,
1078                   unsigned divisor, struct div_result *dr)
1079 {
1080         unsigned long a, b, c, d;
1081         unsigned long w, x, y, z;
1082         u64 ra, rb, rc;
1083
1084         a = dividend_high >> 32;
1085         b = dividend_high & 0xffffffff;
1086         c = dividend_low >> 32;
1087         d = dividend_low & 0xffffffff;
1088
1089         w = a / divisor;
1090         ra = ((u64)(a - (w * divisor)) << 32) + b;
1091
1092         rb = ((u64) do_div(ra, divisor) << 32) + c;
1093         x = ra;
1094
1095         rc = ((u64) do_div(rb, divisor) << 32) + d;
1096         y = rb;
1097
1098         do_div(rc, divisor);
1099         z = rc;
1100
1101         dr->result_high = ((u64)w << 32) + x;
1102         dr->result_low  = ((u64)y << 32) + z;
1103
1104 }
1105
1106 /* We don't need to calibrate delay, we use the CPU timebase for that */
1107 void calibrate_delay(void)
1108 {
1109         /* Some generic code (such as spinlock debug) use loops_per_jiffy
1110          * as the number of __delay(1) in a jiffy, so make it so
1111          */
1112         loops_per_jiffy = tb_ticks_per_jiffy;
1113 }
1114
1115 static int __init rtc_init(void)
1116 {
1117         struct platform_device *pdev;
1118
1119         if (!ppc_md.get_rtc_time)
1120                 return -ENODEV;
1121
1122         pdev = platform_device_register_simple("rtc-generic", -1, NULL, 0);
1123
1124         return PTR_ERR_OR_ZERO(pdev);
1125 }
1126
1127 module_init(rtc_init);