Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / drivers / char / rtc.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *      Real Time Clock interface for Linux
4  *
5  *      Copyright (C) 1996 Paul Gortmaker
6  *
7  *      This driver allows use of the real time clock (built into
8  *      nearly all computers) from user space. It exports the /dev/rtc
9  *      interface supporting various ioctl() and also the
10  *      /proc/driver/rtc pseudo-file for status information.
11  *
12  *      The ioctls can be used to set the interrupt behaviour and
13  *      generation rate from the RTC via IRQ 8. Then the /dev/rtc
14  *      interface can be used to make use of these timer interrupts,
15  *      be they interval or alarm based.
16  *
17  *      The /dev/rtc interface will block on reads until an interrupt
18  *      has been received. If a RTC interrupt has already happened,
19  *      it will output an unsigned long and then block. The output value
20  *      contains the interrupt status in the low byte and the number of
21  *      interrupts since the last read in the remaining high bytes. The
22  *      /dev/rtc interface can also be used with the select(2) call.
23  *
24  *      Based on other minimal char device drivers, like Alan's
25  *      watchdog, Ted's random, etc. etc.
26  *
27  *      1.07    Paul Gortmaker.
28  *      1.08    Miquel van Smoorenburg: disallow certain things on the
29  *              DEC Alpha as the CMOS clock is also used for other things.
30  *      1.09    Nikita Schmidt: epoch support and some Alpha cleanup.
31  *      1.09a   Pete Zaitcev: Sun SPARC
32  *      1.09b   Jeff Garzik: Modularize, init cleanup
33  *      1.09c   Jeff Garzik: SMP cleanup
34  *      1.10    Paul Barton-Davis: add support for async I/O
35  *      1.10a   Andrea Arcangeli: Alpha updates
36  *      1.10b   Andrew Morton: SMP lock fix
37  *      1.10c   Cesar Barros: SMP locking fixes and cleanup
38  *      1.10d   Paul Gortmaker: delete paranoia check in rtc_exit
39  *      1.10e   Maciej W. Rozycki: Handle DECstation's year weirdness.
40  *      1.11    Takashi Iwai: Kernel access functions
41  *                            rtc_register/rtc_unregister/rtc_control
42  *      1.11a   Daniele Bellucci: Audit create_proc_read_entry in rtc_init
43  *      1.12    Venkatesh Pallipadi: Hooks for emulating rtc on HPET base-timer
44  *              CONFIG_HPET_EMULATE_RTC
45  *      1.12a   Maciej W. Rozycki: Handle memory-mapped chips properly.
46  *      1.12ac  Alan Cox: Allow read access to the day of week register
47  *      1.12b   David John: Remove calls to the BKL.
48  */
49
50 #define RTC_VERSION             "1.12b"
51
52 /*
53  *      Note that *all* calls to CMOS_READ and CMOS_WRITE are done with
54  *      interrupts disabled. Due to the index-port/data-port (0x70/0x71)
55  *      design of the RTC, we don't want two different things trying to
56  *      get to it at once. (e.g. the periodic 11 min sync from
57  *      kernel/time/ntp.c vs. this driver.)
58  */
59
60 #include <linux/interrupt.h>
61 #include <linux/module.h>
62 #include <linux/kernel.h>
63 #include <linux/types.h>
64 #include <linux/miscdevice.h>
65 #include <linux/ioport.h>
66 #include <linux/fcntl.h>
67 #include <linux/mc146818rtc.h>
68 #include <linux/init.h>
69 #include <linux/poll.h>
70 #include <linux/proc_fs.h>
71 #include <linux/seq_file.h>
72 #include <linux/spinlock.h>
73 #include <linux/sched/signal.h>
74 #include <linux/sysctl.h>
75 #include <linux/wait.h>
76 #include <linux/bcd.h>
77 #include <linux/delay.h>
78 #include <linux/uaccess.h>
79 #include <linux/ratelimit.h>
80
81 #include <asm/current.h>
82
83 #ifdef CONFIG_X86
84 #include <asm/hpet.h>
85 #endif
86
87 #ifdef CONFIG_SPARC32
88 #include <linux/of.h>
89 #include <linux/of_device.h>
90 #include <asm/io.h>
91
92 static unsigned long rtc_port;
93 static int rtc_irq;
94 #endif
95
96 #ifdef  CONFIG_HPET_EMULATE_RTC
97 #undef  RTC_IRQ
98 #endif
99
100 #ifdef RTC_IRQ
101 static int rtc_has_irq = 1;
102 #endif
103
104 #ifndef CONFIG_HPET_EMULATE_RTC
105 #define is_hpet_enabled()                       0
106 #define hpet_set_alarm_time(hrs, min, sec)      0
107 #define hpet_set_periodic_freq(arg)             0
108 #define hpet_mask_rtc_irq_bit(arg)              0
109 #define hpet_set_rtc_irq_bit(arg)               0
110 #define hpet_rtc_timer_init()                   do { } while (0)
111 #define hpet_rtc_dropped_irq()                  0
112 #define hpet_register_irq_handler(h)            ({ 0; })
113 #define hpet_unregister_irq_handler(h)          ({ 0; })
114 #ifdef RTC_IRQ
115 static irqreturn_t hpet_rtc_interrupt(int irq, void *dev_id)
116 {
117         return 0;
118 }
119 #endif
120 #endif
121
122 /*
123  *      We sponge a minor off of the misc major. No need slurping
124  *      up another valuable major dev number for this. If you add
125  *      an ioctl, make sure you don't conflict with SPARC's RTC
126  *      ioctls.
127  */
128
129 static struct fasync_struct *rtc_async_queue;
130
131 static DECLARE_WAIT_QUEUE_HEAD(rtc_wait);
132
133 #ifdef RTC_IRQ
134 static void rtc_dropped_irq(struct timer_list *unused);
135
136 static DEFINE_TIMER(rtc_irq_timer, rtc_dropped_irq);
137 #endif
138
139 static ssize_t rtc_read(struct file *file, char __user *buf,
140                         size_t count, loff_t *ppos);
141
142 static long rtc_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
143 static void rtc_get_rtc_time(struct rtc_time *rtc_tm);
144
145 #ifdef RTC_IRQ
146 static __poll_t rtc_poll(struct file *file, poll_table *wait);
147 #endif
148
149 static void get_rtc_alm_time(struct rtc_time *alm_tm);
150 #ifdef RTC_IRQ
151 static void set_rtc_irq_bit_locked(unsigned char bit);
152 static void mask_rtc_irq_bit_locked(unsigned char bit);
153
154 static inline void set_rtc_irq_bit(unsigned char bit)
155 {
156         spin_lock_irq(&rtc_lock);
157         set_rtc_irq_bit_locked(bit);
158         spin_unlock_irq(&rtc_lock);
159 }
160
161 static void mask_rtc_irq_bit(unsigned char bit)
162 {
163         spin_lock_irq(&rtc_lock);
164         mask_rtc_irq_bit_locked(bit);
165         spin_unlock_irq(&rtc_lock);
166 }
167 #endif
168
169 #ifdef CONFIG_PROC_FS
170 static int rtc_proc_show(struct seq_file *seq, void *v);
171 #endif
172
173 /*
174  *      Bits in rtc_status. (6 bits of room for future expansion)
175  */
176
177 #define RTC_IS_OPEN             0x01    /* means /dev/rtc is in use     */
178 #define RTC_TIMER_ON            0x02    /* missed irq timer active      */
179
180 /*
181  * rtc_status is never changed by rtc_interrupt, and ioctl/open/close is
182  * protected by the spin lock rtc_lock. However, ioctl can still disable the
183  * timer in rtc_status and then with del_timer after the interrupt has read
184  * rtc_status but before mod_timer is called, which would then reenable the
185  * timer (but you would need to have an awful timing before you'd trip on it)
186  */
187 static unsigned long rtc_status;        /* bitmapped status byte.       */
188 static unsigned long rtc_freq;          /* Current periodic IRQ rate    */
189 static unsigned long rtc_irq_data;      /* our output to the world      */
190 static unsigned long rtc_max_user_freq = 64; /* > this, need CAP_SYS_RESOURCE */
191
192 /*
193  *      If this driver ever becomes modularised, it will be really nice
194  *      to make the epoch retain its value across module reload...
195  */
196
197 static unsigned long epoch = 1900;      /* year corresponding to 0x00   */
198
199 static const unsigned char days_in_mo[] =
200 {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
201
202 /*
203  * Returns true if a clock update is in progress
204  */
205 static inline unsigned char rtc_is_updating(void)
206 {
207         unsigned long flags;
208         unsigned char uip;
209
210         spin_lock_irqsave(&rtc_lock, flags);
211         uip = (CMOS_READ(RTC_FREQ_SELECT) & RTC_UIP);
212         spin_unlock_irqrestore(&rtc_lock, flags);
213         return uip;
214 }
215
216 #ifdef RTC_IRQ
217 /*
218  *      A very tiny interrupt handler. It runs with interrupts disabled,
219  *      but there is possibility of conflicting with the set_rtc_mmss()
220  *      call (the rtc irq and the timer irq can easily run at the same
221  *      time in two different CPUs). So we need to serialize
222  *      accesses to the chip with the rtc_lock spinlock that each
223  *      architecture should implement in the timer code.
224  *      (See ./arch/XXXX/kernel/time.c for the set_rtc_mmss() function.)
225  */
226
227 static irqreturn_t rtc_interrupt(int irq, void *dev_id)
228 {
229         /*
230          *      Can be an alarm interrupt, update complete interrupt,
231          *      or a periodic interrupt. We store the status in the
232          *      low byte and the number of interrupts received since
233          *      the last read in the remainder of rtc_irq_data.
234          */
235
236         spin_lock(&rtc_lock);
237         rtc_irq_data += 0x100;
238         rtc_irq_data &= ~0xff;
239         if (is_hpet_enabled()) {
240                 /*
241                  * In this case it is HPET RTC interrupt handler
242                  * calling us, with the interrupt information
243                  * passed as arg1, instead of irq.
244                  */
245                 rtc_irq_data |= (unsigned long)irq & 0xF0;
246         } else {
247                 rtc_irq_data |= (CMOS_READ(RTC_INTR_FLAGS) & 0xF0);
248         }
249
250         if (rtc_status & RTC_TIMER_ON)
251                 mod_timer(&rtc_irq_timer, jiffies + HZ/rtc_freq + 2*HZ/100);
252
253         spin_unlock(&rtc_lock);
254
255         wake_up_interruptible(&rtc_wait);
256
257         kill_fasync(&rtc_async_queue, SIGIO, POLL_IN);
258
259         return IRQ_HANDLED;
260 }
261 #endif
262
263 /*
264  * sysctl-tuning infrastructure.
265  */
266 static struct ctl_table rtc_table[] = {
267         {
268                 .procname       = "max-user-freq",
269                 .data           = &rtc_max_user_freq,
270                 .maxlen         = sizeof(int),
271                 .mode           = 0644,
272                 .proc_handler   = proc_dointvec,
273         },
274         { }
275 };
276
277 static struct ctl_table rtc_root[] = {
278         {
279                 .procname       = "rtc",
280                 .mode           = 0555,
281                 .child          = rtc_table,
282         },
283         { }
284 };
285
286 static struct ctl_table dev_root[] = {
287         {
288                 .procname       = "dev",
289                 .mode           = 0555,
290                 .child          = rtc_root,
291         },
292         { }
293 };
294
295 static struct ctl_table_header *sysctl_header;
296
297 static int __init init_sysctl(void)
298 {
299     sysctl_header = register_sysctl_table(dev_root);
300     return 0;
301 }
302
303 static void __exit cleanup_sysctl(void)
304 {
305     unregister_sysctl_table(sysctl_header);
306 }
307
308 /*
309  *      Now all the various file operations that we export.
310  */
311
312 static ssize_t rtc_read(struct file *file, char __user *buf,
313                         size_t count, loff_t *ppos)
314 {
315 #ifndef RTC_IRQ
316         return -EIO;
317 #else
318         DECLARE_WAITQUEUE(wait, current);
319         unsigned long data;
320         ssize_t retval;
321
322         if (rtc_has_irq == 0)
323                 return -EIO;
324
325         /*
326          * Historically this function used to assume that sizeof(unsigned long)
327          * is the same in userspace and kernelspace.  This lead to problems
328          * for configurations with multiple ABIs such a the MIPS o32 and 64
329          * ABIs supported on the same kernel.  So now we support read of both
330          * 4 and 8 bytes and assume that's the sizeof(unsigned long) in the
331          * userspace ABI.
332          */
333         if (count != sizeof(unsigned int) && count !=  sizeof(unsigned long))
334                 return -EINVAL;
335
336         add_wait_queue(&rtc_wait, &wait);
337
338         do {
339                 /* First make it right. Then make it fast. Putting this whole
340                  * block within the parentheses of a while would be too
341                  * confusing. And no, xchg() is not the answer. */
342
343                 __set_current_state(TASK_INTERRUPTIBLE);
344
345                 spin_lock_irq(&rtc_lock);
346                 data = rtc_irq_data;
347                 rtc_irq_data = 0;
348                 spin_unlock_irq(&rtc_lock);
349
350                 if (data != 0)
351                         break;
352
353                 if (file->f_flags & O_NONBLOCK) {
354                         retval = -EAGAIN;
355                         goto out;
356                 }
357                 if (signal_pending(current)) {
358                         retval = -ERESTARTSYS;
359                         goto out;
360                 }
361                 schedule();
362         } while (1);
363
364         if (count == sizeof(unsigned int)) {
365                 retval = put_user(data,
366                                   (unsigned int __user *)buf) ?: sizeof(int);
367         } else {
368                 retval = put_user(data,
369                                   (unsigned long __user *)buf) ?: sizeof(long);
370         }
371         if (!retval)
372                 retval = count;
373  out:
374         __set_current_state(TASK_RUNNING);
375         remove_wait_queue(&rtc_wait, &wait);
376
377         return retval;
378 #endif
379 }
380
381 static int rtc_do_ioctl(unsigned int cmd, unsigned long arg, int kernel)
382 {
383         struct rtc_time wtime;
384
385 #ifdef RTC_IRQ
386         if (rtc_has_irq == 0) {
387                 switch (cmd) {
388                 case RTC_AIE_OFF:
389                 case RTC_AIE_ON:
390                 case RTC_PIE_OFF:
391                 case RTC_PIE_ON:
392                 case RTC_UIE_OFF:
393                 case RTC_UIE_ON:
394                 case RTC_IRQP_READ:
395                 case RTC_IRQP_SET:
396                         return -EINVAL;
397                 }
398         }
399 #endif
400
401         switch (cmd) {
402 #ifdef RTC_IRQ
403         case RTC_AIE_OFF:       /* Mask alarm int. enab. bit    */
404         {
405                 mask_rtc_irq_bit(RTC_AIE);
406                 return 0;
407         }
408         case RTC_AIE_ON:        /* Allow alarm interrupts.      */
409         {
410                 set_rtc_irq_bit(RTC_AIE);
411                 return 0;
412         }
413         case RTC_PIE_OFF:       /* Mask periodic int. enab. bit */
414         {
415                 /* can be called from isr via rtc_control() */
416                 unsigned long flags;
417
418                 spin_lock_irqsave(&rtc_lock, flags);
419                 mask_rtc_irq_bit_locked(RTC_PIE);
420                 if (rtc_status & RTC_TIMER_ON) {
421                         rtc_status &= ~RTC_TIMER_ON;
422                         del_timer(&rtc_irq_timer);
423                 }
424                 spin_unlock_irqrestore(&rtc_lock, flags);
425
426                 return 0;
427         }
428         case RTC_PIE_ON:        /* Allow periodic ints          */
429         {
430                 /* can be called from isr via rtc_control() */
431                 unsigned long flags;
432
433                 /*
434                  * We don't really want Joe User enabling more
435                  * than 64Hz of interrupts on a multi-user machine.
436                  */
437                 if (!kernel && (rtc_freq > rtc_max_user_freq) &&
438                                                 (!capable(CAP_SYS_RESOURCE)))
439                         return -EACCES;
440
441                 spin_lock_irqsave(&rtc_lock, flags);
442                 if (!(rtc_status & RTC_TIMER_ON)) {
443                         mod_timer(&rtc_irq_timer, jiffies + HZ/rtc_freq +
444                                         2*HZ/100);
445                         rtc_status |= RTC_TIMER_ON;
446                 }
447                 set_rtc_irq_bit_locked(RTC_PIE);
448                 spin_unlock_irqrestore(&rtc_lock, flags);
449
450                 return 0;
451         }
452         case RTC_UIE_OFF:       /* Mask ints from RTC updates.  */
453         {
454                 mask_rtc_irq_bit(RTC_UIE);
455                 return 0;
456         }
457         case RTC_UIE_ON:        /* Allow ints for RTC updates.  */
458         {
459                 set_rtc_irq_bit(RTC_UIE);
460                 return 0;
461         }
462 #endif
463         case RTC_ALM_READ:      /* Read the present alarm time */
464         {
465                 /*
466                  * This returns a struct rtc_time. Reading >= 0xc0
467                  * means "don't care" or "match all". Only the tm_hour,
468                  * tm_min, and tm_sec values are filled in.
469                  */
470                 memset(&wtime, 0, sizeof(struct rtc_time));
471                 get_rtc_alm_time(&wtime);
472                 break;
473         }
474         case RTC_ALM_SET:       /* Store a time into the alarm */
475         {
476                 /*
477                  * This expects a struct rtc_time. Writing 0xff means
478                  * "don't care" or "match all". Only the tm_hour,
479                  * tm_min and tm_sec are used.
480                  */
481                 unsigned char hrs, min, sec;
482                 struct rtc_time alm_tm;
483
484                 if (copy_from_user(&alm_tm, (struct rtc_time __user *)arg,
485                                    sizeof(struct rtc_time)))
486                         return -EFAULT;
487
488                 hrs = alm_tm.tm_hour;
489                 min = alm_tm.tm_min;
490                 sec = alm_tm.tm_sec;
491
492                 spin_lock_irq(&rtc_lock);
493                 if (hpet_set_alarm_time(hrs, min, sec)) {
494                         /*
495                          * Fallthru and set alarm time in CMOS too,
496                          * so that we will get proper value in RTC_ALM_READ
497                          */
498                 }
499                 if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) ||
500                                                         RTC_ALWAYS_BCD) {
501                         if (sec < 60)
502                                 sec = bin2bcd(sec);
503                         else
504                                 sec = 0xff;
505
506                         if (min < 60)
507                                 min = bin2bcd(min);
508                         else
509                                 min = 0xff;
510
511                         if (hrs < 24)
512                                 hrs = bin2bcd(hrs);
513                         else
514                                 hrs = 0xff;
515                 }
516                 CMOS_WRITE(hrs, RTC_HOURS_ALARM);
517                 CMOS_WRITE(min, RTC_MINUTES_ALARM);
518                 CMOS_WRITE(sec, RTC_SECONDS_ALARM);
519                 spin_unlock_irq(&rtc_lock);
520
521                 return 0;
522         }
523         case RTC_RD_TIME:       /* Read the time/date from RTC  */
524         {
525                 memset(&wtime, 0, sizeof(struct rtc_time));
526                 rtc_get_rtc_time(&wtime);
527                 break;
528         }
529         case RTC_SET_TIME:      /* Set the RTC */
530         {
531                 struct rtc_time rtc_tm;
532                 unsigned char mon, day, hrs, min, sec, leap_yr;
533                 unsigned char save_control, save_freq_select;
534                 unsigned int yrs;
535 #ifdef CONFIG_MACH_DECSTATION
536                 unsigned int real_yrs;
537 #endif
538
539                 if (!capable(CAP_SYS_TIME))
540                         return -EACCES;
541
542                 if (copy_from_user(&rtc_tm, (struct rtc_time __user *)arg,
543                                    sizeof(struct rtc_time)))
544                         return -EFAULT;
545
546                 yrs = rtc_tm.tm_year + 1900;
547                 mon = rtc_tm.tm_mon + 1;   /* tm_mon starts at zero */
548                 day = rtc_tm.tm_mday;
549                 hrs = rtc_tm.tm_hour;
550                 min = rtc_tm.tm_min;
551                 sec = rtc_tm.tm_sec;
552
553                 if (yrs < 1970)
554                         return -EINVAL;
555
556                 leap_yr = ((!(yrs % 4) && (yrs % 100)) || !(yrs % 400));
557
558                 if ((mon > 12) || (day == 0))
559                         return -EINVAL;
560
561                 if (day > (days_in_mo[mon] + ((mon == 2) && leap_yr)))
562                         return -EINVAL;
563
564                 if ((hrs >= 24) || (min >= 60) || (sec >= 60))
565                         return -EINVAL;
566
567                 yrs -= epoch;
568                 if (yrs > 255)          /* They are unsigned */
569                         return -EINVAL;
570
571                 spin_lock_irq(&rtc_lock);
572 #ifdef CONFIG_MACH_DECSTATION
573                 real_yrs = yrs;
574                 yrs = 72;
575
576                 /*
577                  * We want to keep the year set to 73 until March
578                  * for non-leap years, so that Feb, 29th is handled
579                  * correctly.
580                  */
581                 if (!leap_yr && mon < 3) {
582                         real_yrs--;
583                         yrs = 73;
584                 }
585 #endif
586                 /* These limits and adjustments are independent of
587                  * whether the chip is in binary mode or not.
588                  */
589                 if (yrs > 169) {
590                         spin_unlock_irq(&rtc_lock);
591                         return -EINVAL;
592                 }
593                 if (yrs >= 100)
594                         yrs -= 100;
595
596                 if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY)
597                     || RTC_ALWAYS_BCD) {
598                         sec = bin2bcd(sec);
599                         min = bin2bcd(min);
600                         hrs = bin2bcd(hrs);
601                         day = bin2bcd(day);
602                         mon = bin2bcd(mon);
603                         yrs = bin2bcd(yrs);
604                 }
605
606                 save_control = CMOS_READ(RTC_CONTROL);
607                 CMOS_WRITE((save_control|RTC_SET), RTC_CONTROL);
608                 save_freq_select = CMOS_READ(RTC_FREQ_SELECT);
609                 CMOS_WRITE((save_freq_select|RTC_DIV_RESET2), RTC_FREQ_SELECT);
610
611 #ifdef CONFIG_MACH_DECSTATION
612                 CMOS_WRITE(real_yrs, RTC_DEC_YEAR);
613 #endif
614                 CMOS_WRITE(yrs, RTC_YEAR);
615                 CMOS_WRITE(mon, RTC_MONTH);
616                 CMOS_WRITE(day, RTC_DAY_OF_MONTH);
617                 CMOS_WRITE(hrs, RTC_HOURS);
618                 CMOS_WRITE(min, RTC_MINUTES);
619                 CMOS_WRITE(sec, RTC_SECONDS);
620
621                 CMOS_WRITE(save_control, RTC_CONTROL);
622                 CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT);
623
624                 spin_unlock_irq(&rtc_lock);
625                 return 0;
626         }
627 #ifdef RTC_IRQ
628         case RTC_IRQP_READ:     /* Read the periodic IRQ rate.  */
629         {
630                 return put_user(rtc_freq, (unsigned long __user *)arg);
631         }
632         case RTC_IRQP_SET:      /* Set periodic IRQ rate.       */
633         {
634                 int tmp = 0;
635                 unsigned char val;
636                 /* can be called from isr via rtc_control() */
637                 unsigned long flags;
638
639                 /*
640                  * The max we can do is 8192Hz.
641                  */
642                 if ((arg < 2) || (arg > 8192))
643                         return -EINVAL;
644                 /*
645                  * We don't really want Joe User generating more
646                  * than 64Hz of interrupts on a multi-user machine.
647                  */
648                 if (!kernel && (arg > rtc_max_user_freq) &&
649                                         !capable(CAP_SYS_RESOURCE))
650                         return -EACCES;
651
652                 while (arg > (1<<tmp))
653                         tmp++;
654
655                 /*
656                  * Check that the input was really a power of 2.
657                  */
658                 if (arg != (1<<tmp))
659                         return -EINVAL;
660
661                 rtc_freq = arg;
662
663                 spin_lock_irqsave(&rtc_lock, flags);
664                 if (hpet_set_periodic_freq(arg)) {
665                         spin_unlock_irqrestore(&rtc_lock, flags);
666                         return 0;
667                 }
668
669                 val = CMOS_READ(RTC_FREQ_SELECT) & 0xf0;
670                 val |= (16 - tmp);
671                 CMOS_WRITE(val, RTC_FREQ_SELECT);
672                 spin_unlock_irqrestore(&rtc_lock, flags);
673                 return 0;
674         }
675 #endif
676         case RTC_EPOCH_READ:    /* Read the epoch.      */
677         {
678                 return put_user(epoch, (unsigned long __user *)arg);
679         }
680         case RTC_EPOCH_SET:     /* Set the epoch.       */
681         {
682                 /*
683                  * There were no RTC clocks before 1900.
684                  */
685                 if (arg < 1900)
686                         return -EINVAL;
687
688                 if (!capable(CAP_SYS_TIME))
689                         return -EACCES;
690
691                 epoch = arg;
692                 return 0;
693         }
694         default:
695                 return -ENOTTY;
696         }
697         return copy_to_user((void __user *)arg,
698                             &wtime, sizeof wtime) ? -EFAULT : 0;
699 }
700
701 static long rtc_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
702 {
703         long ret;
704         ret = rtc_do_ioctl(cmd, arg, 0);
705         return ret;
706 }
707
708 /*
709  *      We enforce only one user at a time here with the open/close.
710  *      Also clear the previous interrupt data on an open, and clean
711  *      up things on a close.
712  */
713 static int rtc_open(struct inode *inode, struct file *file)
714 {
715         spin_lock_irq(&rtc_lock);
716
717         if (rtc_status & RTC_IS_OPEN)
718                 goto out_busy;
719
720         rtc_status |= RTC_IS_OPEN;
721
722         rtc_irq_data = 0;
723         spin_unlock_irq(&rtc_lock);
724         return 0;
725
726 out_busy:
727         spin_unlock_irq(&rtc_lock);
728         return -EBUSY;
729 }
730
731 static int rtc_fasync(int fd, struct file *filp, int on)
732 {
733         return fasync_helper(fd, filp, on, &rtc_async_queue);
734 }
735
736 static int rtc_release(struct inode *inode, struct file *file)
737 {
738 #ifdef RTC_IRQ
739         unsigned char tmp;
740
741         if (rtc_has_irq == 0)
742                 goto no_irq;
743
744         /*
745          * Turn off all interrupts once the device is no longer
746          * in use, and clear the data.
747          */
748
749         spin_lock_irq(&rtc_lock);
750         if (!hpet_mask_rtc_irq_bit(RTC_PIE | RTC_AIE | RTC_UIE)) {
751                 tmp = CMOS_READ(RTC_CONTROL);
752                 tmp &=  ~RTC_PIE;
753                 tmp &=  ~RTC_AIE;
754                 tmp &=  ~RTC_UIE;
755                 CMOS_WRITE(tmp, RTC_CONTROL);
756                 CMOS_READ(RTC_INTR_FLAGS);
757         }
758         if (rtc_status & RTC_TIMER_ON) {
759                 rtc_status &= ~RTC_TIMER_ON;
760                 del_timer(&rtc_irq_timer);
761         }
762         spin_unlock_irq(&rtc_lock);
763
764 no_irq:
765 #endif
766
767         spin_lock_irq(&rtc_lock);
768         rtc_irq_data = 0;
769         rtc_status &= ~RTC_IS_OPEN;
770         spin_unlock_irq(&rtc_lock);
771
772         return 0;
773 }
774
775 #ifdef RTC_IRQ
776 static __poll_t rtc_poll(struct file *file, poll_table *wait)
777 {
778         unsigned long l;
779
780         if (rtc_has_irq == 0)
781                 return 0;
782
783         poll_wait(file, &rtc_wait, wait);
784
785         spin_lock_irq(&rtc_lock);
786         l = rtc_irq_data;
787         spin_unlock_irq(&rtc_lock);
788
789         if (l != 0)
790                 return EPOLLIN | EPOLLRDNORM;
791         return 0;
792 }
793 #endif
794
795 /*
796  *      The various file operations we support.
797  */
798
799 static const struct file_operations rtc_fops = {
800         .owner          = THIS_MODULE,
801         .llseek         = no_llseek,
802         .read           = rtc_read,
803 #ifdef RTC_IRQ
804         .poll           = rtc_poll,
805 #endif
806         .unlocked_ioctl = rtc_ioctl,
807         .open           = rtc_open,
808         .release        = rtc_release,
809         .fasync         = rtc_fasync,
810 };
811
812 static struct miscdevice rtc_dev = {
813         .minor          = RTC_MINOR,
814         .name           = "rtc",
815         .fops           = &rtc_fops,
816 };
817
818 static resource_size_t rtc_size;
819
820 static struct resource * __init rtc_request_region(resource_size_t size)
821 {
822         struct resource *r;
823
824         if (RTC_IOMAPPED)
825                 r = request_region(RTC_PORT(0), size, "rtc");
826         else
827                 r = request_mem_region(RTC_PORT(0), size, "rtc");
828
829         if (r)
830                 rtc_size = size;
831
832         return r;
833 }
834
835 static void rtc_release_region(void)
836 {
837         if (RTC_IOMAPPED)
838                 release_region(RTC_PORT(0), rtc_size);
839         else
840                 release_mem_region(RTC_PORT(0), rtc_size);
841 }
842
843 static int __init rtc_init(void)
844 {
845 #ifdef CONFIG_PROC_FS
846         struct proc_dir_entry *ent;
847 #endif
848 #if defined(__alpha__) || defined(__mips__)
849         unsigned int year, ctrl;
850         char *guess = NULL;
851 #endif
852 #ifdef CONFIG_SPARC32
853         struct device_node *ebus_dp;
854         struct platform_device *op;
855 #else
856         void *r;
857 #ifdef RTC_IRQ
858         irq_handler_t rtc_int_handler_ptr;
859 #endif
860 #endif
861
862 #ifdef CONFIG_SPARC32
863         for_each_node_by_name(ebus_dp, "ebus") {
864                 struct device_node *dp;
865                 for_each_child_of_node(ebus_dp, dp) {
866                         if (of_node_name_eq(dp, "rtc")) {
867                                 op = of_find_device_by_node(dp);
868                                 if (op) {
869                                         rtc_port = op->resource[0].start;
870                                         rtc_irq = op->irqs[0];
871                                         goto found;
872                                 }
873                         }
874                 }
875         }
876         rtc_has_irq = 0;
877         printk(KERN_ERR "rtc_init: no PC rtc found\n");
878         return -EIO;
879
880 found:
881         if (!rtc_irq) {
882                 rtc_has_irq = 0;
883                 goto no_irq;
884         }
885
886         /*
887          * XXX Interrupt pin #7 in Espresso is shared between RTC and
888          * PCI Slot 2 INTA# (and some INTx# in Slot 1).
889          */
890         if (request_irq(rtc_irq, rtc_interrupt, IRQF_SHARED, "rtc",
891                         (void *)&rtc_port)) {
892                 rtc_has_irq = 0;
893                 printk(KERN_ERR "rtc: cannot register IRQ %d\n", rtc_irq);
894                 return -EIO;
895         }
896 no_irq:
897 #else
898         r = rtc_request_region(RTC_IO_EXTENT);
899
900         /*
901          * If we've already requested a smaller range (for example, because
902          * PNPBIOS or ACPI told us how the device is configured), the request
903          * above might fail because it's too big.
904          *
905          * If so, request just the range we actually use.
906          */
907         if (!r)
908                 r = rtc_request_region(RTC_IO_EXTENT_USED);
909         if (!r) {
910 #ifdef RTC_IRQ
911                 rtc_has_irq = 0;
912 #endif
913                 printk(KERN_ERR "rtc: I/O resource %lx is not free.\n",
914                        (long)(RTC_PORT(0)));
915                 return -EIO;
916         }
917
918 #ifdef RTC_IRQ
919         if (is_hpet_enabled()) {
920                 int err;
921
922                 rtc_int_handler_ptr = hpet_rtc_interrupt;
923                 err = hpet_register_irq_handler(rtc_interrupt);
924                 if (err != 0) {
925                         printk(KERN_WARNING "hpet_register_irq_handler failed "
926                                         "in rtc_init().");
927                         return err;
928                 }
929         } else {
930                 rtc_int_handler_ptr = rtc_interrupt;
931         }
932
933         if (request_irq(RTC_IRQ, rtc_int_handler_ptr, 0, "rtc", NULL)) {
934                 /* Yeah right, seeing as irq 8 doesn't even hit the bus. */
935                 rtc_has_irq = 0;
936                 printk(KERN_ERR "rtc: IRQ %d is not free.\n", RTC_IRQ);
937                 rtc_release_region();
938
939                 return -EIO;
940         }
941         hpet_rtc_timer_init();
942
943 #endif
944
945 #endif /* CONFIG_SPARC32 vs. others */
946
947         if (misc_register(&rtc_dev)) {
948 #ifdef RTC_IRQ
949                 free_irq(RTC_IRQ, NULL);
950                 hpet_unregister_irq_handler(rtc_interrupt);
951                 rtc_has_irq = 0;
952 #endif
953                 rtc_release_region();
954                 return -ENODEV;
955         }
956
957 #ifdef CONFIG_PROC_FS
958         ent = proc_create_single("driver/rtc", 0, NULL, rtc_proc_show);
959         if (!ent)
960                 printk(KERN_WARNING "rtc: Failed to register with procfs.\n");
961 #endif
962
963 #if defined(__alpha__) || defined(__mips__)
964         rtc_freq = HZ;
965
966         /* Each operating system on an Alpha uses its own epoch.
967            Let's try to guess which one we are using now. */
968
969         if (rtc_is_updating() != 0)
970                 msleep(20);
971
972         spin_lock_irq(&rtc_lock);
973         year = CMOS_READ(RTC_YEAR);
974         ctrl = CMOS_READ(RTC_CONTROL);
975         spin_unlock_irq(&rtc_lock);
976
977         if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD)
978                 year = bcd2bin(year);       /* This should never happen... */
979
980         if (year < 20) {
981                 epoch = 2000;
982                 guess = "SRM (post-2000)";
983         } else if (year >= 20 && year < 48) {
984                 epoch = 1980;
985                 guess = "ARC console";
986         } else if (year >= 48 && year < 72) {
987                 epoch = 1952;
988                 guess = "Digital UNIX";
989 #if defined(__mips__)
990         } else if (year >= 72 && year < 74) {
991                 epoch = 2000;
992                 guess = "Digital DECstation";
993 #else
994         } else if (year >= 70) {
995                 epoch = 1900;
996                 guess = "Standard PC (1900)";
997 #endif
998         }
999         if (guess)
1000                 printk(KERN_INFO "rtc: %s epoch (%lu) detected\n",
1001                         guess, epoch);
1002 #endif
1003 #ifdef RTC_IRQ
1004         if (rtc_has_irq == 0)
1005                 goto no_irq2;
1006
1007         spin_lock_irq(&rtc_lock);
1008         rtc_freq = 1024;
1009         if (!hpet_set_periodic_freq(rtc_freq)) {
1010                 /*
1011                  * Initialize periodic frequency to CMOS reset default,
1012                  * which is 1024Hz
1013                  */
1014                 CMOS_WRITE(((CMOS_READ(RTC_FREQ_SELECT) & 0xF0) | 0x06),
1015                            RTC_FREQ_SELECT);
1016         }
1017         spin_unlock_irq(&rtc_lock);
1018 no_irq2:
1019 #endif
1020
1021         (void) init_sysctl();
1022
1023         printk(KERN_INFO "Real Time Clock Driver v" RTC_VERSION "\n");
1024
1025         return 0;
1026 }
1027
1028 static void __exit rtc_exit(void)
1029 {
1030         cleanup_sysctl();
1031         remove_proc_entry("driver/rtc", NULL);
1032         misc_deregister(&rtc_dev);
1033
1034 #ifdef CONFIG_SPARC32
1035         if (rtc_has_irq)
1036                 free_irq(rtc_irq, &rtc_port);
1037 #else
1038         rtc_release_region();
1039 #ifdef RTC_IRQ
1040         if (rtc_has_irq) {
1041                 free_irq(RTC_IRQ, NULL);
1042                 hpet_unregister_irq_handler(hpet_rtc_interrupt);
1043         }
1044 #endif
1045 #endif /* CONFIG_SPARC32 */
1046 }
1047
1048 module_init(rtc_init);
1049 module_exit(rtc_exit);
1050
1051 #ifdef RTC_IRQ
1052 /*
1053  *      At IRQ rates >= 4096Hz, an interrupt may get lost altogether.
1054  *      (usually during an IDE disk interrupt, with IRQ unmasking off)
1055  *      Since the interrupt handler doesn't get called, the IRQ status
1056  *      byte doesn't get read, and the RTC stops generating interrupts.
1057  *      A timer is set, and will call this function if/when that happens.
1058  *      To get it out of this stalled state, we just read the status.
1059  *      At least a jiffy of interrupts (rtc_freq/HZ) will have been lost.
1060  *      (You *really* shouldn't be trying to use a non-realtime system
1061  *      for something that requires a steady > 1KHz signal anyways.)
1062  */
1063
1064 static void rtc_dropped_irq(struct timer_list *unused)
1065 {
1066         unsigned long freq;
1067
1068         spin_lock_irq(&rtc_lock);
1069
1070         if (hpet_rtc_dropped_irq()) {
1071                 spin_unlock_irq(&rtc_lock);
1072                 return;
1073         }
1074
1075         /* Just in case someone disabled the timer from behind our back... */
1076         if (rtc_status & RTC_TIMER_ON)
1077                 mod_timer(&rtc_irq_timer, jiffies + HZ/rtc_freq + 2*HZ/100);
1078
1079         rtc_irq_data += ((rtc_freq/HZ)<<8);
1080         rtc_irq_data &= ~0xff;
1081         rtc_irq_data |= (CMOS_READ(RTC_INTR_FLAGS) & 0xF0);     /* restart */
1082
1083         freq = rtc_freq;
1084
1085         spin_unlock_irq(&rtc_lock);
1086
1087         printk_ratelimited(KERN_WARNING "rtc: lost some interrupts at %ldHz.\n",
1088                            freq);
1089
1090         /* Now we have new data */
1091         wake_up_interruptible(&rtc_wait);
1092
1093         kill_fasync(&rtc_async_queue, SIGIO, POLL_IN);
1094 }
1095 #endif
1096
1097 #ifdef CONFIG_PROC_FS
1098 /*
1099  *      Info exported via "/proc/driver/rtc".
1100  */
1101
1102 static int rtc_proc_show(struct seq_file *seq, void *v)
1103 {
1104 #define YN(bit) ((ctrl & bit) ? "yes" : "no")
1105 #define NY(bit) ((ctrl & bit) ? "no" : "yes")
1106         struct rtc_time tm;
1107         unsigned char batt, ctrl;
1108         unsigned long freq;
1109
1110         spin_lock_irq(&rtc_lock);
1111         batt = CMOS_READ(RTC_VALID) & RTC_VRT;
1112         ctrl = CMOS_READ(RTC_CONTROL);
1113         freq = rtc_freq;
1114         spin_unlock_irq(&rtc_lock);
1115
1116
1117         rtc_get_rtc_time(&tm);
1118
1119         /*
1120          * There is no way to tell if the luser has the RTC set for local
1121          * time or for Universal Standard Time (GMT). Probably local though.
1122          */
1123         seq_printf(seq,
1124                    "rtc_time\t: %ptRt\n"
1125                    "rtc_date\t: %ptRd\n"
1126                    "rtc_epoch\t: %04lu\n",
1127                    &tm, &tm, epoch);
1128
1129         get_rtc_alm_time(&tm);
1130
1131         /*
1132          * We implicitly assume 24hr mode here. Alarm values >= 0xc0 will
1133          * match any value for that particular field. Values that are
1134          * greater than a valid time, but less than 0xc0 shouldn't appear.
1135          */
1136         seq_puts(seq, "alarm\t\t: ");
1137         if (tm.tm_hour <= 24)
1138                 seq_printf(seq, "%02d:", tm.tm_hour);
1139         else
1140                 seq_puts(seq, "**:");
1141
1142         if (tm.tm_min <= 59)
1143                 seq_printf(seq, "%02d:", tm.tm_min);
1144         else
1145                 seq_puts(seq, "**:");
1146
1147         if (tm.tm_sec <= 59)
1148                 seq_printf(seq, "%02d\n", tm.tm_sec);
1149         else
1150                 seq_puts(seq, "**\n");
1151
1152         seq_printf(seq,
1153                    "DST_enable\t: %s\n"
1154                    "BCD\t\t: %s\n"
1155                    "24hr\t\t: %s\n"
1156                    "square_wave\t: %s\n"
1157                    "alarm_IRQ\t: %s\n"
1158                    "update_IRQ\t: %s\n"
1159                    "periodic_IRQ\t: %s\n"
1160                    "periodic_freq\t: %ld\n"
1161                    "batt_status\t: %s\n",
1162                    YN(RTC_DST_EN),
1163                    NY(RTC_DM_BINARY),
1164                    YN(RTC_24H),
1165                    YN(RTC_SQWE),
1166                    YN(RTC_AIE),
1167                    YN(RTC_UIE),
1168                    YN(RTC_PIE),
1169                    freq,
1170                    batt ? "okay" : "dead");
1171
1172         return  0;
1173 #undef YN
1174 #undef NY
1175 }
1176 #endif
1177
1178 static void rtc_get_rtc_time(struct rtc_time *rtc_tm)
1179 {
1180         unsigned long uip_watchdog = jiffies, flags;
1181         unsigned char ctrl;
1182 #ifdef CONFIG_MACH_DECSTATION
1183         unsigned int real_year;
1184 #endif
1185
1186         /*
1187          * read RTC once any update in progress is done. The update
1188          * can take just over 2ms. We wait 20ms. There is no need to
1189          * to poll-wait (up to 1s - eeccch) for the falling edge of RTC_UIP.
1190          * If you need to know *exactly* when a second has started, enable
1191          * periodic update complete interrupts, (via ioctl) and then
1192          * immediately read /dev/rtc which will block until you get the IRQ.
1193          * Once the read clears, read the RTC time (again via ioctl). Easy.
1194          */
1195
1196         while (rtc_is_updating() != 0 &&
1197                time_before(jiffies, uip_watchdog + 2*HZ/100))
1198                 cpu_relax();
1199
1200         /*
1201          * Only the values that we read from the RTC are set. We leave
1202          * tm_wday, tm_yday and tm_isdst untouched. Note that while the
1203          * RTC has RTC_DAY_OF_WEEK, we should usually ignore it, as it is
1204          * only updated by the RTC when initially set to a non-zero value.
1205          */
1206         spin_lock_irqsave(&rtc_lock, flags);
1207         rtc_tm->tm_sec = CMOS_READ(RTC_SECONDS);
1208         rtc_tm->tm_min = CMOS_READ(RTC_MINUTES);
1209         rtc_tm->tm_hour = CMOS_READ(RTC_HOURS);
1210         rtc_tm->tm_mday = CMOS_READ(RTC_DAY_OF_MONTH);
1211         rtc_tm->tm_mon = CMOS_READ(RTC_MONTH);
1212         rtc_tm->tm_year = CMOS_READ(RTC_YEAR);
1213         /* Only set from 2.6.16 onwards */
1214         rtc_tm->tm_wday = CMOS_READ(RTC_DAY_OF_WEEK);
1215
1216 #ifdef CONFIG_MACH_DECSTATION
1217         real_year = CMOS_READ(RTC_DEC_YEAR);
1218 #endif
1219         ctrl = CMOS_READ(RTC_CONTROL);
1220         spin_unlock_irqrestore(&rtc_lock, flags);
1221
1222         if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1223                 rtc_tm->tm_sec = bcd2bin(rtc_tm->tm_sec);
1224                 rtc_tm->tm_min = bcd2bin(rtc_tm->tm_min);
1225                 rtc_tm->tm_hour = bcd2bin(rtc_tm->tm_hour);
1226                 rtc_tm->tm_mday = bcd2bin(rtc_tm->tm_mday);
1227                 rtc_tm->tm_mon = bcd2bin(rtc_tm->tm_mon);
1228                 rtc_tm->tm_year = bcd2bin(rtc_tm->tm_year);
1229                 rtc_tm->tm_wday = bcd2bin(rtc_tm->tm_wday);
1230         }
1231
1232 #ifdef CONFIG_MACH_DECSTATION
1233         rtc_tm->tm_year += real_year - 72;
1234 #endif
1235
1236         /*
1237          * Account for differences between how the RTC uses the values
1238          * and how they are defined in a struct rtc_time;
1239          */
1240         rtc_tm->tm_year += epoch - 1900;
1241         if (rtc_tm->tm_year <= 69)
1242                 rtc_tm->tm_year += 100;
1243
1244         rtc_tm->tm_mon--;
1245 }
1246
1247 static void get_rtc_alm_time(struct rtc_time *alm_tm)
1248 {
1249         unsigned char ctrl;
1250
1251         /*
1252          * Only the values that we read from the RTC are set. That
1253          * means only tm_hour, tm_min, and tm_sec.
1254          */
1255         spin_lock_irq(&rtc_lock);
1256         alm_tm->tm_sec = CMOS_READ(RTC_SECONDS_ALARM);
1257         alm_tm->tm_min = CMOS_READ(RTC_MINUTES_ALARM);
1258         alm_tm->tm_hour = CMOS_READ(RTC_HOURS_ALARM);
1259         ctrl = CMOS_READ(RTC_CONTROL);
1260         spin_unlock_irq(&rtc_lock);
1261
1262         if (!(ctrl & RTC_DM_BINARY) || RTC_ALWAYS_BCD) {
1263                 alm_tm->tm_sec = bcd2bin(alm_tm->tm_sec);
1264                 alm_tm->tm_min = bcd2bin(alm_tm->tm_min);
1265                 alm_tm->tm_hour = bcd2bin(alm_tm->tm_hour);
1266         }
1267 }
1268
1269 #ifdef RTC_IRQ
1270 /*
1271  * Used to disable/enable interrupts for any one of UIE, AIE, PIE.
1272  * Rumour has it that if you frob the interrupt enable/disable
1273  * bits in RTC_CONTROL, you should read RTC_INTR_FLAGS, to
1274  * ensure you actually start getting interrupts. Probably for
1275  * compatibility with older/broken chipset RTC implementations.
1276  * We also clear out any old irq data after an ioctl() that
1277  * meddles with the interrupt enable/disable bits.
1278  */
1279
1280 static void mask_rtc_irq_bit_locked(unsigned char bit)
1281 {
1282         unsigned char val;
1283
1284         if (hpet_mask_rtc_irq_bit(bit))
1285                 return;
1286         val = CMOS_READ(RTC_CONTROL);
1287         val &=  ~bit;
1288         CMOS_WRITE(val, RTC_CONTROL);
1289         CMOS_READ(RTC_INTR_FLAGS);
1290
1291         rtc_irq_data = 0;
1292 }
1293
1294 static void set_rtc_irq_bit_locked(unsigned char bit)
1295 {
1296         unsigned char val;
1297
1298         if (hpet_set_rtc_irq_bit(bit))
1299                 return;
1300         val = CMOS_READ(RTC_CONTROL);
1301         val |= bit;
1302         CMOS_WRITE(val, RTC_CONTROL);
1303         CMOS_READ(RTC_INTR_FLAGS);
1304
1305         rtc_irq_data = 0;
1306 }
1307 #endif
1308
1309 MODULE_AUTHOR("Paul Gortmaker");
1310 MODULE_LICENSE("GPL");
1311 MODULE_ALIAS_MISCDEV(RTC_MINOR);