87c10a7544da68c3e8846798f9a619afa90d4544
[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/errno.h>
13 #include <linux/module.h>
14 #include <linux/sched.h>
15 #include <linux/kernel.h>
16 #include <linux/param.h>
17 #include <linux/string.h>
18 #include <linux/mm.h>
19 #include <linux/interrupt.h>
20 #include <linux/time.h>
21 #include <linux/timex.h>
22 #include <linux/init.h>
23 #include <linux/ioport.h>
24 #include <linux/mc146818rtc.h>
25 #include <linux/delay.h>
26 #include <linux/profile.h>
27 #include <linux/bcd.h>
28 #include <linux/jiffies.h>
29 #include <linux/cpufreq.h>
30 #include <linux/percpu.h>
31 #include <linux/profile.h>
32 #include <linux/miscdevice.h>
33 #include <linux/rtc.h>
34 #include <linux/kernel_stat.h>
35 #include <linux/clockchips.h>
36 #include <linux/clocksource.h>
37
38 #include <asm/oplib.h>
39 #include <asm/mostek.h>
40 #include <asm/timer.h>
41 #include <asm/irq.h>
42 #include <asm/io.h>
43 #include <asm/prom.h>
44 #include <asm/of_device.h>
45 #include <asm/starfire.h>
46 #include <asm/smp.h>
47 #include <asm/sections.h>
48 #include <asm/cpudata.h>
49 #include <asm/uaccess.h>
50 #include <asm/prom.h>
51 #include <asm/irq_regs.h>
52
53 DEFINE_SPINLOCK(mostek_lock);
54 DEFINE_SPINLOCK(rtc_lock);
55 void __iomem *mstk48t02_regs = NULL;
56 #ifdef CONFIG_PCI
57 unsigned long ds1287_regs = 0UL;
58 static void __iomem *bq4802_regs;
59 #endif
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 #define TICKCMP_IRQ_BIT (1UL << 63)
68
69 #ifdef CONFIG_SMP
70 unsigned long profile_pc(struct pt_regs *regs)
71 {
72         unsigned long pc = instruction_pointer(regs);
73
74         if (in_lock_functions(pc))
75                 return regs->u_regs[UREG_RETPC];
76         return pc;
77 }
78 EXPORT_SYMBOL(profile_pc);
79 #endif
80
81 static void tick_disable_protection(void)
82 {
83         /* Set things up so user can access tick register for profiling
84          * purposes.  Also workaround BB_ERRATA_1 by doing a dummy
85          * read back of %tick after writing it.
86          */
87         __asm__ __volatile__(
88         "       ba,pt   %%xcc, 1f\n"
89         "        nop\n"
90         "       .align  64\n"
91         "1:     rd      %%tick, %%g2\n"
92         "       add     %%g2, 6, %%g2\n"
93         "       andn    %%g2, %0, %%g2\n"
94         "       wrpr    %%g2, 0, %%tick\n"
95         "       rdpr    %%tick, %%g0"
96         : /* no outputs */
97         : "r" (TICK_PRIV_BIT)
98         : "g2");
99 }
100
101 static void tick_disable_irq(void)
102 {
103         __asm__ __volatile__(
104         "       ba,pt   %%xcc, 1f\n"
105         "        nop\n"
106         "       .align  64\n"
107         "1:     wr      %0, 0x0, %%tick_cmpr\n"
108         "       rd      %%tick_cmpr, %%g0"
109         : /* no outputs */
110         : "r" (TICKCMP_IRQ_BIT));
111 }
112
113 static void tick_init_tick(void)
114 {
115         tick_disable_protection();
116         tick_disable_irq();
117 }
118
119 static unsigned long tick_get_tick(void)
120 {
121         unsigned long ret;
122
123         __asm__ __volatile__("rd        %%tick, %0\n\t"
124                              "mov       %0, %0"
125                              : "=r" (ret));
126
127         return ret & ~TICK_PRIV_BIT;
128 }
129
130 static int tick_add_compare(unsigned long adj)
131 {
132         unsigned long orig_tick, new_tick, new_compare;
133
134         __asm__ __volatile__("rd        %%tick, %0"
135                              : "=r" (orig_tick));
136
137         orig_tick &= ~TICKCMP_IRQ_BIT;
138
139         /* Workaround for Spitfire Errata (#54 I think??), I discovered
140          * this via Sun BugID 4008234, mentioned in Solaris-2.5.1 patch
141          * number 103640.
142          *
143          * On Blackbird writes to %tick_cmpr can fail, the
144          * workaround seems to be to execute the wr instruction
145          * at the start of an I-cache line, and perform a dummy
146          * read back from %tick_cmpr right after writing to it. -DaveM
147          */
148         __asm__ __volatile__("ba,pt     %%xcc, 1f\n\t"
149                              " add      %1, %2, %0\n\t"
150                              ".align    64\n"
151                              "1:\n\t"
152                              "wr        %0, 0, %%tick_cmpr\n\t"
153                              "rd        %%tick_cmpr, %%g0\n\t"
154                              : "=r" (new_compare)
155                              : "r" (orig_tick), "r" (adj));
156
157         __asm__ __volatile__("rd        %%tick, %0"
158                              : "=r" (new_tick));
159         new_tick &= ~TICKCMP_IRQ_BIT;
160
161         return ((long)(new_tick - (orig_tick+adj))) > 0L;
162 }
163
164 static unsigned long tick_add_tick(unsigned long adj)
165 {
166         unsigned long new_tick;
167
168         /* Also need to handle Blackbird bug here too. */
169         __asm__ __volatile__("rd        %%tick, %0\n\t"
170                              "add       %0, %1, %0\n\t"
171                              "wrpr      %0, 0, %%tick\n\t"
172                              : "=&r" (new_tick)
173                              : "r" (adj));
174
175         return new_tick;
176 }
177
178 static struct sparc64_tick_ops tick_operations __read_mostly = {
179         .name           =       "tick",
180         .init_tick      =       tick_init_tick,
181         .disable_irq    =       tick_disable_irq,
182         .get_tick       =       tick_get_tick,
183         .add_tick       =       tick_add_tick,
184         .add_compare    =       tick_add_compare,
185         .softint_mask   =       1UL << 0,
186 };
187
188 struct sparc64_tick_ops *tick_ops __read_mostly = &tick_operations;
189
190 static void stick_disable_irq(void)
191 {
192         __asm__ __volatile__(
193         "wr     %0, 0x0, %%asr25"
194         : /* no outputs */
195         : "r" (TICKCMP_IRQ_BIT));
196 }
197
198 static void stick_init_tick(void)
199 {
200         /* Writes to the %tick and %stick register are not
201          * allowed on sun4v.  The Hypervisor controls that
202          * bit, per-strand.
203          */
204         if (tlb_type != hypervisor) {
205                 tick_disable_protection();
206                 tick_disable_irq();
207
208                 /* Let the user get at STICK too. */
209                 __asm__ __volatile__(
210                 "       rd      %%asr24, %%g2\n"
211                 "       andn    %%g2, %0, %%g2\n"
212                 "       wr      %%g2, 0, %%asr24"
213                 : /* no outputs */
214                 : "r" (TICK_PRIV_BIT)
215                 : "g1", "g2");
216         }
217
218         stick_disable_irq();
219 }
220
221 static unsigned long stick_get_tick(void)
222 {
223         unsigned long ret;
224
225         __asm__ __volatile__("rd        %%asr24, %0"
226                              : "=r" (ret));
227
228         return ret & ~TICK_PRIV_BIT;
229 }
230
231 static unsigned long stick_add_tick(unsigned long adj)
232 {
233         unsigned long new_tick;
234
235         __asm__ __volatile__("rd        %%asr24, %0\n\t"
236                              "add       %0, %1, %0\n\t"
237                              "wr        %0, 0, %%asr24\n\t"
238                              : "=&r" (new_tick)
239                              : "r" (adj));
240
241         return new_tick;
242 }
243
244 static int stick_add_compare(unsigned long adj)
245 {
246         unsigned long orig_tick, new_tick;
247
248         __asm__ __volatile__("rd        %%asr24, %0"
249                              : "=r" (orig_tick));
250         orig_tick &= ~TICKCMP_IRQ_BIT;
251
252         __asm__ __volatile__("wr        %0, 0, %%asr25"
253                              : /* no outputs */
254                              : "r" (orig_tick + adj));
255
256         __asm__ __volatile__("rd        %%asr24, %0"
257                              : "=r" (new_tick));
258         new_tick &= ~TICKCMP_IRQ_BIT;
259
260         return ((long)(new_tick - (orig_tick+adj))) > 0L;
261 }
262
263 static struct sparc64_tick_ops stick_operations __read_mostly = {
264         .name           =       "stick",
265         .init_tick      =       stick_init_tick,
266         .disable_irq    =       stick_disable_irq,
267         .get_tick       =       stick_get_tick,
268         .add_tick       =       stick_add_tick,
269         .add_compare    =       stick_add_compare,
270         .softint_mask   =       1UL << 16,
271 };
272
273 /* On Hummingbird the STICK/STICK_CMPR register is implemented
274  * in I/O space.  There are two 64-bit registers each, the
275  * first holds the low 32-bits of the value and the second holds
276  * the high 32-bits.
277  *
278  * Since STICK is constantly updating, we have to access it carefully.
279  *
280  * The sequence we use to read is:
281  * 1) read high
282  * 2) read low
283  * 3) read high again, if it rolled re-read both low and high again.
284  *
285  * Writing STICK safely is also tricky:
286  * 1) write low to zero
287  * 2) write high
288  * 3) write low
289  */
290 #define HBIRD_STICKCMP_ADDR     0x1fe0000f060UL
291 #define HBIRD_STICK_ADDR        0x1fe0000f070UL
292
293 static unsigned long __hbird_read_stick(void)
294 {
295         unsigned long ret, tmp1, tmp2, tmp3;
296         unsigned long addr = HBIRD_STICK_ADDR+8;
297
298         __asm__ __volatile__("ldxa      [%1] %5, %2\n"
299                              "1:\n\t"
300                              "sub       %1, 0x8, %1\n\t"
301                              "ldxa      [%1] %5, %3\n\t"
302                              "add       %1, 0x8, %1\n\t"
303                              "ldxa      [%1] %5, %4\n\t"
304                              "cmp       %4, %2\n\t"
305                              "bne,a,pn  %%xcc, 1b\n\t"
306                              " mov      %4, %2\n\t"
307                              "sllx      %4, 32, %4\n\t"
308                              "or        %3, %4, %0\n\t"
309                              : "=&r" (ret), "=&r" (addr),
310                                "=&r" (tmp1), "=&r" (tmp2), "=&r" (tmp3)
311                              : "i" (ASI_PHYS_BYPASS_EC_E), "1" (addr));
312
313         return ret;
314 }
315
316 static void __hbird_write_stick(unsigned long val)
317 {
318         unsigned long low = (val & 0xffffffffUL);
319         unsigned long high = (val >> 32UL);
320         unsigned long addr = HBIRD_STICK_ADDR;
321
322         __asm__ __volatile__("stxa      %%g0, [%0] %4\n\t"
323                              "add       %0, 0x8, %0\n\t"
324                              "stxa      %3, [%0] %4\n\t"
325                              "sub       %0, 0x8, %0\n\t"
326                              "stxa      %2, [%0] %4"
327                              : "=&r" (addr)
328                              : "0" (addr), "r" (low), "r" (high),
329                                "i" (ASI_PHYS_BYPASS_EC_E));
330 }
331
332 static void __hbird_write_compare(unsigned long val)
333 {
334         unsigned long low = (val & 0xffffffffUL);
335         unsigned long high = (val >> 32UL);
336         unsigned long addr = HBIRD_STICKCMP_ADDR + 0x8UL;
337
338         __asm__ __volatile__("stxa      %3, [%0] %4\n\t"
339                              "sub       %0, 0x8, %0\n\t"
340                              "stxa      %2, [%0] %4"
341                              : "=&r" (addr)
342                              : "0" (addr), "r" (low), "r" (high),
343                                "i" (ASI_PHYS_BYPASS_EC_E));
344 }
345
346 static void hbtick_disable_irq(void)
347 {
348         __hbird_write_compare(TICKCMP_IRQ_BIT);
349 }
350
351 static void hbtick_init_tick(void)
352 {
353         tick_disable_protection();
354
355         /* XXX This seems to be necessary to 'jumpstart' Hummingbird
356          * XXX into actually sending STICK interrupts.  I think because
357          * XXX of how we store %tick_cmpr in head.S this somehow resets the
358          * XXX {TICK + STICK} interrupt mux.  -DaveM
359          */
360         __hbird_write_stick(__hbird_read_stick());
361
362         hbtick_disable_irq();
363 }
364
365 static unsigned long hbtick_get_tick(void)
366 {
367         return __hbird_read_stick() & ~TICK_PRIV_BIT;
368 }
369
370 static unsigned long hbtick_add_tick(unsigned long adj)
371 {
372         unsigned long val;
373
374         val = __hbird_read_stick() + adj;
375         __hbird_write_stick(val);
376
377         return val;
378 }
379
380 static int hbtick_add_compare(unsigned long adj)
381 {
382         unsigned long val = __hbird_read_stick();
383         unsigned long val2;
384
385         val &= ~TICKCMP_IRQ_BIT;
386         val += adj;
387         __hbird_write_compare(val);
388
389         val2 = __hbird_read_stick() & ~TICKCMP_IRQ_BIT;
390
391         return ((long)(val2 - val)) > 0L;
392 }
393
394 static struct sparc64_tick_ops hbtick_operations __read_mostly = {
395         .name           =       "hbtick",
396         .init_tick      =       hbtick_init_tick,
397         .disable_irq    =       hbtick_disable_irq,
398         .get_tick       =       hbtick_get_tick,
399         .add_tick       =       hbtick_add_tick,
400         .add_compare    =       hbtick_add_compare,
401         .softint_mask   =       1UL << 0,
402 };
403
404 static unsigned long timer_ticks_per_nsec_quotient __read_mostly;
405
406 #define TICK_SIZE (tick_nsec / 1000)
407
408 #define USEC_AFTER      500000
409 #define USEC_BEFORE     500000
410
411 static void sync_cmos_clock(unsigned long dummy);
412
413 static DEFINE_TIMER(sync_cmos_timer, sync_cmos_clock, 0, 0);
414
415 static void sync_cmos_clock(unsigned long dummy)
416 {
417         struct timeval now, next;
418         int fail = 1;
419
420         /*
421          * If we have an externally synchronized Linux clock, then update
422          * CMOS clock accordingly every ~11 minutes. Set_rtc_mmss() has to be
423          * called as close as possible to 500 ms before the new second starts.
424          * This code is run on a timer.  If the clock is set, that timer
425          * may not expire at the correct time.  Thus, we adjust...
426          */
427         if (!ntp_synced())
428                 /*
429                  * Not synced, exit, do not restart a timer (if one is
430                  * running, let it run out).
431                  */
432                 return;
433
434         do_gettimeofday(&now);
435         if (now.tv_usec >= USEC_AFTER - ((unsigned) TICK_SIZE) / 2 &&
436             now.tv_usec <= USEC_BEFORE + ((unsigned) TICK_SIZE) / 2)
437                 fail = set_rtc_mmss(now.tv_sec);
438
439         next.tv_usec = USEC_AFTER - now.tv_usec;
440         if (next.tv_usec <= 0)
441                 next.tv_usec += USEC_PER_SEC;
442
443         if (!fail)
444                 next.tv_sec = 659;
445         else
446                 next.tv_sec = 0;
447
448         if (next.tv_usec >= USEC_PER_SEC) {
449                 next.tv_sec++;
450                 next.tv_usec -= USEC_PER_SEC;
451         }
452         mod_timer(&sync_cmos_timer, jiffies + timeval_to_jiffies(&next));
453 }
454
455 void notify_arch_cmos_timer(void)
456 {
457         mod_timer(&sync_cmos_timer, jiffies + 1);
458 }
459
460 /* Kick start a stopped clock (procedure from the Sun NVRAM/hostid FAQ). */
461 static void __init kick_start_clock(void)
462 {
463         void __iomem *regs = mstk48t02_regs;
464         u8 sec, tmp;
465         int i, count;
466
467         prom_printf("CLOCK: Clock was stopped. Kick start ");
468
469         spin_lock_irq(&mostek_lock);
470
471         /* Turn on the kick start bit to start the oscillator. */
472         tmp = mostek_read(regs + MOSTEK_CREG);
473         tmp |= MSTK_CREG_WRITE;
474         mostek_write(regs + MOSTEK_CREG, tmp);
475         tmp = mostek_read(regs + MOSTEK_SEC);
476         tmp &= ~MSTK_STOP;
477         mostek_write(regs + MOSTEK_SEC, tmp);
478         tmp = mostek_read(regs + MOSTEK_HOUR);
479         tmp |= MSTK_KICK_START;
480         mostek_write(regs + MOSTEK_HOUR, tmp);
481         tmp = mostek_read(regs + MOSTEK_CREG);
482         tmp &= ~MSTK_CREG_WRITE;
483         mostek_write(regs + MOSTEK_CREG, tmp);
484
485         spin_unlock_irq(&mostek_lock);
486
487         /* Delay to allow the clock oscillator to start. */
488         sec = MSTK_REG_SEC(regs);
489         for (i = 0; i < 3; i++) {
490                 while (sec == MSTK_REG_SEC(regs))
491                         for (count = 0; count < 100000; count++)
492                                 /* nothing */ ;
493                 prom_printf(".");
494                 sec = MSTK_REG_SEC(regs);
495         }
496         prom_printf("\n");
497
498         spin_lock_irq(&mostek_lock);
499
500         /* Turn off kick start and set a "valid" time and date. */
501         tmp = mostek_read(regs + MOSTEK_CREG);
502         tmp |= MSTK_CREG_WRITE;
503         mostek_write(regs + MOSTEK_CREG, tmp);
504         tmp = mostek_read(regs + MOSTEK_HOUR);
505         tmp &= ~MSTK_KICK_START;
506         mostek_write(regs + MOSTEK_HOUR, tmp);
507         MSTK_SET_REG_SEC(regs,0);
508         MSTK_SET_REG_MIN(regs,0);
509         MSTK_SET_REG_HOUR(regs,0);
510         MSTK_SET_REG_DOW(regs,5);
511         MSTK_SET_REG_DOM(regs,1);
512         MSTK_SET_REG_MONTH(regs,8);
513         MSTK_SET_REG_YEAR(regs,1996 - MSTK_YEAR_ZERO);
514         tmp = mostek_read(regs + MOSTEK_CREG);
515         tmp &= ~MSTK_CREG_WRITE;
516         mostek_write(regs + MOSTEK_CREG, tmp);
517
518         spin_unlock_irq(&mostek_lock);
519
520         /* Ensure the kick start bit is off. If it isn't, turn it off. */
521         while (mostek_read(regs + MOSTEK_HOUR) & MSTK_KICK_START) {
522                 prom_printf("CLOCK: Kick start still on!\n");
523
524                 spin_lock_irq(&mostek_lock);
525
526                 tmp = mostek_read(regs + MOSTEK_CREG);
527                 tmp |= MSTK_CREG_WRITE;
528                 mostek_write(regs + MOSTEK_CREG, tmp);
529
530                 tmp = mostek_read(regs + MOSTEK_HOUR);
531                 tmp &= ~MSTK_KICK_START;
532                 mostek_write(regs + MOSTEK_HOUR, tmp);
533
534                 tmp = mostek_read(regs + MOSTEK_CREG);
535                 tmp &= ~MSTK_CREG_WRITE;
536                 mostek_write(regs + MOSTEK_CREG, tmp);
537
538                 spin_unlock_irq(&mostek_lock);
539         }
540
541         prom_printf("CLOCK: Kick start procedure successful.\n");
542 }
543
544 /* Return nonzero if the clock chip battery is low. */
545 static int __init has_low_battery(void)
546 {
547         void __iomem *regs = mstk48t02_regs;
548         u8 data1, data2;
549
550         spin_lock_irq(&mostek_lock);
551
552         data1 = mostek_read(regs + MOSTEK_EEPROM);      /* Read some data. */
553         mostek_write(regs + MOSTEK_EEPROM, ~data1);     /* Write back the complement. */
554         data2 = mostek_read(regs + MOSTEK_EEPROM);      /* Read back the complement. */
555         mostek_write(regs + MOSTEK_EEPROM, data1);      /* Restore original value. */
556
557         spin_unlock_irq(&mostek_lock);
558
559         return (data1 == data2);        /* Was the write blocked? */
560 }
561
562 /* Probe for the real time clock chip. */
563 static void __init set_system_time(void)
564 {
565         unsigned int year, mon, day, hour, min, sec;
566         void __iomem *mregs = mstk48t02_regs;
567 #ifdef CONFIG_PCI
568         unsigned long dregs = ds1287_regs;
569         void __iomem *bregs = bq4802_regs;
570 #else
571         unsigned long dregs = 0UL;
572         void __iomem *bregs = 0UL;
573 #endif
574         u8 tmp;
575
576         if (!mregs && !dregs && !bregs) {
577                 prom_printf("Something wrong, clock regs not mapped yet.\n");
578                 prom_halt();
579         }               
580
581         if (mregs) {
582                 spin_lock_irq(&mostek_lock);
583
584                 /* Traditional Mostek chip. */
585                 tmp = mostek_read(mregs + MOSTEK_CREG);
586                 tmp |= MSTK_CREG_READ;
587                 mostek_write(mregs + MOSTEK_CREG, tmp);
588
589                 sec = MSTK_REG_SEC(mregs);
590                 min = MSTK_REG_MIN(mregs);
591                 hour = MSTK_REG_HOUR(mregs);
592                 day = MSTK_REG_DOM(mregs);
593                 mon = MSTK_REG_MONTH(mregs);
594                 year = MSTK_CVT_YEAR( MSTK_REG_YEAR(mregs) );
595         } else if (bregs) {
596                 unsigned char val = readb(bregs + 0x0e);
597                 unsigned int century;
598
599                 /* BQ4802 RTC chip. */
600
601                 writeb(val | 0x08, bregs + 0x0e);
602
603                 sec  = readb(bregs + 0x00);
604                 min  = readb(bregs + 0x02);
605                 hour = readb(bregs + 0x04);
606                 day  = readb(bregs + 0x06);
607                 mon  = readb(bregs + 0x09);
608                 year = readb(bregs + 0x0a);
609                 century = readb(bregs + 0x0f);
610
611                 writeb(val, bregs + 0x0e);
612
613                 BCD_TO_BIN(sec);
614                 BCD_TO_BIN(min);
615                 BCD_TO_BIN(hour);
616                 BCD_TO_BIN(day);
617                 BCD_TO_BIN(mon);
618                 BCD_TO_BIN(year);
619                 BCD_TO_BIN(century);
620
621                 year += (century * 100);
622         } else {
623                 /* Dallas 12887 RTC chip. */
624
625                 do {
626                         sec  = CMOS_READ(RTC_SECONDS);
627                         min  = CMOS_READ(RTC_MINUTES);
628                         hour = CMOS_READ(RTC_HOURS);
629                         day  = CMOS_READ(RTC_DAY_OF_MONTH);
630                         mon  = CMOS_READ(RTC_MONTH);
631                         year = CMOS_READ(RTC_YEAR);
632                 } while (sec != CMOS_READ(RTC_SECONDS));
633
634                 if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
635                         BCD_TO_BIN(sec);
636                         BCD_TO_BIN(min);
637                         BCD_TO_BIN(hour);
638                         BCD_TO_BIN(day);
639                         BCD_TO_BIN(mon);
640                         BCD_TO_BIN(year);
641                 }
642                 if ((year += 1900) < 1970)
643                         year += 100;
644         }
645
646         xtime.tv_sec = mktime(year, mon, day, hour, min, sec);
647         xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
648         set_normalized_timespec(&wall_to_monotonic,
649                                 -xtime.tv_sec, -xtime.tv_nsec);
650
651         if (mregs) {
652                 tmp = mostek_read(mregs + MOSTEK_CREG);
653                 tmp &= ~MSTK_CREG_READ;
654                 mostek_write(mregs + MOSTEK_CREG, tmp);
655
656                 spin_unlock_irq(&mostek_lock);
657         }
658 }
659
660 /* davem suggests we keep this within the 4M locked kernel image */
661 static u32 starfire_get_time(void)
662 {
663         static char obp_gettod[32];
664         static u32 unix_tod;
665
666         sprintf(obp_gettod, "h# %08x unix-gettod",
667                 (unsigned int) (long) &unix_tod);
668         prom_feval(obp_gettod);
669
670         return unix_tod;
671 }
672
673 static int starfire_set_time(u32 val)
674 {
675         /* Do nothing, time is set using the service processor
676          * console on this platform.
677          */
678         return 0;
679 }
680
681 static u32 hypervisor_get_time(void)
682 {
683         unsigned long ret, time;
684         int retries = 10000;
685
686 retry:
687         ret = sun4v_tod_get(&time);
688         if (ret == HV_EOK)
689                 return time;
690         if (ret == HV_EWOULDBLOCK) {
691                 if (--retries > 0) {
692                         udelay(100);
693                         goto retry;
694                 }
695                 printk(KERN_WARNING "SUN4V: tod_get() timed out.\n");
696                 return 0;
697         }
698         printk(KERN_WARNING "SUN4V: tod_get() not supported.\n");
699         return 0;
700 }
701
702 static int hypervisor_set_time(u32 secs)
703 {
704         unsigned long ret;
705         int retries = 10000;
706
707 retry:
708         ret = sun4v_tod_set(secs);
709         if (ret == HV_EOK)
710                 return 0;
711         if (ret == HV_EWOULDBLOCK) {
712                 if (--retries > 0) {
713                         udelay(100);
714                         goto retry;
715                 }
716                 printk(KERN_WARNING "SUN4V: tod_set() timed out.\n");
717                 return -EAGAIN;
718         }
719         printk(KERN_WARNING "SUN4V: tod_set() not supported.\n");
720         return -EOPNOTSUPP;
721 }
722
723 static int __init clock_model_matches(const char *model)
724 {
725         if (strcmp(model, "mk48t02") &&
726             strcmp(model, "mk48t08") &&
727             strcmp(model, "mk48t59") &&
728             strcmp(model, "m5819") &&
729             strcmp(model, "m5819p") &&
730             strcmp(model, "m5823") &&
731             strcmp(model, "ds1287") &&
732             strcmp(model, "bq4802"))
733                 return 0;
734
735         return 1;
736 }
737
738 static int __devinit clock_probe(struct of_device *op, const struct of_device_id *match)
739 {
740         struct device_node *dp = op->node;
741         const char *model = of_get_property(dp, "model", NULL);
742         const char *compat = of_get_property(dp, "compatible", NULL);
743         unsigned long size, flags;
744         void __iomem *regs;
745
746         if (!model)
747                 model = compat;
748
749         if (!model || !clock_model_matches(model))
750                 return -ENODEV;
751
752         /* On an Enterprise system there can be multiple mostek clocks.
753          * We should only match the one that is on the central FHC bus.
754          */
755         if (!strcmp(dp->parent->name, "fhc") &&
756             strcmp(dp->parent->parent->name, "central") != 0)
757                 return -ENODEV;
758
759         size = (op->resource[0].end - op->resource[0].start) + 1;
760         regs = of_ioremap(&op->resource[0], 0, size, "clock");
761         if (!regs)
762                 return -ENOMEM;
763
764 #ifdef CONFIG_PCI
765         if (!strcmp(model, "ds1287") ||
766             !strcmp(model, "m5819") ||
767             !strcmp(model, "m5819p") ||
768             !strcmp(model, "m5823")) {
769                 ds1287_regs = (unsigned long) regs;
770         } else if (!strcmp(model, "bq4802")) {
771                 bq4802_regs = regs;
772         } else
773 #endif
774         if (model[5] == '0' && model[6] == '2') {
775                 mstk48t02_regs = regs;
776         } else if(model[5] == '0' && model[6] == '8') {
777                 mstk48t08_regs = regs;
778                 mstk48t02_regs = mstk48t08_regs + MOSTEK_48T08_48T02;
779         } else {
780                 mstk48t59_regs = regs;
781                 mstk48t02_regs = mstk48t59_regs + MOSTEK_48T59_48T02;
782         }
783
784         printk(KERN_INFO "%s: Clock regs at %p\n", dp->full_name, regs);
785
786         local_irq_save(flags);
787
788         if (mstk48t02_regs != NULL) {
789                 /* Report a low battery voltage condition. */
790                 if (has_low_battery())
791                         prom_printf("NVRAM: Low battery voltage!\n");
792
793                 /* Kick start the clock if it is completely stopped. */
794                 if (mostek_read(mstk48t02_regs + MOSTEK_SEC) & MSTK_STOP)
795                         kick_start_clock();
796         }
797
798         set_system_time();
799         
800         local_irq_restore(flags);
801
802         return 0;
803 }
804
805 static struct of_device_id clock_match[] = {
806         {
807                 .name = "eeprom",
808         },
809         {
810                 .name = "rtc",
811         },
812         {},
813 };
814
815 static struct of_platform_driver clock_driver = {
816         .name           = "clock",
817         .match_table    = clock_match,
818         .probe          = clock_probe,
819 };
820
821 static int __init clock_init(void)
822 {
823         if (this_is_starfire) {
824                 xtime.tv_sec = starfire_get_time();
825                 xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
826                 set_normalized_timespec(&wall_to_monotonic,
827                                         -xtime.tv_sec, -xtime.tv_nsec);
828                 return 0;
829         }
830         if (tlb_type == hypervisor) {
831                 xtime.tv_sec = hypervisor_get_time();
832                 xtime.tv_nsec = (INITIAL_JIFFIES % HZ) * (NSEC_PER_SEC / HZ);
833                 set_normalized_timespec(&wall_to_monotonic,
834                                         -xtime.tv_sec, -xtime.tv_nsec);
835                 return 0;
836         }
837
838         return of_register_driver(&clock_driver, &of_platform_bus_type);
839 }
840
841 /* Must be after subsys_initcall() so that busses are probed.  Must
842  * be before device_initcall() because things like the RTC driver
843  * need to see the clock registers.
844  */
845 fs_initcall(clock_init);
846
847 /* This is gets the master TICK_INT timer going. */
848 static unsigned long sparc64_init_timers(void)
849 {
850         struct device_node *dp;
851         unsigned long clock;
852
853         dp = of_find_node_by_path("/");
854         if (tlb_type == spitfire) {
855                 unsigned long ver, manuf, impl;
856
857                 __asm__ __volatile__ ("rdpr %%ver, %0"
858                                       : "=&r" (ver));
859                 manuf = ((ver >> 48) & 0xffff);
860                 impl = ((ver >> 32) & 0xffff);
861                 if (manuf == 0x17 && impl == 0x13) {
862                         /* Hummingbird, aka Ultra-IIe */
863                         tick_ops = &hbtick_operations;
864                         clock = of_getintprop_default(dp, "stick-frequency", 0);
865                 } else {
866                         tick_ops = &tick_operations;
867                         clock = local_cpu_data().clock_tick;
868                 }
869         } else {
870                 tick_ops = &stick_operations;
871                 clock = of_getintprop_default(dp, "stick-frequency", 0);
872         }
873
874         return clock;
875 }
876
877 struct freq_table {
878         unsigned long clock_tick_ref;
879         unsigned int ref_freq;
880 };
881 static DEFINE_PER_CPU(struct freq_table, sparc64_freq_table) = { 0, 0 };
882
883 unsigned long sparc64_get_clock_tick(unsigned int cpu)
884 {
885         struct freq_table *ft = &per_cpu(sparc64_freq_table, cpu);
886
887         if (ft->clock_tick_ref)
888                 return ft->clock_tick_ref;
889         return cpu_data(cpu).clock_tick;
890 }
891
892 #ifdef CONFIG_CPU_FREQ
893
894 static int sparc64_cpufreq_notifier(struct notifier_block *nb, unsigned long val,
895                                     void *data)
896 {
897         struct cpufreq_freqs *freq = data;
898         unsigned int cpu = freq->cpu;
899         struct freq_table *ft = &per_cpu(sparc64_freq_table, cpu);
900
901         if (!ft->ref_freq) {
902                 ft->ref_freq = freq->old;
903                 ft->clock_tick_ref = cpu_data(cpu).clock_tick;
904         }
905         if ((val == CPUFREQ_PRECHANGE  && freq->old < freq->new) ||
906             (val == CPUFREQ_POSTCHANGE && freq->old > freq->new) ||
907             (val == CPUFREQ_RESUMECHANGE)) {
908                 cpu_data(cpu).clock_tick =
909                         cpufreq_scale(ft->clock_tick_ref,
910                                       ft->ref_freq,
911                                       freq->new);
912         }
913
914         return 0;
915 }
916
917 static struct notifier_block sparc64_cpufreq_notifier_block = {
918         .notifier_call  = sparc64_cpufreq_notifier
919 };
920
921 #endif /* CONFIG_CPU_FREQ */
922
923 static int sparc64_next_event(unsigned long delta,
924                               struct clock_event_device *evt)
925 {
926         return tick_ops->add_compare(delta) ? -ETIME : 0;
927 }
928
929 static void sparc64_timer_setup(enum clock_event_mode mode,
930                                 struct clock_event_device *evt)
931 {
932         switch (mode) {
933         case CLOCK_EVT_MODE_ONESHOT:
934         case CLOCK_EVT_MODE_RESUME:
935                 break;
936
937         case CLOCK_EVT_MODE_SHUTDOWN:
938                 tick_ops->disable_irq();
939                 break;
940
941         case CLOCK_EVT_MODE_PERIODIC:
942         case CLOCK_EVT_MODE_UNUSED:
943                 WARN_ON(1);
944                 break;
945         };
946 }
947
948 static struct clock_event_device sparc64_clockevent = {
949         .features       = CLOCK_EVT_FEAT_ONESHOT,
950         .set_mode       = sparc64_timer_setup,
951         .set_next_event = sparc64_next_event,
952         .rating         = 100,
953         .shift          = 30,
954         .irq            = -1,
955 };
956 static DEFINE_PER_CPU(struct clock_event_device, sparc64_events);
957
958 void timer_interrupt(int irq, struct pt_regs *regs)
959 {
960         struct pt_regs *old_regs = set_irq_regs(regs);
961         unsigned long tick_mask = tick_ops->softint_mask;
962         int cpu = smp_processor_id();
963         struct clock_event_device *evt = &per_cpu(sparc64_events, cpu);
964
965         clear_softint(tick_mask);
966
967         irq_enter();
968
969         kstat_this_cpu.irqs[0]++;
970
971         if (unlikely(!evt->event_handler)) {
972                 printk(KERN_WARNING
973                        "Spurious SPARC64 timer interrupt on cpu %d\n", cpu);
974         } else
975                 evt->event_handler(evt);
976
977         irq_exit();
978
979         set_irq_regs(old_regs);
980 }
981
982 void __devinit setup_sparc64_timer(void)
983 {
984         struct clock_event_device *sevt;
985         unsigned long pstate;
986
987         /* Guarantee that the following sequences execute
988          * uninterrupted.
989          */
990         __asm__ __volatile__("rdpr      %%pstate, %0\n\t"
991                              "wrpr      %0, %1, %%pstate"
992                              : "=r" (pstate)
993                              : "i" (PSTATE_IE));
994
995         tick_ops->init_tick();
996
997         /* Restore PSTATE_IE. */
998         __asm__ __volatile__("wrpr      %0, 0x0, %%pstate"
999                              : /* no outputs */
1000                              : "r" (pstate));
1001
1002         sevt = &__get_cpu_var(sparc64_events);
1003
1004         memcpy(sevt, &sparc64_clockevent, sizeof(*sevt));
1005         sevt->cpumask = cpumask_of_cpu(smp_processor_id());
1006
1007         clockevents_register_device(sevt);
1008 }
1009
1010 #define SPARC64_NSEC_PER_CYC_SHIFT      10UL
1011
1012 static struct clocksource clocksource_tick = {
1013         .rating         = 100,
1014         .mask           = CLOCKSOURCE_MASK(64),
1015         .shift          = 16,
1016         .flags          = CLOCK_SOURCE_IS_CONTINUOUS,
1017 };
1018
1019 static void __init setup_clockevent_multiplier(unsigned long hz)
1020 {
1021         unsigned long mult, shift = 32;
1022
1023         while (1) {
1024                 mult = div_sc(hz, NSEC_PER_SEC, shift);
1025                 if (mult && (mult >> 32UL) == 0UL)
1026                         break;
1027
1028                 shift--;
1029         }
1030
1031         sparc64_clockevent.shift = shift;
1032         sparc64_clockevent.mult = mult;
1033 }
1034
1035 static unsigned long tb_ticks_per_usec __read_mostly;
1036
1037 void __delay(unsigned long loops)
1038 {
1039         unsigned long bclock, now;
1040
1041         bclock = tick_ops->get_tick();
1042         do {
1043                 now = tick_ops->get_tick();
1044         } while ((now-bclock) < loops);
1045 }
1046 EXPORT_SYMBOL(__delay);
1047
1048 void udelay(unsigned long usecs)
1049 {
1050         __delay(tb_ticks_per_usec * usecs);
1051 }
1052 EXPORT_SYMBOL(udelay);
1053
1054 void __init time_init(void)
1055 {
1056         unsigned long clock = sparc64_init_timers();
1057
1058         tb_ticks_per_usec = clock / USEC_PER_SEC;
1059
1060         timer_ticks_per_nsec_quotient =
1061                 clocksource_hz2mult(clock, SPARC64_NSEC_PER_CYC_SHIFT);
1062
1063         clocksource_tick.name = tick_ops->name;
1064         clocksource_tick.mult =
1065                 clocksource_hz2mult(clock,
1066                                     clocksource_tick.shift);
1067         clocksource_tick.read = tick_ops->get_tick;
1068
1069         printk("clocksource: mult[%x] shift[%d]\n",
1070                clocksource_tick.mult, clocksource_tick.shift);
1071
1072         clocksource_register(&clocksource_tick);
1073
1074         sparc64_clockevent.name = tick_ops->name;
1075
1076         setup_clockevent_multiplier(clock);
1077
1078         sparc64_clockevent.max_delta_ns =
1079                 clockevent_delta2ns(0x7fffffffffffffff, &sparc64_clockevent);
1080         sparc64_clockevent.min_delta_ns =
1081                 clockevent_delta2ns(0xF, &sparc64_clockevent);
1082
1083         printk("clockevent: mult[%lx] shift[%d]\n",
1084                sparc64_clockevent.mult, sparc64_clockevent.shift);
1085
1086         setup_sparc64_timer();
1087
1088 #ifdef CONFIG_CPU_FREQ
1089         cpufreq_register_notifier(&sparc64_cpufreq_notifier_block,
1090                                   CPUFREQ_TRANSITION_NOTIFIER);
1091 #endif
1092 }
1093
1094 unsigned long long sched_clock(void)
1095 {
1096         unsigned long ticks = tick_ops->get_tick();
1097
1098         return (ticks * timer_ticks_per_nsec_quotient)
1099                 >> SPARC64_NSEC_PER_CYC_SHIFT;
1100 }
1101
1102 static int set_rtc_mmss(unsigned long nowtime)
1103 {
1104         int real_seconds, real_minutes, chip_minutes;
1105         void __iomem *mregs = mstk48t02_regs;
1106 #ifdef CONFIG_PCI
1107         unsigned long dregs = ds1287_regs;
1108         void __iomem *bregs = bq4802_regs;
1109 #else
1110         unsigned long dregs = 0UL;
1111         void __iomem *bregs = 0UL;
1112 #endif
1113         unsigned long flags;
1114         u8 tmp;
1115
1116         /* 
1117          * Not having a register set can lead to trouble.
1118          * Also starfire doesn't have a tod clock.
1119          */
1120         if (!mregs && !dregs & !bregs)
1121                 return -1;
1122
1123         if (mregs) {
1124                 spin_lock_irqsave(&mostek_lock, flags);
1125
1126                 /* Read the current RTC minutes. */
1127                 tmp = mostek_read(mregs + MOSTEK_CREG);
1128                 tmp |= MSTK_CREG_READ;
1129                 mostek_write(mregs + MOSTEK_CREG, tmp);
1130
1131                 chip_minutes = MSTK_REG_MIN(mregs);
1132
1133                 tmp = mostek_read(mregs + MOSTEK_CREG);
1134                 tmp &= ~MSTK_CREG_READ;
1135                 mostek_write(mregs + MOSTEK_CREG, tmp);
1136
1137                 /*
1138                  * since we're only adjusting minutes and seconds,
1139                  * don't interfere with hour overflow. This avoids
1140                  * messing with unknown time zones but requires your
1141                  * RTC not to be off by more than 15 minutes
1142                  */
1143                 real_seconds = nowtime % 60;
1144                 real_minutes = nowtime / 60;
1145                 if (((abs(real_minutes - chip_minutes) + 15)/30) & 1)
1146                         real_minutes += 30;     /* correct for half hour time zone */
1147                 real_minutes %= 60;
1148
1149                 if (abs(real_minutes - chip_minutes) < 30) {
1150                         tmp = mostek_read(mregs + MOSTEK_CREG);
1151                         tmp |= MSTK_CREG_WRITE;
1152                         mostek_write(mregs + MOSTEK_CREG, tmp);
1153
1154                         MSTK_SET_REG_SEC(mregs,real_seconds);
1155                         MSTK_SET_REG_MIN(mregs,real_minutes);
1156
1157                         tmp = mostek_read(mregs + MOSTEK_CREG);
1158                         tmp &= ~MSTK_CREG_WRITE;
1159                         mostek_write(mregs + MOSTEK_CREG, tmp);
1160
1161                         spin_unlock_irqrestore(&mostek_lock, flags);
1162
1163                         return 0;
1164                 } else {
1165                         spin_unlock_irqrestore(&mostek_lock, flags);
1166
1167                         return -1;
1168                 }
1169         } else if (bregs) {
1170                 int retval = 0;
1171                 unsigned char val = readb(bregs + 0x0e);
1172
1173                 /* BQ4802 RTC chip. */
1174
1175                 writeb(val | 0x08, bregs + 0x0e);
1176
1177                 chip_minutes = readb(bregs + 0x02);
1178                 BCD_TO_BIN(chip_minutes);
1179                 real_seconds = nowtime % 60;
1180                 real_minutes = nowtime / 60;
1181                 if (((abs(real_minutes - chip_minutes) + 15)/30) & 1)
1182                         real_minutes += 30;
1183                 real_minutes %= 60;
1184
1185                 if (abs(real_minutes - chip_minutes) < 30) {
1186                         BIN_TO_BCD(real_seconds);
1187                         BIN_TO_BCD(real_minutes);
1188                         writeb(real_seconds, bregs + 0x00);
1189                         writeb(real_minutes, bregs + 0x02);
1190                 } else {
1191                         printk(KERN_WARNING
1192                                "set_rtc_mmss: can't update from %d to %d\n",
1193                                chip_minutes, real_minutes);
1194                         retval = -1;
1195                 }
1196
1197                 writeb(val, bregs + 0x0e);
1198
1199                 return retval;
1200         } else {
1201                 int retval = 0;
1202                 unsigned char save_control, save_freq_select;
1203
1204                 /* Stolen from arch/i386/kernel/time.c, see there for
1205                  * credits and descriptive comments.
1206                  */
1207                 spin_lock_irqsave(&rtc_lock, flags);
1208                 save_control = CMOS_READ(RTC_CONTROL); /* tell the clock it's being set */
1209                 CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
1210
1211                 save_freq_select = CMOS_READ(RTC_FREQ_SELECT); /* stop and reset prescaler */
1212                 CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
1213
1214                 chip_minutes = CMOS_READ(RTC_MINUTES);
1215                 if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
1216                         BCD_TO_BIN(chip_minutes);
1217                 real_seconds = nowtime % 60;
1218                 real_minutes = nowtime / 60;
1219                 if (((abs(real_minutes - chip_minutes) + 15)/30) & 1)
1220                         real_minutes += 30;
1221                 real_minutes %= 60;
1222
1223                 if (abs(real_minutes - chip_minutes) < 30) {
1224                         if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1225                                 BIN_TO_BCD(real_seconds);
1226                                 BIN_TO_BCD(real_minutes);
1227                         }
1228                         CMOS_WRITE(real_seconds,RTC_SECONDS);
1229                         CMOS_WRITE(real_minutes,RTC_MINUTES);
1230                 } else {
1231                         printk(KERN_WARNING
1232                                "set_rtc_mmss: can't update from %d to %d\n",
1233                                chip_minutes, real_minutes);
1234                         retval = -1;
1235                 }
1236
1237                 CMOS_WRITE(save_control, RTC_CONTROL);
1238                 CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
1239                 spin_unlock_irqrestore(&rtc_lock, flags);
1240
1241                 return retval;
1242         }
1243 }
1244
1245 #define RTC_IS_OPEN             0x01    /* means /dev/rtc is in use     */
1246 static unsigned char mini_rtc_status;   /* bitmapped status byte.       */
1247
1248 #define FEBRUARY        2
1249 #define STARTOFTIME     1970
1250 #define SECDAY          86400L
1251 #define SECYR           (SECDAY * 365)
1252 #define leapyear(year)          ((year) % 4 == 0 && \
1253                                  ((year) % 100 != 0 || (year) % 400 == 0))
1254 #define days_in_year(a)         (leapyear(a) ? 366 : 365)
1255 #define days_in_month(a)        (month_days[(a) - 1])
1256
1257 static int month_days[12] = {
1258         31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
1259 };
1260
1261 /*
1262  * This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
1263  */
1264 static void GregorianDay(struct rtc_time * tm)
1265 {
1266         int leapsToDate;
1267         int lastYear;
1268         int day;
1269         int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
1270
1271         lastYear = tm->tm_year - 1;
1272
1273         /*
1274          * Number of leap corrections to apply up to end of last year
1275          */
1276         leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
1277
1278         /*
1279          * This year is a leap year if it is divisible by 4 except when it is
1280          * divisible by 100 unless it is divisible by 400
1281          *
1282          * e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 was
1283          */
1284         day = tm->tm_mon > 2 && leapyear(tm->tm_year);
1285
1286         day += lastYear*365 + leapsToDate + MonthOffset[tm->tm_mon-1] +
1287                    tm->tm_mday;
1288
1289         tm->tm_wday = day % 7;
1290 }
1291
1292 static void to_tm(int tim, struct rtc_time *tm)
1293 {
1294         register int    i;
1295         register long   hms, day;
1296
1297         day = tim / SECDAY;
1298         hms = tim % SECDAY;
1299
1300         /* Hours, minutes, seconds are easy */
1301         tm->tm_hour = hms / 3600;
1302         tm->tm_min = (hms % 3600) / 60;
1303         tm->tm_sec = (hms % 3600) % 60;
1304
1305         /* Number of years in days */
1306         for (i = STARTOFTIME; day >= days_in_year(i); i++)
1307                 day -= days_in_year(i);
1308         tm->tm_year = i;
1309
1310         /* Number of months in days left */
1311         if (leapyear(tm->tm_year))
1312                 days_in_month(FEBRUARY) = 29;
1313         for (i = 1; day >= days_in_month(i); i++)
1314                 day -= days_in_month(i);
1315         days_in_month(FEBRUARY) = 28;
1316         tm->tm_mon = i;
1317
1318         /* Days are what is left over (+1) from all that. */
1319         tm->tm_mday = day + 1;
1320
1321         /*
1322          * Determine the day of week
1323          */
1324         GregorianDay(tm);
1325 }
1326
1327 /* Both Starfire and SUN4V give us seconds since Jan 1st, 1970,
1328  * aka Unix time.  So we have to convert to/from rtc_time.
1329  */
1330 static void starfire_get_rtc_time(struct rtc_time *time)
1331 {
1332         u32 seconds = starfire_get_time();
1333
1334         to_tm(seconds, time);
1335         time->tm_year -= 1900;
1336         time->tm_mon -= 1;
1337 }
1338
1339 static int starfire_set_rtc_time(struct rtc_time *time)
1340 {
1341         u32 seconds = mktime(time->tm_year + 1900, time->tm_mon + 1,
1342                              time->tm_mday, time->tm_hour,
1343                              time->tm_min, time->tm_sec);
1344
1345         return starfire_set_time(seconds);
1346 }
1347
1348 static void hypervisor_get_rtc_time(struct rtc_time *time)
1349 {
1350         u32 seconds = hypervisor_get_time();
1351
1352         to_tm(seconds, time);
1353         time->tm_year -= 1900;
1354         time->tm_mon -= 1;
1355 }
1356
1357 static int hypervisor_set_rtc_time(struct rtc_time *time)
1358 {
1359         u32 seconds = mktime(time->tm_year + 1900, time->tm_mon + 1,
1360                              time->tm_mday, time->tm_hour,
1361                              time->tm_min, time->tm_sec);
1362
1363         return hypervisor_set_time(seconds);
1364 }
1365
1366 #ifdef CONFIG_PCI
1367 static void bq4802_get_rtc_time(struct rtc_time *time)
1368 {
1369         unsigned char val = readb(bq4802_regs + 0x0e);
1370         unsigned int century;
1371
1372         writeb(val | 0x08, bq4802_regs + 0x0e);
1373
1374         time->tm_sec = readb(bq4802_regs + 0x00);
1375         time->tm_min = readb(bq4802_regs + 0x02);
1376         time->tm_hour = readb(bq4802_regs + 0x04);
1377         time->tm_mday = readb(bq4802_regs + 0x06);
1378         time->tm_mon = readb(bq4802_regs + 0x09);
1379         time->tm_year = readb(bq4802_regs + 0x0a);
1380         time->tm_wday = readb(bq4802_regs + 0x08);
1381         century = readb(bq4802_regs + 0x0f);
1382
1383         writeb(val, bq4802_regs + 0x0e);
1384
1385         BCD_TO_BIN(time->tm_sec);
1386         BCD_TO_BIN(time->tm_min);
1387         BCD_TO_BIN(time->tm_hour);
1388         BCD_TO_BIN(time->tm_mday);
1389         BCD_TO_BIN(time->tm_mon);
1390         BCD_TO_BIN(time->tm_year);
1391         BCD_TO_BIN(time->tm_wday);
1392         BCD_TO_BIN(century);
1393
1394         time->tm_year += (century * 100);
1395         time->tm_year -= 1900;
1396
1397         time->tm_mon--;
1398 }
1399
1400 static int bq4802_set_rtc_time(struct rtc_time *time)
1401 {
1402         unsigned char val = readb(bq4802_regs + 0x0e);
1403         unsigned char sec, min, hrs, day, mon, yrs, century;
1404         unsigned int year;
1405
1406         year = time->tm_year + 1900;
1407         century = year / 100;
1408         yrs = year % 100;
1409
1410         mon = time->tm_mon + 1;   /* tm_mon starts at zero */
1411         day = time->tm_mday;
1412         hrs = time->tm_hour;
1413         min = time->tm_min;
1414         sec = time->tm_sec;
1415
1416         BIN_TO_BCD(sec);
1417         BIN_TO_BCD(min);
1418         BIN_TO_BCD(hrs);
1419         BIN_TO_BCD(day);
1420         BIN_TO_BCD(mon);
1421         BIN_TO_BCD(yrs);
1422         BIN_TO_BCD(century);
1423
1424         writeb(val | 0x08, bq4802_regs + 0x0e);
1425
1426         writeb(sec, bq4802_regs + 0x00);
1427         writeb(min, bq4802_regs + 0x02);
1428         writeb(hrs, bq4802_regs + 0x04);
1429         writeb(day, bq4802_regs + 0x06);
1430         writeb(mon, bq4802_regs + 0x09);
1431         writeb(yrs, bq4802_regs + 0x0a);
1432         writeb(century, bq4802_regs + 0x0f);
1433
1434         writeb(val, bq4802_regs + 0x0e);
1435
1436         return 0;
1437 }
1438
1439 static void cmos_get_rtc_time(struct rtc_time *rtc_tm)
1440 {
1441         unsigned char ctrl;
1442
1443         rtc_tm->tm_sec = CMOS_READ(RTC_SECONDS);
1444         rtc_tm->tm_min = CMOS_READ(RTC_MINUTES);
1445         rtc_tm->tm_hour = CMOS_READ(RTC_HOURS);
1446         rtc_tm->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH);
1447         rtc_tm->tm_mon = CMOS_READ(RTC_MONTH);
1448         rtc_tm->tm_year = CMOS_READ(RTC_YEAR);
1449         rtc_tm->tm_wday = CMOS_READ(RTC_DAY_OF_WEEK);
1450
1451         ctrl = CMOS_READ(RTC_CONTROL);
1452         if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1453                 BCD_TO_BIN(rtc_tm->tm_sec);
1454                 BCD_TO_BIN(rtc_tm->tm_min);
1455                 BCD_TO_BIN(rtc_tm->tm_hour);
1456                 BCD_TO_BIN(rtc_tm->tm_mday);
1457                 BCD_TO_BIN(rtc_tm->tm_mon);
1458                 BCD_TO_BIN(rtc_tm->tm_year);
1459                 BCD_TO_BIN(rtc_tm->tm_wday);
1460         }
1461
1462         if (rtc_tm->tm_year <= 69)
1463                 rtc_tm->tm_year += 100;
1464
1465         rtc_tm->tm_mon--;
1466 }
1467
1468 static int cmos_set_rtc_time(struct rtc_time *rtc_tm)
1469 {
1470         unsigned char mon, day, hrs, min, sec;
1471         unsigned char save_control, save_freq_select;
1472         unsigned int yrs;
1473
1474         yrs = rtc_tm->tm_year;
1475         mon = rtc_tm->tm_mon + 1;
1476         day = rtc_tm->tm_mday;
1477         hrs = rtc_tm->tm_hour;
1478         min = rtc_tm->tm_min;
1479         sec = rtc_tm->tm_sec;
1480
1481         if (yrs >= 100)
1482                 yrs -= 100;
1483
1484         if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1485                 BIN_TO_BCD(sec);
1486                 BIN_TO_BCD(min);
1487                 BIN_TO_BCD(hrs);
1488                 BIN_TO_BCD(day);
1489                 BIN_TO_BCD(mon);
1490                 BIN_TO_BCD(yrs);
1491         }
1492
1493         save_control = CMOS_READ(RTC_CONTROL);
1494         CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
1495         save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
1496         CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
1497
1498         CMOS_WRITE(yrs, RTC_YEAR);
1499         CMOS_WRITE(mon, RTC_MONTH);
1500         CMOS_WRITE(day, RTC_DAY_OF_MONTH);
1501         CMOS_WRITE(hrs, RTC_HOURS);
1502         CMOS_WRITE(min, RTC_MINUTES);
1503         CMOS_WRITE(sec, RTC_SECONDS);
1504
1505         CMOS_WRITE(save_control, RTC_CONTROL);
1506         CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
1507
1508         return 0;
1509 }
1510 #endif /* CONFIG_PCI */
1511
1512 struct mini_rtc_ops {
1513         void (*get_rtc_time)(struct rtc_time *);
1514         int (*set_rtc_time)(struct rtc_time *);
1515 };
1516
1517 static struct mini_rtc_ops starfire_rtc_ops = {
1518         .get_rtc_time = starfire_get_rtc_time,
1519         .set_rtc_time = starfire_set_rtc_time,
1520 };
1521
1522 static struct mini_rtc_ops hypervisor_rtc_ops = {
1523         .get_rtc_time = hypervisor_get_rtc_time,
1524         .set_rtc_time = hypervisor_set_rtc_time,
1525 };
1526
1527 #ifdef CONFIG_PCI
1528 static struct mini_rtc_ops bq4802_rtc_ops = {
1529         .get_rtc_time = bq4802_get_rtc_time,
1530         .set_rtc_time = bq4802_set_rtc_time,
1531 };
1532
1533 static struct mini_rtc_ops cmos_rtc_ops = {
1534         .get_rtc_time = cmos_get_rtc_time,
1535         .set_rtc_time = cmos_set_rtc_time,
1536 };
1537 #endif /* CONFIG_PCI */
1538
1539 static struct mini_rtc_ops *mini_rtc_ops;
1540
1541 static inline void mini_get_rtc_time(struct rtc_time *time)
1542 {
1543         unsigned long flags;
1544
1545         spin_lock_irqsave(&rtc_lock, flags);
1546         mini_rtc_ops->get_rtc_time(time);
1547         spin_unlock_irqrestore(&rtc_lock, flags);
1548 }
1549
1550 static inline int mini_set_rtc_time(struct rtc_time *time)
1551 {
1552         unsigned long flags;
1553         int err;
1554
1555         spin_lock_irqsave(&rtc_lock, flags);
1556         err = mini_rtc_ops->set_rtc_time(time);
1557         spin_unlock_irqrestore(&rtc_lock, flags);
1558
1559         return err;
1560 }
1561
1562 static int mini_rtc_ioctl(struct inode *inode, struct file *file,
1563                           unsigned int cmd, unsigned long arg)
1564 {
1565         struct rtc_time wtime;
1566         void __user *argp = (void __user *)arg;
1567
1568         switch (cmd) {
1569
1570         case RTC_PLL_GET:
1571                 return -EINVAL;
1572
1573         case RTC_PLL_SET:
1574                 return -EINVAL;
1575
1576         case RTC_UIE_OFF:       /* disable ints from RTC updates.       */
1577                 return 0;
1578
1579         case RTC_UIE_ON:        /* enable ints for RTC updates. */
1580                 return -EINVAL;
1581
1582         case RTC_RD_TIME:       /* Read the time/date from RTC  */
1583                 /* this doesn't get week-day, who cares */
1584                 memset(&wtime, 0, sizeof(wtime));
1585                 mini_get_rtc_time(&wtime);
1586
1587                 return copy_to_user(argp, &wtime, sizeof(wtime)) ? -EFAULT : 0;
1588
1589         case RTC_SET_TIME:      /* Set the RTC */
1590             {
1591                 int year, days;
1592
1593                 if (!capable(CAP_SYS_TIME))
1594                         return -EACCES;
1595
1596                 if (copy_from_user(&wtime, argp, sizeof(wtime)))
1597                         return -EFAULT;
1598
1599                 year = wtime.tm_year + 1900;
1600                 days = month_days[wtime.tm_mon] +
1601                        ((wtime.tm_mon == 1) && leapyear(year));
1602
1603                 if ((wtime.tm_mon < 0 || wtime.tm_mon > 11) ||
1604                     (wtime.tm_mday < 1))
1605                         return -EINVAL;
1606
1607                 if (wtime.tm_mday < 0 || wtime.tm_mday > days)
1608                         return -EINVAL;
1609
1610                 if (wtime.tm_hour < 0 || wtime.tm_hour >= 24 ||
1611                     wtime.tm_min < 0 || wtime.tm_min >= 60 ||
1612                     wtime.tm_sec < 0 || wtime.tm_sec >= 60)
1613                         return -EINVAL;
1614
1615                 return mini_set_rtc_time(&wtime);
1616             }
1617         }
1618
1619         return -EINVAL;
1620 }
1621
1622 static int mini_rtc_open(struct inode *inode, struct file *file)
1623 {
1624         if (mini_rtc_status & RTC_IS_OPEN)
1625                 return -EBUSY;
1626
1627         mini_rtc_status |= RTC_IS_OPEN;
1628
1629         return 0;
1630 }
1631
1632 static int mini_rtc_release(struct inode *inode, struct file *file)
1633 {
1634         mini_rtc_status &= ~RTC_IS_OPEN;
1635         return 0;
1636 }
1637
1638
1639 static const struct file_operations mini_rtc_fops = {
1640         .owner          = THIS_MODULE,
1641         .ioctl          = mini_rtc_ioctl,
1642         .open           = mini_rtc_open,
1643         .release        = mini_rtc_release,
1644 };
1645
1646 static struct miscdevice rtc_mini_dev =
1647 {
1648         .minor          = RTC_MINOR,
1649         .name           = "rtc",
1650         .fops           = &mini_rtc_fops,
1651 };
1652
1653 static int __init rtc_mini_init(void)
1654 {
1655         int retval;
1656
1657         if (tlb_type == hypervisor)
1658                 mini_rtc_ops = &hypervisor_rtc_ops;
1659         else if (this_is_starfire)
1660                 mini_rtc_ops = &starfire_rtc_ops;
1661 #ifdef CONFIG_PCI
1662         else if (bq4802_regs)
1663                 mini_rtc_ops = &bq4802_rtc_ops;
1664         else if (ds1287_regs)
1665                 mini_rtc_ops = &cmos_rtc_ops;
1666 #endif /* CONFIG_PCI */
1667         else
1668                 return -ENODEV;
1669
1670         printk(KERN_INFO "Mini RTC Driver\n");
1671
1672         retval = misc_register(&rtc_mini_dev);
1673         if (retval < 0)
1674                 return retval;
1675
1676         return 0;
1677 }
1678
1679 static void __exit rtc_mini_exit(void)
1680 {
1681         misc_deregister(&rtc_mini_dev);
1682 }
1683
1684
1685 module_init(rtc_mini_init);
1686 module_exit(rtc_mini_exit);