Merge branch 'devel' of master.kernel.org:/home/rmk/linux-2.6-mmc
[pandora-kernel.git] / arch / sparc64 / kernel / time.c
1 /* $Id: time.c,v 1.42 2002/01/23 14:33:55 davem Exp $
2  * time.c: UltraSparc timer and TOD clock support.
3  *
4  * Copyright (C) 1997 David S. Miller (davem@caip.rutgers.edu)
5  * Copyright (C) 1998 Eddie C. Dost   (ecd@skynet.be)
6  *
7  * Based largely on code which is:
8  *
9  * Copyright (C) 1996 Thomas K. Dyas (tdyas@eden.rutgers.edu)
10  */
11
12 #include <linux/config.h>
13 #include <linux/errno.h>
14 #include <linux/module.h>
15 #include <linux/sched.h>
16 #include <linux/kernel.h>
17 #include <linux/param.h>
18 #include <linux/string.h>
19 #include <linux/mm.h>
20 #include <linux/interrupt.h>
21 #include <linux/time.h>
22 #include <linux/timex.h>
23 #include <linux/init.h>
24 #include <linux/ioport.h>
25 #include <linux/mc146818rtc.h>
26 #include <linux/delay.h>
27 #include <linux/profile.h>
28 #include <linux/bcd.h>
29 #include <linux/jiffies.h>
30 #include <linux/cpufreq.h>
31 #include <linux/percpu.h>
32 #include <linux/profile.h>
33 #include <linux/miscdevice.h>
34 #include <linux/rtc.h>
35
36 #include <asm/oplib.h>
37 #include <asm/mostek.h>
38 #include <asm/timer.h>
39 #include <asm/irq.h>
40 #include <asm/io.h>
41 #include <asm/sbus.h>
42 #include <asm/fhc.h>
43 #include <asm/pbm.h>
44 #include <asm/ebus.h>
45 #include <asm/isa.h>
46 #include <asm/starfire.h>
47 #include <asm/smp.h>
48 #include <asm/sections.h>
49 #include <asm/cpudata.h>
50 #include <asm/uaccess.h>
51
52 DEFINE_SPINLOCK(mostek_lock);
53 DEFINE_SPINLOCK(rtc_lock);
54 void __iomem *mstk48t02_regs = NULL;
55 #ifdef CONFIG_PCI
56 unsigned long ds1287_regs = 0UL;
57 #endif
58
59 extern unsigned long wall_jiffies;
60
61 static void __iomem *mstk48t08_regs;
62 static void __iomem *mstk48t59_regs;
63
64 static int set_rtc_mmss(unsigned long);
65
66 #define TICK_PRIV_BIT   (1UL << 63)
67
68 #ifdef CONFIG_SMP
69 unsigned long profile_pc(struct pt_regs *regs)
70 {
71         unsigned long pc = instruction_pointer(regs);
72
73         if (in_lock_functions(pc))
74                 return regs->u_regs[UREG_RETPC];
75         return pc;
76 }
77 EXPORT_SYMBOL(profile_pc);
78 #endif
79
80 static void tick_disable_protection(void)
81 {
82         /* Set things up so user can access tick register for profiling
83          * purposes.  Also workaround BB_ERRATA_1 by doing a dummy
84          * read back of %tick after writing it.
85          */
86         __asm__ __volatile__(
87         "       ba,pt   %%xcc, 1f\n"
88         "        nop\n"
89         "       .align  64\n"
90         "1:     rd      %%tick, %%g2\n"
91         "       add     %%g2, 6, %%g2\n"
92         "       andn    %%g2, %0, %%g2\n"
93         "       wrpr    %%g2, 0, %%tick\n"
94         "       rdpr    %%tick, %%g0"
95         : /* no outputs */
96         : "r" (TICK_PRIV_BIT)
97         : "g2");
98 }
99
100 static void tick_init_tick(unsigned long offset)
101 {
102         tick_disable_protection();
103
104         __asm__ __volatile__(
105         "       rd      %%tick, %%g1\n"
106         "       andn    %%g1, %1, %%g1\n"
107         "       ba,pt   %%xcc, 1f\n"
108         "        add    %%g1, %0, %%g1\n"
109         "       .align  64\n"
110         "1:     wr      %%g1, 0x0, %%tick_cmpr\n"
111         "       rd      %%tick_cmpr, %%g0"
112         : /* no outputs */
113         : "r" (offset), "r" (TICK_PRIV_BIT)
114         : "g1");
115 }
116
117 static unsigned long tick_get_tick(void)
118 {
119         unsigned long ret;
120
121         __asm__ __volatile__("rd        %%tick, %0\n\t"
122                              "mov       %0, %0"
123                              : "=r" (ret));
124
125         return ret & ~TICK_PRIV_BIT;
126 }
127
128 static unsigned long tick_get_compare(void)
129 {
130         unsigned long ret;
131
132         __asm__ __volatile__("rd        %%tick_cmpr, %0\n\t"
133                              "mov       %0, %0"
134                              : "=r" (ret));
135
136         return ret;
137 }
138
139 static unsigned long tick_add_compare(unsigned long adj)
140 {
141         unsigned long new_compare;
142
143         /* Workaround for Spitfire Errata (#54 I think??), I discovered
144          * this via Sun BugID 4008234, mentioned in Solaris-2.5.1 patch
145          * number 103640.
146          *
147          * On Blackbird writes to %tick_cmpr can fail, the
148          * workaround seems to be to execute the wr instruction
149          * at the start of an I-cache line, and perform a dummy
150          * read back from %tick_cmpr right after writing to it. -DaveM
151          */
152         __asm__ __volatile__("rd        %%tick_cmpr, %0\n\t"
153                              "ba,pt     %%xcc, 1f\n\t"
154                              " add      %0, %1, %0\n\t"
155                              ".align    64\n"
156                              "1:\n\t"
157                              "wr        %0, 0, %%tick_cmpr\n\t"
158                              "rd        %%tick_cmpr, %%g0"
159                              : "=&r" (new_compare)
160                              : "r" (adj));
161
162         return new_compare;
163 }
164
165 static unsigned long tick_add_tick(unsigned long adj, unsigned long offset)
166 {
167         unsigned long new_tick, tmp;
168
169         /* Also need to handle Blackbird bug here too. */
170         __asm__ __volatile__("rd        %%tick, %0\n\t"
171                              "add       %0, %2, %0\n\t"
172                              "wrpr      %0, 0, %%tick\n\t"
173                              "andn      %0, %4, %1\n\t"
174                              "ba,pt     %%xcc, 1f\n\t"
175                              " add      %1, %3, %1\n\t"
176                              ".align    64\n"
177                              "1:\n\t"
178                              "wr        %1, 0, %%tick_cmpr\n\t"
179                              "rd        %%tick_cmpr, %%g0"
180                              : "=&r" (new_tick), "=&r" (tmp)
181                              : "r" (adj), "r" (offset), "r" (TICK_PRIV_BIT));
182
183         return new_tick;
184 }
185
186 static struct sparc64_tick_ops tick_operations __read_mostly = {
187         .init_tick      =       tick_init_tick,
188         .get_tick       =       tick_get_tick,
189         .get_compare    =       tick_get_compare,
190         .add_tick       =       tick_add_tick,
191         .add_compare    =       tick_add_compare,
192         .softint_mask   =       1UL << 0,
193 };
194
195 struct sparc64_tick_ops *tick_ops __read_mostly = &tick_operations;
196
197 static void stick_init_tick(unsigned long offset)
198 {
199         /* Writes to the %tick and %stick register are not
200          * allowed on sun4v.  The Hypervisor controls that
201          * bit, per-strand.
202          */
203         if (tlb_type != hypervisor) {
204                 tick_disable_protection();
205
206                 /* Let the user get at STICK too. */
207                 __asm__ __volatile__(
208                 "       rd      %%asr24, %%g2\n"
209                 "       andn    %%g2, %0, %%g2\n"
210                 "       wr      %%g2, 0, %%asr24"
211                 : /* no outputs */
212                 : "r" (TICK_PRIV_BIT)
213                 : "g1", "g2");
214         }
215
216         __asm__ __volatile__(
217         "       rd      %%asr24, %%g1\n"
218         "       andn    %%g1, %1, %%g1\n"
219         "       add     %%g1, %0, %%g1\n"
220         "       wr      %%g1, 0x0, %%asr25"
221         : /* no outputs */
222         : "r" (offset), "r" (TICK_PRIV_BIT)
223         : "g1");
224 }
225
226 static unsigned long stick_get_tick(void)
227 {
228         unsigned long ret;
229
230         __asm__ __volatile__("rd        %%asr24, %0"
231                              : "=r" (ret));
232
233         return ret & ~TICK_PRIV_BIT;
234 }
235
236 static unsigned long stick_get_compare(void)
237 {
238         unsigned long ret;
239
240         __asm__ __volatile__("rd        %%asr25, %0"
241                              : "=r" (ret));
242
243         return ret;
244 }
245
246 static unsigned long stick_add_tick(unsigned long adj, unsigned long offset)
247 {
248         unsigned long new_tick, tmp;
249
250         __asm__ __volatile__("rd        %%asr24, %0\n\t"
251                              "add       %0, %2, %0\n\t"
252                              "wr        %0, 0, %%asr24\n\t"
253                              "andn      %0, %4, %1\n\t"
254                              "add       %1, %3, %1\n\t"
255                              "wr        %1, 0, %%asr25"
256                              : "=&r" (new_tick), "=&r" (tmp)
257                              : "r" (adj), "r" (offset), "r" (TICK_PRIV_BIT));
258
259         return new_tick;
260 }
261
262 static unsigned long stick_add_compare(unsigned long adj)
263 {
264         unsigned long new_compare;
265
266         __asm__ __volatile__("rd        %%asr25, %0\n\t"
267                              "add       %0, %1, %0\n\t"
268                              "wr        %0, 0, %%asr25"
269                              : "=&r" (new_compare)
270                              : "r" (adj));
271
272         return new_compare;
273 }
274
275 static struct sparc64_tick_ops stick_operations __read_mostly = {
276         .init_tick      =       stick_init_tick,
277         .get_tick       =       stick_get_tick,
278         .get_compare    =       stick_get_compare,
279         .add_tick       =       stick_add_tick,
280         .add_compare    =       stick_add_compare,
281         .softint_mask   =       1UL << 16,
282 };
283
284 /* On Hummingbird the STICK/STICK_CMPR register is implemented
285  * in I/O space.  There are two 64-bit registers each, the
286  * first holds the low 32-bits of the value and the second holds
287  * the high 32-bits.
288  *
289  * Since STICK is constantly updating, we have to access it carefully.
290  *
291  * The sequence we use to read is:
292  * 1) read high
293  * 2) read low
294  * 3) read high again, if it rolled re-read both low and high again.
295  *
296  * Writing STICK safely is also tricky:
297  * 1) write low to zero
298  * 2) write high
299  * 3) write low
300  */
301 #define HBIRD_STICKCMP_ADDR     0x1fe0000f060UL
302 #define HBIRD_STICK_ADDR        0x1fe0000f070UL
303
304 static unsigned long __hbird_read_stick(void)
305 {
306         unsigned long ret, tmp1, tmp2, tmp3;
307         unsigned long addr = HBIRD_STICK_ADDR+8;
308
309         __asm__ __volatile__("ldxa      [%1] %5, %2\n"
310                              "1:\n\t"
311                              "sub       %1, 0x8, %1\n\t"
312                              "ldxa      [%1] %5, %3\n\t"
313                              "add       %1, 0x8, %1\n\t"
314                              "ldxa      [%1] %5, %4\n\t"
315                              "cmp       %4, %2\n\t"
316                              "bne,a,pn  %%xcc, 1b\n\t"
317                              " mov      %4, %2\n\t"
318                              "sllx      %4, 32, %4\n\t"
319                              "or        %3, %4, %0\n\t"
320                              : "=&r" (ret), "=&r" (addr),
321                                "=&r" (tmp1), "=&r" (tmp2), "=&r" (tmp3)
322                              : "i" (ASI_PHYS_BYPASS_EC_E), "1" (addr));
323
324         return ret;
325 }
326
327 static unsigned long __hbird_read_compare(void)
328 {
329         unsigned long low, high;
330         unsigned long addr = HBIRD_STICKCMP_ADDR;
331
332         __asm__ __volatile__("ldxa      [%2] %3, %0\n\t"
333                              "add       %2, 0x8, %2\n\t"
334                              "ldxa      [%2] %3, %1"
335                              : "=&r" (low), "=&r" (high), "=&r" (addr)
336                              : "i" (ASI_PHYS_BYPASS_EC_E), "2" (addr));
337
338         return (high << 32UL) | low;
339 }
340
341 static void __hbird_write_stick(unsigned long val)
342 {
343         unsigned long low = (val & 0xffffffffUL);
344         unsigned long high = (val >> 32UL);
345         unsigned long addr = HBIRD_STICK_ADDR;
346
347         __asm__ __volatile__("stxa      %%g0, [%0] %4\n\t"
348                              "add       %0, 0x8, %0\n\t"
349                              "stxa      %3, [%0] %4\n\t"
350                              "sub       %0, 0x8, %0\n\t"
351                              "stxa      %2, [%0] %4"
352                              : "=&r" (addr)
353                              : "0" (addr), "r" (low), "r" (high),
354                                "i" (ASI_PHYS_BYPASS_EC_E));
355 }
356
357 static void __hbird_write_compare(unsigned long val)
358 {
359         unsigned long low = (val & 0xffffffffUL);
360         unsigned long high = (val >> 32UL);
361         unsigned long addr = HBIRD_STICKCMP_ADDR + 0x8UL;
362
363         __asm__ __volatile__("stxa      %3, [%0] %4\n\t"
364                              "sub       %0, 0x8, %0\n\t"
365                              "stxa      %2, [%0] %4"
366                              : "=&r" (addr)
367                              : "0" (addr), "r" (low), "r" (high),
368                                "i" (ASI_PHYS_BYPASS_EC_E));
369 }
370
371 static void hbtick_init_tick(unsigned long offset)
372 {
373         unsigned long val;
374
375         tick_disable_protection();
376
377         /* XXX This seems to be necessary to 'jumpstart' Hummingbird
378          * XXX into actually sending STICK interrupts.  I think because
379          * XXX of how we store %tick_cmpr in head.S this somehow resets the
380          * XXX {TICK + STICK} interrupt mux.  -DaveM
381          */
382         __hbird_write_stick(__hbird_read_stick());
383
384         val = __hbird_read_stick() & ~TICK_PRIV_BIT;
385         __hbird_write_compare(val + offset);
386 }
387
388 static unsigned long hbtick_get_tick(void)
389 {
390         return __hbird_read_stick() & ~TICK_PRIV_BIT;
391 }
392
393 static unsigned long hbtick_get_compare(void)
394 {
395         return __hbird_read_compare();
396 }
397
398 static unsigned long hbtick_add_tick(unsigned long adj, unsigned long offset)
399 {
400         unsigned long val;
401
402         val = __hbird_read_stick() + adj;
403         __hbird_write_stick(val);
404
405         val &= ~TICK_PRIV_BIT;
406         __hbird_write_compare(val + offset);
407
408         return val;
409 }
410
411 static unsigned long hbtick_add_compare(unsigned long adj)
412 {
413         unsigned long val = __hbird_read_compare() + adj;
414
415         val &= ~TICK_PRIV_BIT;
416         __hbird_write_compare(val);
417
418         return val;
419 }
420
421 static struct sparc64_tick_ops hbtick_operations __read_mostly = {
422         .init_tick      =       hbtick_init_tick,
423         .get_tick       =       hbtick_get_tick,
424         .get_compare    =       hbtick_get_compare,
425         .add_tick       =       hbtick_add_tick,
426         .add_compare    =       hbtick_add_compare,
427         .softint_mask   =       1UL << 0,
428 };
429
430 /* timer_interrupt() needs to keep up the real-time clock,
431  * as well as call the "do_timer()" routine every clocktick
432  *
433  * NOTE: On SUN5 systems the ticker interrupt comes in using 2
434  *       interrupts, one at level14 and one with softint bit 0.
435  */
436 unsigned long timer_tick_offset __read_mostly;
437
438 static unsigned long timer_ticks_per_nsec_quotient __read_mostly;
439
440 #define TICK_SIZE (tick_nsec / 1000)
441
442 static inline void timer_check_rtc(void)
443 {
444         /* last time the cmos clock got updated */
445         static long last_rtc_update;
446
447         /* Determine when to update the Mostek clock. */
448         if (ntp_synced() &&
449             xtime.tv_sec > last_rtc_update + 660 &&
450             (xtime.tv_nsec / 1000) >= 500000 - ((unsigned) TICK_SIZE) / 2 &&
451             (xtime.tv_nsec / 1000) <= 500000 + ((unsigned) TICK_SIZE) / 2) {
452                 if (set_rtc_mmss(xtime.tv_sec) == 0)
453                         last_rtc_update = xtime.tv_sec;
454                 else
455                         last_rtc_update = xtime.tv_sec - 600;
456                         /* do it again in 60 s */
457         }
458 }
459
460 irqreturn_t timer_interrupt(int irq, void *dev_id, struct pt_regs * regs)
461 {
462         unsigned long ticks, compare, pstate;
463
464         write_seqlock(&xtime_lock);
465
466         do {
467 #ifndef CONFIG_SMP
468                 profile_tick(CPU_PROFILING, regs);
469                 update_process_times(user_mode(regs));
470 #endif
471                 do_timer(regs);
472
473                 /* Guarantee that the following sequences execute
474                  * uninterrupted.
475                  */
476                 __asm__ __volatile__("rdpr      %%pstate, %0\n\t"
477                                      "wrpr      %0, %1, %%pstate"
478                                      : "=r" (pstate)
479                                      : "i" (PSTATE_IE));
480
481                 compare = tick_ops->add_compare(timer_tick_offset);
482                 ticks = tick_ops->get_tick();
483
484                 /* Restore PSTATE_IE. */
485                 __asm__ __volatile__("wrpr      %0, 0x0, %%pstate"
486                                      : /* no outputs */
487                                      : "r" (pstate));
488         } while (time_after_eq(ticks, compare));
489
490         timer_check_rtc();
491
492         write_sequnlock(&xtime_lock);
493
494         return IRQ_HANDLED;
495 }
496
497 #ifdef CONFIG_SMP
498 void timer_tick_interrupt(struct pt_regs *regs)
499 {
500         write_seqlock(&xtime_lock);
501
502         do_timer(regs);
503
504         timer_check_rtc();
505
506         write_sequnlock(&xtime_lock);
507 }
508 #endif
509
510 /* Kick start a stopped clock (procedure from the Sun NVRAM/hostid FAQ). */
511 static void __init kick_start_clock(void)
512 {
513         void __iomem *regs = mstk48t02_regs;
514         u8 sec, tmp;
515         int i, count;
516
517         prom_printf("CLOCK: Clock was stopped. Kick start ");
518
519         spin_lock_irq(&mostek_lock);
520
521         /* Turn on the kick start bit to start the oscillator. */
522         tmp = mostek_read(regs + MOSTEK_CREG);
523         tmp |= MSTK_CREG_WRITE;
524         mostek_write(regs + MOSTEK_CREG, tmp);
525         tmp = mostek_read(regs + MOSTEK_SEC);
526         tmp &= ~MSTK_STOP;
527         mostek_write(regs + MOSTEK_SEC, tmp);
528         tmp = mostek_read(regs + MOSTEK_HOUR);
529         tmp |= MSTK_KICK_START;
530         mostek_write(regs + MOSTEK_HOUR, tmp);
531         tmp = mostek_read(regs + MOSTEK_CREG);
532         tmp &= ~MSTK_CREG_WRITE;
533         mostek_write(regs + MOSTEK_CREG, tmp);
534
535         spin_unlock_irq(&mostek_lock);
536
537         /* Delay to allow the clock oscillator to start. */
538         sec = MSTK_REG_SEC(regs);
539         for (i = 0; i < 3; i++) {
540                 while (sec == MSTK_REG_SEC(regs))
541                         for (count = 0; count < 100000; count++)
542                                 /* nothing */ ;
543                 prom_printf(".");
544                 sec = MSTK_REG_SEC(regs);
545         }
546         prom_printf("\n");
547
548         spin_lock_irq(&mostek_lock);
549
550         /* Turn off kick start and set a "valid" time and date. */
551         tmp = mostek_read(regs + MOSTEK_CREG);
552         tmp |= MSTK_CREG_WRITE;
553         mostek_write(regs + MOSTEK_CREG, tmp);
554         tmp = mostek_read(regs + MOSTEK_HOUR);
555         tmp &= ~MSTK_KICK_START;
556         mostek_write(regs + MOSTEK_HOUR, tmp);
557         MSTK_SET_REG_SEC(regs,0);
558         MSTK_SET_REG_MIN(regs,0);
559         MSTK_SET_REG_HOUR(regs,0);
560         MSTK_SET_REG_DOW(regs,5);
561         MSTK_SET_REG_DOM(regs,1);
562         MSTK_SET_REG_MONTH(regs,8);
563         MSTK_SET_REG_YEAR(regs,1996 - MSTK_YEAR_ZERO);
564         tmp = mostek_read(regs + MOSTEK_CREG);
565         tmp &= ~MSTK_CREG_WRITE;
566         mostek_write(regs + MOSTEK_CREG, tmp);
567
568         spin_unlock_irq(&mostek_lock);
569
570         /* Ensure the kick start bit is off. If it isn't, turn it off. */
571         while (mostek_read(regs + MOSTEK_HOUR) & MSTK_KICK_START) {
572                 prom_printf("CLOCK: Kick start still on!\n");
573
574                 spin_lock_irq(&mostek_lock);
575
576                 tmp = mostek_read(regs + MOSTEK_CREG);
577                 tmp |= MSTK_CREG_WRITE;
578                 mostek_write(regs + MOSTEK_CREG, tmp);
579
580                 tmp = mostek_read(regs + MOSTEK_HOUR);
581                 tmp &= ~MSTK_KICK_START;
582                 mostek_write(regs + MOSTEK_HOUR, tmp);
583
584                 tmp = mostek_read(regs + MOSTEK_CREG);
585                 tmp &= ~MSTK_CREG_WRITE;
586                 mostek_write(regs + MOSTEK_CREG, tmp);
587
588                 spin_unlock_irq(&mostek_lock);
589         }
590
591         prom_printf("CLOCK: Kick start procedure successful.\n");
592 }
593
594 /* Return nonzero if the clock chip battery is low. */
595 static int __init has_low_battery(void)
596 {
597         void __iomem *regs = mstk48t02_regs;
598         u8 data1, data2;
599
600         spin_lock_irq(&mostek_lock);
601
602         data1 = mostek_read(regs + MOSTEK_EEPROM);      /* Read some data. */
603         mostek_write(regs + MOSTEK_EEPROM, ~data1);     /* Write back the complement. */
604         data2 = mostek_read(regs + MOSTEK_EEPROM);      /* Read back the complement. */
605         mostek_write(regs + MOSTEK_EEPROM, data1);      /* Restore original value. */
606
607         spin_unlock_irq(&mostek_lock);
608
609         return (data1 == data2);        /* Was the write blocked? */
610 }
611
612 /* Probe for the real time clock chip. */
613 static void __init set_system_time(void)
614 {
615         unsigned int year, mon, day, hour, min, sec;
616         void __iomem *mregs = mstk48t02_regs;
617 #ifdef CONFIG_PCI
618         unsigned long dregs = ds1287_regs;
619 #else
620         unsigned long dregs = 0UL;
621 #endif
622         u8 tmp;
623
624         if (!mregs && !dregs) {
625                 prom_printf("Something wrong, clock regs not mapped yet.\n");
626                 prom_halt();
627         }               
628
629         if (mregs) {
630                 spin_lock_irq(&mostek_lock);
631
632                 /* Traditional Mostek chip. */
633                 tmp = mostek_read(mregs + MOSTEK_CREG);
634                 tmp |= MSTK_CREG_READ;
635                 mostek_write(mregs + MOSTEK_CREG, tmp);
636
637                 sec = MSTK_REG_SEC(mregs);
638                 min = MSTK_REG_MIN(mregs);
639                 hour = MSTK_REG_HOUR(mregs);
640                 day = MSTK_REG_DOM(mregs);
641                 mon = MSTK_REG_MONTH(mregs);
642                 year = MSTK_CVT_YEAR( MSTK_REG_YEAR(mregs) );
643         } else {
644                 /* Dallas 12887 RTC chip. */
645
646                 do {
647                         sec  = CMOS_READ(RTC_SECONDS);
648                         min  = CMOS_READ(RTC_MINUTES);
649                         hour = CMOS_READ(RTC_HOURS);
650                         day  = CMOS_READ(RTC_DAY_OF_MONTH);
651                         mon  = CMOS_READ(RTC_MONTH);
652                         year = CMOS_READ(RTC_YEAR);
653                 } while (sec != CMOS_READ(RTC_SECONDS));
654
655                 if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
656                         BCD_TO_BIN(sec);
657                         BCD_TO_BIN(min);
658                         BCD_TO_BIN(hour);
659                         BCD_TO_BIN(day);
660                         BCD_TO_BIN(mon);
661                         BCD_TO_BIN(year);
662                 }
663                 if ((year += 1900) < 1970)
664                         year += 100;
665         }
666
667         xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
668         xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
669         set_normalized_timespec(&wall_to_monotonic,
670                                 -xtime.tv_sec, -xtime.tv_nsec);
671
672         if (mregs) {
673                 tmp = mostek_read(mregs + MOSTEK_CREG);
674                 tmp &= ~MSTK_CREG_READ;
675                 mostek_write(mregs + MOSTEK_CREG, tmp);
676
677                 spin_unlock_irq(&mostek_lock);
678         }
679 }
680
681 /* davem suggests we keep this within the 4M locked kernel image */
682 static u32 starfire_get_time(void)
683 {
684         static char obp_gettod[32];
685         static u32 unix_tod;
686
687         sprintf(obp_gettod, "h# %08x unix-gettod",
688                 (unsigned int) (long) &unix_tod);
689         prom_feval(obp_gettod);
690
691         return unix_tod;
692 }
693
694 static int starfire_set_time(u32 val)
695 {
696         /* Do nothing, time is set using the service processor
697          * console on this platform.
698          */
699         return 0;
700 }
701
702 static u32 hypervisor_get_time(void)
703 {
704         register unsigned long func asm("%o5");
705         register unsigned long arg0 asm("%o0");
706         register unsigned long arg1 asm("%o1");
707         int retries = 10000;
708
709 retry:
710         func = HV_FAST_TOD_GET;
711         arg0 = 0;
712         arg1 = 0;
713         __asm__ __volatile__("ta        %6"
714                              : "=&r" (func), "=&r" (arg0), "=&r" (arg1)
715                              : "0" (func), "1" (arg0), "2" (arg1),
716                                "i" (HV_FAST_TRAP));
717         if (arg0 == HV_EOK)
718                 return arg1;
719         if (arg0 == HV_EWOULDBLOCK) {
720                 if (--retries > 0) {
721                         udelay(100);
722                         goto retry;
723                 }
724                 printk(KERN_WARNING "SUN4V: tod_get() timed out.\n");
725                 return 0;
726         }
727         printk(KERN_WARNING "SUN4V: tod_get() not supported.\n");
728         return 0;
729 }
730
731 static int hypervisor_set_time(u32 secs)
732 {
733         register unsigned long func asm("%o5");
734         register unsigned long arg0 asm("%o0");
735         int retries = 10000;
736
737 retry:
738         func = HV_FAST_TOD_SET;
739         arg0 = secs;
740         __asm__ __volatile__("ta        %4"
741                              : "=&r" (func), "=&r" (arg0)
742                              : "0" (func), "1" (arg0),
743                                "i" (HV_FAST_TRAP));
744         if (arg0 == HV_EOK)
745                 return 0;
746         if (arg0 == HV_EWOULDBLOCK) {
747                 if (--retries > 0) {
748                         udelay(100);
749                         goto retry;
750                 }
751                 printk(KERN_WARNING "SUN4V: tod_set() timed out.\n");
752                 return -EAGAIN;
753         }
754         printk(KERN_WARNING "SUN4V: tod_set() not supported.\n");
755         return -EOPNOTSUPP;
756 }
757
758 void __init clock_probe(void)
759 {
760         struct linux_prom_registers clk_reg[2];
761         char model[128];
762         int node, busnd = -1, err;
763         unsigned long flags;
764         struct linux_central *cbus;
765 #ifdef CONFIG_PCI
766         struct linux_ebus *ebus = NULL;
767         struct sparc_isa_bridge *isa_br = NULL;
768 #endif
769         static int invoked;
770
771         if (invoked)
772                 return;
773         invoked = 1;
774
775
776         if (this_is_starfire) {
777                 xtime.tv_sec = starfire_get_time();
778                 xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
779                 set_normalized_timespec(&wall_to_monotonic,
780                                         -xtime.tv_sec, -xtime.tv_nsec);
781                 return;
782         }
783         if (tlb_type == hypervisor) {
784                 xtime.tv_sec = hypervisor_get_time();
785                 xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
786                 set_normalized_timespec(&wall_to_monotonic,
787                                         -xtime.tv_sec, -xtime.tv_nsec);
788                 return;
789         }
790
791         local_irq_save(flags);
792
793         cbus = central_bus;
794         if (cbus != NULL)
795                 busnd = central_bus->child->prom_node;
796
797         /* Check FHC Central then EBUSs then ISA bridges then SBUSs.
798          * That way we handle the presence of multiple properly.
799          *
800          * As a special case, machines with Central must provide the
801          * timer chip there.
802          */
803 #ifdef CONFIG_PCI
804         if (ebus_chain != NULL) {
805                 ebus = ebus_chain;
806                 if (busnd == -1)
807                         busnd = ebus->prom_node;
808         }
809         if (isa_chain != NULL) {
810                 isa_br = isa_chain;
811                 if (busnd == -1)
812                         busnd = isa_br->prom_node;
813         }
814 #endif
815         if (sbus_root != NULL && busnd == -1)
816                 busnd = sbus_root->prom_node;
817
818         if (busnd == -1) {
819                 prom_printf("clock_probe: problem, cannot find bus to search.\n");
820                 prom_halt();
821         }
822
823         node = prom_getchild(busnd);
824
825         while (1) {
826                 if (!node)
827                         model[0] = 0;
828                 else
829                         prom_getstring(node, "model", model, sizeof(model));
830                 if (strcmp(model, "mk48t02") &&
831                     strcmp(model, "mk48t08") &&
832                     strcmp(model, "mk48t59") &&
833                     strcmp(model, "m5819") &&
834                     strcmp(model, "m5819p") &&
835                     strcmp(model, "m5823") &&
836                     strcmp(model, "ds1287")) {
837                         if (cbus != NULL) {
838                                 prom_printf("clock_probe: Central bus lacks timer chip.\n");
839                                 prom_halt();
840                         }
841
842                         if (node != 0)
843                                 node = prom_getsibling(node);
844 #ifdef CONFIG_PCI
845                         while ((node == 0) && ebus != NULL) {
846                                 ebus = ebus->next;
847                                 if (ebus != NULL) {
848                                         busnd = ebus->prom_node;
849                                         node = prom_getchild(busnd);
850                                 }
851                         }
852                         while ((node == 0) && isa_br != NULL) {
853                                 isa_br = isa_br->next;
854                                 if (isa_br != NULL) {
855                                         busnd = isa_br->prom_node;
856                                         node = prom_getchild(busnd);
857                                 }
858                         }
859 #endif
860                         if (node == 0) {
861                                 prom_printf("clock_probe: Cannot find timer chip\n");
862                                 prom_halt();
863                         }
864                         continue;
865                 }
866
867                 err = prom_getproperty(node, "reg", (char *)clk_reg,
868                                        sizeof(clk_reg));
869                 if(err == -1) {
870                         prom_printf("clock_probe: Cannot get Mostek reg property\n");
871                         prom_halt();
872                 }
873
874                 if (cbus != NULL) {
875                         apply_fhc_ranges(central_bus->child, clk_reg, 1);
876                         apply_central_ranges(central_bus, clk_reg, 1);
877                 }
878 #ifdef CONFIG_PCI
879                 else if (ebus != NULL) {
880                         struct linux_ebus_device *edev;
881
882                         for_each_ebusdev(edev, ebus)
883                                 if (edev->prom_node == node)
884                                         break;
885                         if (edev == NULL) {
886                                 if (isa_chain != NULL)
887                                         goto try_isa_clock;
888                                 prom_printf("%s: Mostek not probed by EBUS\n",
889                                             __FUNCTION__);
890                                 prom_halt();
891                         }
892
893                         if (!strcmp(model, "ds1287") ||
894                             !strcmp(model, "m5819") ||
895                             !strcmp(model, "m5819p") ||
896                             !strcmp(model, "m5823")) {
897                                 ds1287_regs = edev->resource[0].start;
898                         } else {
899                                 mstk48t59_regs = (void __iomem *)
900                                         edev->resource[0].start;
901                                 mstk48t02_regs = mstk48t59_regs + MOSTEK_48T59_48T02;
902                         }
903                         break;
904                 }
905                 else if (isa_br != NULL) {
906                         struct sparc_isa_device *isadev;
907
908 try_isa_clock:
909                         for_each_isadev(isadev, isa_br)
910                                 if (isadev->prom_node == node)
911                                         break;
912                         if (isadev == NULL) {
913                                 prom_printf("%s: Mostek not probed by ISA\n");
914                                 prom_halt();
915                         }
916                         if (!strcmp(model, "ds1287") ||
917                             !strcmp(model, "m5819") ||
918                             !strcmp(model, "m5819p") ||
919                             !strcmp(model, "m5823")) {
920                                 ds1287_regs = isadev->resource.start;
921                         } else {
922                                 mstk48t59_regs = (void __iomem *)
923                                         isadev->resource.start;
924                                 mstk48t02_regs = mstk48t59_regs + MOSTEK_48T59_48T02;
925                         }
926                         break;
927                 }
928 #endif
929                 else {
930                         if (sbus_root->num_sbus_ranges) {
931                                 int nranges = sbus_root->num_sbus_ranges;
932                                 int rngc;
933
934                                 for (rngc = 0; rngc < nranges; rngc++)
935                                         if (clk_reg[0].which_io ==
936                                             sbus_root->sbus_ranges[rngc].ot_child_space)
937                                                 break;
938                                 if (rngc == nranges) {
939                                         prom_printf("clock_probe: Cannot find ranges for "
940                                                     "clock regs.\n");
941                                         prom_halt();
942                                 }
943                                 clk_reg[0].which_io =
944                                         sbus_root->sbus_ranges[rngc].ot_parent_space;
945                                 clk_reg[0].phys_addr +=
946                                         sbus_root->sbus_ranges[rngc].ot_parent_base;
947                         }
948                 }
949
950                 if(model[5] == '0' && model[6] == '2') {
951                         mstk48t02_regs = (void __iomem *)
952                                 (((u64)clk_reg[0].phys_addr) |
953                                  (((u64)clk_reg[0].which_io)<<32UL));
954                 } else if(model[5] == '0' && model[6] == '8') {
955                         mstk48t08_regs = (void __iomem *)
956                                 (((u64)clk_reg[0].phys_addr) |
957                                  (((u64)clk_reg[0].which_io)<<32UL));
958                         mstk48t02_regs = mstk48t08_regs + MOSTEK_48T08_48T02;
959                 } else {
960                         mstk48t59_regs = (void __iomem *)
961                                 (((u64)clk_reg[0].phys_addr) |
962                                  (((u64)clk_reg[0].which_io)<<32UL));
963                         mstk48t02_regs = mstk48t59_regs + MOSTEK_48T59_48T02;
964                 }
965                 break;
966         }
967
968         if (mstk48t02_regs != NULL) {
969                 /* Report a low battery voltage condition. */
970                 if (has_low_battery())
971                         prom_printf("NVRAM: Low battery voltage!\n");
972
973                 /* Kick start the clock if it is completely stopped. */
974                 if (mostek_read(mstk48t02_regs + MOSTEK_SEC) & MSTK_STOP)
975                         kick_start_clock();
976         }
977
978         set_system_time();
979         
980         local_irq_restore(flags);
981 }
982
983 /* This is gets the master TICK_INT timer going. */
984 static unsigned long sparc64_init_timers(void)
985 {
986         unsigned long clock;
987         int node;
988 #ifdef CONFIG_SMP
989         extern void smp_tick_init(void);
990 #endif
991
992         if (tlb_type == spitfire) {
993                 unsigned long ver, manuf, impl;
994
995                 __asm__ __volatile__ ("rdpr %%ver, %0"
996                                       : "=&r" (ver));
997                 manuf = ((ver >> 48) & 0xffff);
998                 impl = ((ver >> 32) & 0xffff);
999                 if (manuf == 0x17 && impl == 0x13) {
1000                         /* Hummingbird, aka Ultra-IIe */
1001                         tick_ops = &hbtick_operations;
1002                         node = prom_root_node;
1003                         clock = prom_getint(node, "stick-frequency");
1004                 } else {
1005                         tick_ops = &tick_operations;
1006                         cpu_find_by_instance(0, &node, NULL);
1007                         clock = prom_getint(node, "clock-frequency");
1008                 }
1009         } else {
1010                 tick_ops = &stick_operations;
1011                 node = prom_root_node;
1012                 clock = prom_getint(node, "stick-frequency");
1013         }
1014         timer_tick_offset = clock / HZ;
1015
1016 #ifdef CONFIG_SMP
1017         smp_tick_init();
1018 #endif
1019
1020         return clock;
1021 }
1022
1023 static void sparc64_start_timers(void)
1024 {
1025         unsigned long pstate;
1026
1027         /* Guarantee that the following sequences execute
1028          * uninterrupted.
1029          */
1030         __asm__ __volatile__("rdpr      %%pstate, %0\n\t"
1031                              "wrpr      %0, %1, %%pstate"
1032                              : "=r" (pstate)
1033                              : "i" (PSTATE_IE));
1034
1035         tick_ops->init_tick(timer_tick_offset);
1036
1037         /* Restore PSTATE_IE. */
1038         __asm__ __volatile__("wrpr      %0, 0x0, %%pstate"
1039                              : /* no outputs */
1040                              : "r" (pstate));
1041
1042         local_irq_enable();
1043 }
1044
1045 struct freq_table {
1046         unsigned long clock_tick_ref;
1047         unsigned int ref_freq;
1048 };
1049 static DEFINE_PER_CPU(struct freq_table, sparc64_freq_table) = { 0, 0 };
1050
1051 unsigned long sparc64_get_clock_tick(unsigned int cpu)
1052 {
1053         struct freq_table *ft = &per_cpu(sparc64_freq_table, cpu);
1054
1055         if (ft->clock_tick_ref)
1056                 return ft->clock_tick_ref;
1057         return cpu_data(cpu).clock_tick;
1058 }
1059
1060 #ifdef CONFIG_CPU_FREQ
1061
1062 static int sparc64_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
1063                                     void *data)
1064 {
1065         struct cpufreq_freqs *freq = data;
1066         unsigned int cpu = freq->cpu;
1067         struct freq_table *ft = &per_cpu(sparc64_freq_table, cpu);
1068
1069         if (!ft->ref_freq) {
1070                 ft->ref_freq = freq->old;
1071                 ft->clock_tick_ref = cpu_data(cpu).clock_tick;
1072         }
1073         if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
1074             (val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
1075             (val == CPUFREQ_RESUMECHANGE)) {
1076                 cpu_data(cpu).clock_tick =
1077                         cpufreq_scale(ft->clock_tick_ref,
1078                                       ft->ref_freq,
1079                                       freq->new);
1080         }
1081
1082         return 0;
1083 }
1084
1085 static struct notifier_block sparc64_cpufreq_notifier_block = {
1086         .notifier_call  = sparc64_cpufreq_notifier
1087 };
1088
1089 #endif /* CONFIG_CPU_FREQ */
1090
1091 static struct time_interpolator sparc64_cpu_interpolator = {
1092         .source         =       TIME_SOURCE_CPU,
1093         .shift          =       16,
1094         .mask           =       0xffffffffffffffffLL
1095 };
1096
1097 /* The quotient formula is taken from the IA64 port. */
1098 #define SPARC64_NSEC_PER_CYC_SHIFT      30UL
1099 void __init time_init(void)
1100 {
1101         unsigned long clock = sparc64_init_timers();
1102
1103         sparc64_cpu_interpolator.frequency = clock;
1104         register_time_interpolator(&sparc64_cpu_interpolator);
1105
1106         /* Now that the interpolator is registered, it is
1107          * safe to start the timer ticking.
1108          */
1109         sparc64_start_timers();
1110
1111         timer_ticks_per_nsec_quotient =
1112                 (((NSEC_PER_SEC << SPARC64_NSEC_PER_CYC_SHIFT) +
1113                   (clock / 2)) / clock);
1114
1115 #ifdef CONFIG_CPU_FREQ
1116         cpufreq_register_notifier(&sparc64_cpufreq_notifier_block,
1117                                   CPUFREQ_TRANSITION_NOTIFIER);
1118 #endif
1119 }
1120
1121 unsigned long long sched_clock(void)
1122 {
1123         unsigned long ticks = tick_ops->get_tick();
1124
1125         return (ticks * timer_ticks_per_nsec_quotient)
1126                 >> SPARC64_NSEC_PER_CYC_SHIFT;
1127 }
1128
1129 static int set_rtc_mmss(unsigned long nowtime)
1130 {
1131         int real_seconds, real_minutes, chip_minutes;
1132         void __iomem *mregs = mstk48t02_regs;
1133 #ifdef CONFIG_PCI
1134         unsigned long dregs = ds1287_regs;
1135 #else
1136         unsigned long dregs = 0UL;
1137 #endif
1138         unsigned long flags;
1139         u8 tmp;
1140
1141         /* 
1142          * Not having a register set can lead to trouble.
1143          * Also starfire doesn't have a tod clock.
1144          */
1145         if (!mregs && !dregs) 
1146                 return -1;
1147
1148         if (mregs) {
1149                 spin_lock_irqsave(&mostek_lock, flags);
1150
1151                 /* Read the current RTC minutes. */
1152                 tmp = mostek_read(mregs + MOSTEK_CREG);
1153                 tmp |= MSTK_CREG_READ;
1154                 mostek_write(mregs + MOSTEK_CREG, tmp);
1155
1156                 chip_minutes = MSTK_REG_MIN(mregs);
1157
1158                 tmp = mostek_read(mregs + MOSTEK_CREG);
1159                 tmp &= ~MSTK_CREG_READ;
1160                 mostek_write(mregs + MOSTEK_CREG, tmp);
1161
1162                 /*
1163                  * since we're only adjusting minutes and seconds,
1164                  * don't interfere with hour overflow. This avoids
1165                  * messing with unknown time zones but requires your
1166                  * RTC not to be off by more than 15 minutes
1167                  */
1168                 real_seconds = nowtime % 60;
1169                 real_minutes = nowtime / 60;
1170                 if (((abs(real_minutes - chip_minutes) + 15)/30) & 1)
1171                         real_minutes += 30;     /* correct for half hour time zone */
1172                 real_minutes %= 60;
1173
1174                 if (abs(real_minutes - chip_minutes) < 30) {
1175                         tmp = mostek_read(mregs + MOSTEK_CREG);
1176                         tmp |= MSTK_CREG_WRITE;
1177                         mostek_write(mregs + MOSTEK_CREG, tmp);
1178
1179                         MSTK_SET_REG_SEC(mregs,real_seconds);
1180                         MSTK_SET_REG_MIN(mregs,real_minutes);
1181
1182                         tmp = mostek_read(mregs + MOSTEK_CREG);
1183                         tmp &= ~MSTK_CREG_WRITE;
1184                         mostek_write(mregs + MOSTEK_CREG, tmp);
1185
1186                         spin_unlock_irqrestore(&mostek_lock, flags);
1187
1188                         return 0;
1189                 } else {
1190                         spin_unlock_irqrestore(&mostek_lock, flags);
1191
1192                         return -1;
1193                 }
1194         } else {
1195                 int retval = 0;
1196                 unsigned char save_control, save_freq_select;
1197
1198                 /* Stolen from arch/i386/kernel/time.c, see there for
1199                  * credits and descriptive comments.
1200                  */
1201                 spin_lock_irqsave(&rtc_lock, flags);
1202                 save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being set */
1203                 CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
1204
1205                 save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset prescaler */
1206                 CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
1207
1208                 chip_minutes = CMOS_READ(RTC_MINUTES);
1209                 if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
1210                         BCD_TO_BIN(chip_minutes);
1211                 real_seconds = nowtime % 60;
1212                 real_minutes = nowtime / 60;
1213                 if (((abs(real_minutes - chip_minutes) + 15)/30) & 1)
1214                         real_minutes += 30;
1215                 real_minutes %= 60;
1216
1217                 if (abs(real_minutes - chip_minutes) < 30) {
1218                         if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1219                                 BIN_TO_BCD(real_seconds);
1220                                 BIN_TO_BCD(real_minutes);
1221                         }
1222                         CMOS_WRITE(real_seconds,RTC_SECONDS);
1223                         CMOS_WRITE(real_minutes,RTC_MINUTES);
1224                 } else {
1225                         printk(KERN_WARNING
1226                                "set_rtc_mmss: can't update from %d to %d\n",
1227                                chip_minutes, real_minutes);
1228                         retval = -1;
1229                 }
1230
1231                 CMOS_WRITE(save_control, RTC_CONTROL);
1232                 CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
1233                 spin_unlock_irqrestore(&rtc_lock, flags);
1234
1235                 return retval;
1236         }
1237 }
1238
1239 #define RTC_IS_OPEN             0x01    /* means /dev/rtc is in use     */
1240 static unsigned char mini_rtc_status;   /* bitmapped status byte.       */
1241
1242 /* months start at 0 now */
1243 static unsigned char days_in_mo[] =
1244 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
1245
1246 #define FEBRUARY        2
1247 #define STARTOFTIME     1970
1248 #define SECDAY          86400L
1249 #define SECYR           (SECDAY * 365)
1250 #define leapyear(year)          ((year) % 4 == 0 && \
1251                                  ((year) % 100 != 0 || (year) % 400 == 0))
1252 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
1253 #define days_in_month(a)        (month_days[(a) - 1])
1254
1255 static int month_days[12] = {
1256         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
1257 };
1258
1259 /*
1260  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
1261  */
1262 static void GregorianDay(struct rtc_time * tm)
1263 {
1264         int leapsToDate;
1265         int lastYear;
1266         int day;
1267         int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
1268
1269         lastYear = tm->tm_year - 1;
1270
1271         /*
1272          * Number of leap corrections to apply up to end of last year
1273          */
1274         leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
1275
1276         /*
1277          * This year is a leap year if it is divisible by 4 except when it is
1278          * divisible by 100 unless it is divisible by 400
1279          *
1280          * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
1281          */
1282         day = tm->tm_mon > 2 && leapyear(tm->tm_year);
1283
1284         day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
1285                    tm->tm_mday;
1286
1287         tm->tm_wday = day % 7;
1288 }
1289
1290 static void to_tm(int tim, struct rtc_time *tm)
1291 {
1292         register int    i;
1293         register long   hms, day;
1294
1295         day = tim / SECDAY;
1296         hms = tim % SECDAY;
1297
1298         /* Hours, minutes, seconds are easy */
1299         tm->tm_hour = hms / 3600;
1300         tm->tm_min = (hms % 3600) / 60;
1301         tm->tm_sec = (hms % 3600) % 60;
1302
1303         /* Number of years in days */
1304         for (i = STARTOFTIME; day >= days_in_year(i); i++)
1305                 day -= days_in_year(i);
1306         tm->tm_year = i;
1307
1308         /* Number of months in days left */
1309         if (leapyear(tm->tm_year))
1310                 days_in_month(FEBRUARY) = 29;
1311         for (i = 1; day >= days_in_month(i); i++)
1312                 day -= days_in_month(i);
1313         days_in_month(FEBRUARY) = 28;
1314         tm->tm_mon = i;
1315
1316         /* Days are what is left over (+1) from all that. */
1317         tm->tm_mday = day + 1;
1318
1319         /*
1320          * Determine the day of week
1321          */
1322         GregorianDay(tm);
1323 }
1324
1325 /* Both Starfire and SUN4V give us seconds since Jan 1st, 1970,
1326  * aka Unix time.  So we have to convert to/from rtc_time.
1327  */
1328 static inline void mini_get_rtc_time(struct rtc_time *time)
1329 {
1330         unsigned long flags;
1331         u32 seconds;
1332
1333         spin_lock_irqsave(&rtc_lock, flags);
1334         seconds = 0;
1335         if (this_is_starfire)
1336                 seconds = starfire_get_time();
1337         else if (tlb_type == hypervisor)
1338                 seconds = hypervisor_get_time();
1339         spin_unlock_irqrestore(&rtc_lock, flags);
1340
1341         to_tm(seconds, time);
1342         time->tm_year -= 1900;
1343         time->tm_mon -= 1;
1344 }
1345
1346 static inline int mini_set_rtc_time(struct rtc_time *time)
1347 {
1348         u32 seconds = mktime(time->tm_year + 1900, time->tm_mon + 1,
1349                              time->tm_mday, time->tm_hour,
1350                              time->tm_min, time->tm_sec);
1351         unsigned long flags;
1352         int err;
1353
1354         spin_lock_irqsave(&rtc_lock, flags);
1355         err = -ENODEV;
1356         if (this_is_starfire)
1357                 err = starfire_set_time(seconds);
1358         else  if (tlb_type == hypervisor)
1359                 err = hypervisor_set_time(seconds);
1360         spin_unlock_irqrestore(&rtc_lock, flags);
1361
1362         return err;
1363 }
1364
1365 static int mini_rtc_ioctl(struct inode *inode, struct file *file,
1366                           unsigned int cmd, unsigned long arg)
1367 {
1368         struct rtc_time wtime;
1369         void __user *argp = (void __user *)arg;
1370
1371         switch (cmd) {
1372
1373         case RTC_PLL_GET:
1374                 return -EINVAL;
1375
1376         case RTC_PLL_SET:
1377                 return -EINVAL;
1378
1379         case RTC_UIE_OFF:       /* disable ints from RTC updates.       */
1380                 return 0;
1381
1382         case RTC_UIE_ON:        /* enable ints for RTC updates. */
1383                 return -EINVAL;
1384
1385         case RTC_RD_TIME:       /* Read the time/date from RTC  */
1386                 /* this doesn't get week-day, who cares */
1387                 memset(&wtime, 0, sizeof(wtime));
1388                 mini_get_rtc_time(&wtime);
1389
1390                 return copy_to_user(argp, &wtime, sizeof(wtime)) ? -EFAULT : 0;
1391
1392         case RTC_SET_TIME:      /* Set the RTC */
1393             {
1394                 int year;
1395                 unsigned char leap_yr;
1396
1397                 if (!capable(CAP_SYS_TIME))
1398                         return -EACCES;
1399
1400                 if (copy_from_user(&wtime, argp, sizeof(wtime)))
1401                         return -EFAULT;
1402
1403                 year = wtime.tm_year + 1900;
1404                 leap_yr = ((!(year % 4) && (year % 100)) ||
1405                            !(year % 400));
1406
1407                 if ((wtime.tm_mon < 0 || wtime.tm_mon > 11) || (wtime.tm_mday < 1))
1408                         return -EINVAL;
1409
1410                 if (wtime.tm_mday < 0 || wtime.tm_mday >
1411                     (days_in_mo[wtime.tm_mon] + ((wtime.tm_mon == 1) && leap_yr)))
1412                         return -EINVAL;
1413
1414                 if (wtime.tm_hour < 0 || wtime.tm_hour >= 24 ||
1415                     wtime.tm_min < 0 || wtime.tm_min >= 60 ||
1416                     wtime.tm_sec < 0 || wtime.tm_sec >= 60)
1417                         return -EINVAL;
1418
1419                 return mini_set_rtc_time(&wtime);
1420             }
1421         }
1422
1423         return -EINVAL;
1424 }
1425
1426 static int mini_rtc_open(struct inode *inode, struct file *file)
1427 {
1428         if (mini_rtc_status & RTC_IS_OPEN)
1429                 return -EBUSY;
1430
1431         mini_rtc_status |= RTC_IS_OPEN;
1432
1433         return 0;
1434 }
1435
1436 static int mini_rtc_release(struct inode *inode, struct file *file)
1437 {
1438         mini_rtc_status &= ~RTC_IS_OPEN;
1439         return 0;
1440 }
1441
1442
1443 static struct file_operations mini_rtc_fops = {
1444         .owner          = THIS_MODULE,
1445         .ioctl          = mini_rtc_ioctl,
1446         .open           = mini_rtc_open,
1447         .release        = mini_rtc_release,
1448 };
1449
1450 static struct miscdevice rtc_mini_dev =
1451 {
1452         .minor          = RTC_MINOR,
1453         .name           = "rtc",
1454         .fops           = &mini_rtc_fops,
1455 };
1456
1457 static int __init rtc_mini_init(void)
1458 {
1459         int retval;
1460
1461         if (tlb_type != hypervisor && !this_is_starfire)
1462                 return -ENODEV;
1463
1464         printk(KERN_INFO "Mini RTC Driver\n");
1465
1466         retval = misc_register(&rtc_mini_dev);
1467         if (retval < 0)
1468                 return retval;
1469
1470         return 0;
1471 }
1472
1473 static void __exit rtc_mini_exit(void)
1474 {
1475         misc_deregister(&rtc_mini_dev);
1476 }
1477
1478
1479 module_init(rtc_mini_init);
1480 module_exit(rtc_mini_exit);