Upload Tizen:Base source
[framework/base/util-linux-ng.git] / hwclock / cmos.c
1 /*
2  * i386 CMOS starts out with 14 bytes clock data
3  * alpha has something similar, but with details
4  * depending on the machine type.
5  *
6  * byte 0: seconds (0-59)
7  * byte 2: minutes (0-59)
8  * byte 4: hours (0-23 in 24hr mode,
9  *                1-12 in 12hr mode, with high bit unset/set if am/pm)
10  * byte 6: weekday (1-7, Sunday=1)
11  * byte 7: day of the month (1-31)
12  * byte 8: month (1-12)
13  * byte 9: year (0-99)
14  * Numbers are stored in BCD/binary if bit 2 of byte 11 is unset/set
15  * The clock is in 12hr/24hr mode if bit 1 of byte 11 is unset/set
16  * The clock is undefined (being updated) if bit 7 of byte 10 is set.
17  * The clock is frozen (to be updated) by setting bit 7 of byte 11
18  * Bit 7 of byte 14 indicates whether the CMOS clock is reliable:
19  * it is 1 if RTC power has been good since this bit was last read;
20  * it is 0 when the battery is dead and system power has been off.
21  *
22  * Avoid setting the RTC clock within 2 seconds of the day rollover
23  * that starts a new month or enters daylight saving time.
24  *
25  * The century situation is messy:
26  * Usually byte 50 (0x32) gives the century (in BCD, so 19 or 20 hex),
27  * but IBM PS/2 has (part of) a checksum there and uses byte 55 (0x37).
28  * Sometimes byte 127 (0x7f) or Bank 1, byte 0x48 gives the century.
29  * The original RTC will not access any century byte; some modern
30  * versions will. If a modern RTC or BIOS increments the century byte
31  * it may go from 0x19 to 0x20, but in some buggy cases 0x1a is produced.
32  */
33
34 /*
35  * A struct tm has int fields
36  *   tm_sec (0-59, 60 or 61 only for leap seconds)
37  *   tm_min (0-59)
38  *   tm_hour (0-23)
39  *   tm_mday (1-31)
40  *   tm_mon (0-11)
41  *   tm_year (number of years since 1900)
42  *   tm_wday (0-6, 0=Sunday)
43  *   tm_yday (0-365)
44  *   tm_isdst (>0: yes, 0: no, <0: unknown)
45  */
46
47 #include <unistd.h>             /* for geteuid() */
48 #include <fcntl.h>              /* for O_RDWR */
49 #include <errno.h>
50 #include "nls.h"
51
52 #if defined(__i386__)
53 #ifdef HAVE_SYS_IO_H
54 #include <sys/io.h>
55 #else
56 #include <asm/io.h>             /* for inb, outb */
57 #endif
58 #elif defined(__alpha__)
59 /* <asm/io.h> fails to compile, probably because of u8 etc */
60 extern unsigned int     inb(unsigned long port);
61 extern void             outb(unsigned char b,unsigned long port);
62 #else
63 void outb(int a, int b){}
64 int inb(int c){ return 0; }
65 #endif
66
67 #include "clock.h"
68
69 #define BCD_TO_BIN(val) ((val)=((val)&15) + ((val)>>4)*10)
70 #define BIN_TO_BCD(val) ((val)=(((val)/10)<<4) + (val)%10)
71
72 /*
73  * The epoch.
74  *
75  * Unix uses 1900 as epoch for a struct tm, and 1970 for a time_t.
76  * But what was written to CMOS?
77  * Digital DECstations use 1928 - this is on a mips or alpha
78  * Digital Unix uses 1952, e.g. on AXPpxi33
79  * Windows NT uses 1980.
80  * The ARC console expects to boot Windows NT and uses 1980.
81  * (But a Ruffian uses 1900, just like SRM.)
82  * It is reported that ALPHA_PRE_V1_2_SRM_CONSOLE uses 1958.
83  */
84 #define TM_EPOCH 1900
85 int cmos_epoch = 1900;
86
87 /* Martin Ostermann writes:
88 The problem with the Jensen is twofold: First, it has the clock at a
89 different address. Secondly, it has a distinction beween "local" and
90 normal bus addresses. The local ones pertain to the hardware integrated
91 into the chipset, like serial/parallel ports and of course, the RTC.
92 Those need to be addressed differently. This is handled fine in the kernel,
93 and it's not a problem, since this usually gets totally optimized by the
94 compile. But the i/o routines of (g)libc lack this support so far.
95 The result of this is, that the old clock program worked only on the
96 Jensen when USE_DEV_PORT was defined, but not with the normal inb/outb
97 functions.
98  */
99 int use_dev_port = 0;           /* 1 for Jensen */
100 int dev_port_fd;
101 unsigned short clock_ctl_addr = 0x70;   /* 0x170 for Jensen */
102 unsigned short clock_data_addr = 0x71;  /* 0x171 for Jensen */
103
104
105 int century_byte = 0;           /* 0: don't access a century byte
106                                   50 (0x32): usual PC value
107                                   55 (0x37): PS/2 */
108
109 #ifdef __alpha__
110 int funkyTOY = 0;               /* 1 for PC164/LX164/SX164 type alpha */
111 #endif
112
113 #ifdef __alpha
114
115 static int
116 is_in_cpuinfo(char *fmt, char *str)
117 {
118     FILE *cpuinfo;
119     char field[256];
120     char format[256];
121     int found = 0;
122
123     sprintf(format, "%s : %s", fmt, "%255s");
124
125     if ((cpuinfo = fopen ("/proc/cpuinfo", "r")) != NULL) {
126         while (!feof(cpuinfo)) {
127             if (fscanf (cpuinfo, format, field) == 1) {
128                 if (strncmp(field, str, strlen(str)) == 0)
129                     found = 1;
130                 break;
131             }
132             fgets (field, 256, cpuinfo);
133         }
134         fclose(cpuinfo);
135     }
136     return found;
137 }
138
139 /* Set cmos_epoch, either from user options, or by asking the kernel,
140    or by looking at /proc/cpu_info */
141 void
142 set_cmos_epoch(int ARCconsole, int SRM) {
143   unsigned long epoch;
144
145   /* Believe the user */
146   if (epoch_option != -1) {
147     cmos_epoch = epoch_option;
148     return;
149   }
150
151   if (ARCconsole)
152     cmos_epoch = 1980;
153
154   if (ARCconsole || SRM)
155     return;
156
157
158   /* If we can ask the kernel, we don't need guessing from /proc/cpuinfo */
159   if (get_epoch_rtc(&epoch, 1) == 0) {
160      cmos_epoch = epoch;
161      return;
162   }
163
164   /* The kernel source today says: read the year.
165      If it is in 0-19 then the epoch is 2000.
166      If it is in 20-47 then the epoch is 1980.
167      If it is in 48-69 then the epoch is 1952.
168      If it is in 70-99 then the epoch is 1928.
169      Otherwise the epoch is 1900.
170      Clearly, this must be changed before 2019. */
171
172   /* See whether we are dealing with SRM or MILO, as they have
173      different "epoch" ideas. */
174   if (is_in_cpuinfo("system serial number", "MILO")) {
175       ARCconsole = 1;
176       if (debug) printf (_("booted from MILO\n"));
177   }
178
179   /* See whether we are dealing with a RUFFIAN aka Alpha PC-164 UX (or BX),
180      as they have REALLY different TOY (TimeOfYear) format: BCD, and not
181      an ARC-style epoch.
182      BCD is detected dynamically, but we must NOT adjust like ARC. */
183   if (ARCconsole && is_in_cpuinfo("system type", "Ruffian")) {
184     ARCconsole = 0;
185     if (debug) printf (_("Ruffian BCD clock\n"));
186   }
187
188   if (ARCconsole)
189     cmos_epoch = 1980;
190 }
191
192 void
193 set_cmos_access(int Jensen, int funky_toy) {
194
195   /* See whether we're dealing with a Jensen---it has a weird I/O
196      system.  DEC was just learning how to build Alpha PCs.  */
197   if (Jensen || is_in_cpuinfo("system type", "Jensen")) {
198     use_dev_port = 1;
199     clock_ctl_addr = 0x170;
200     clock_data_addr = 0x171;
201     if (debug) printf (_("clockport adjusted to 0x%x\n"), clock_ctl_addr);
202   }
203
204   /* see whether we are dealing with PC164/LX164/SX164, as they have a TOY
205      that must be accessed differently to work correctly. */
206   /* Nautilus stuff reported by Neoklis Kyriazis */
207   if (funky_toy ||
208       is_in_cpuinfo("system variation", "PC164") ||
209       is_in_cpuinfo("system variation", "LX164") ||
210       is_in_cpuinfo("system variation", "SX164") ||
211       is_in_cpuinfo("system type", "Nautilus")) {
212       funkyTOY = 1;
213       if (debug) printf (_("funky TOY!\n"));
214   }
215 }
216 #endif
217
218
219 #if __alpha__
220 /*
221  * The Alpha doesn't allow user-level code to disable interrupts (for
222  * good reasons).  Instead, we ensure atomic operation by performing
223  * the operation and checking whether the high 32 bits of the cycle
224  * counter changed.  If they did, a context switch must have occurred
225  * and we redo the operation.  As long as the operation is reasonably
226  * short, it will complete atomically, eventually.
227  */
228
229 static unsigned long
230 atomic(const char *name, unsigned long (*op)(unsigned long),
231        unsigned long arg)
232 {
233   unsigned long ts1, ts2, n, v;
234
235   for (n = 0; n < 1000; ++n) {
236     asm volatile ("rpcc %0" : "r="(ts1));
237     v = (*op)(arg);
238     asm volatile ("rpcc %0" : "r="(ts2));
239
240     if ((ts1 ^ ts2) >> 32 == 0) {
241       return v;
242     }
243   }
244   fprintf(stderr, _("%s: atomic %s failed for 1000 iterations!"), progname, name);
245   exit(1);
246 }
247 #else
248
249 /*
250  * Hmmh, this isn't very atomic.  Maybe we should force an error
251  * instead?
252  *
253  * TODO: optimize the access to CMOS by mlockall(MCL_CURRENT)
254  *       and SCHED_FIFO
255  */
256 static unsigned long
257 atomic(const char *name, unsigned long (*op)(unsigned long),
258        unsigned long arg)
259 {
260     return (*op)(arg);
261 }
262
263 #endif
264
265
266 static inline
267 unsigned long cmos_read(unsigned long reg)
268 {
269   if (use_dev_port) {
270     unsigned char v = reg | 0x80;
271     lseek(dev_port_fd, clock_ctl_addr, 0);
272     if (write(dev_port_fd, &v, 1) == -1 && debug)
273       printf(_("cmos_read(): write to control address %X failed: %s\n"), clock_ctl_addr, strerror(errno));
274     lseek(dev_port_fd, clock_data_addr, 0);
275     if (read(dev_port_fd, &v, 1) == -1 && debug)
276       printf(_("cmos_read(): read data address %X failed: %s\n"), clock_data_addr, strerror(errno));
277     return v;
278   } else {
279     /* We only want to read CMOS data, but unfortunately
280        writing to bit 7 disables (1) or enables (0) NMI;
281        since this bit is read-only we have to guess the old status.
282        Various docs suggest that one should disable NMI while
283        reading/writing CMOS data, and enable it again afterwards.
284        This would yield the sequence
285           outb (reg | 0x80, 0x70);
286           val = inb(0x71);
287           outb (0x0d, 0x70);    // 0x0d: random read-only location
288        Other docs state that "any write to 0x70 should be followed
289        by an action to 0x71 or the RTC wil be left in an unknown state".
290        Most docs say that it doesnt matter at all what one does.
291      */
292     /* bit 0x80: disable NMI while reading - should we?
293        Let us follow the kernel and not disable.
294        Called only with 0 <= reg < 128 */
295     outb (reg, clock_ctl_addr);
296     return inb (clock_data_addr);
297   }
298 }
299
300 static inline
301 unsigned long cmos_write(unsigned long reg, unsigned long val)
302 {
303   if (use_dev_port) {
304     unsigned char v = reg | 0x80;
305     lseek(dev_port_fd, clock_ctl_addr, 0);
306     if (write(dev_port_fd, &v, 1) == -1 && debug)
307       printf(_("cmos_write(): write to control address %X failed: %s\n"), clock_ctl_addr, strerror(errno));
308     v = (val & 0xff);
309     lseek(dev_port_fd, clock_data_addr, 0);
310     if (write(dev_port_fd, &v, 1) == -1 && debug)
311       printf(_("cmos_write(): write to data address %X failed: %s\n"), clock_data_addr, strerror(errno));
312   } else {
313     outb (reg, clock_ctl_addr);
314     outb (val, clock_data_addr);
315   }
316   return 0;
317 }
318
319 static unsigned long cmos_set_time(unsigned long arg)
320 {
321   unsigned char save_control, save_freq_select, pmbit = 0;
322   struct tm tm = *(struct tm *) arg;
323   unsigned int century;
324
325 /*
326  * CMOS byte 10 (clock status register A) has 3 bitfields:
327  * bit 7: 1 if data invalid, update in progress (read-only bit)
328  *         (this is raised 224 us before the actual update starts)
329  *  6-4    select base frequency
330  *         010: 32768 Hz time base (default)
331  *         111: reset
332  *         all other combinations are manufacturer-dependent
333  *         (e.g.: DS1287: 010 = start oscillator, anything else = stop)
334  *  3-0    rate selection bits for interrupt
335  *         0000 none (may stop RTC)
336  *         0001, 0010 give same frequency as 1000, 1001
337  *         0011 122 microseconds (minimum, 8192 Hz)
338  *         .... each increase by 1 halves the frequency, doubles the period
339  *         1111 500 milliseconds (maximum, 2 Hz)
340  *         0110 976.562 microseconds (default 1024 Hz)
341  */
342
343   save_control = cmos_read (11);   /* tell the clock it's being set */
344   cmos_write (11, (save_control | 0x80));
345   save_freq_select = cmos_read (10);       /* stop and reset prescaler */
346   cmos_write (10, (save_freq_select | 0x70));
347
348   tm.tm_year += TM_EPOCH;
349   century = tm.tm_year/100;
350   tm.tm_year -= cmos_epoch;
351   tm.tm_year %= 100;
352   tm.tm_mon += 1;
353   tm.tm_wday += 1;
354
355   if (!(save_control & 0x02)) { /* 12hr mode; the default is 24hr mode */
356       if (tm.tm_hour == 0)
357           tm.tm_hour = 24;
358       if (tm.tm_hour > 12) {
359           tm.tm_hour -= 12;
360           pmbit = 0x80;
361       }
362   }
363
364   if (!(save_control & 0x04)) { /* BCD mode - the default */
365       BIN_TO_BCD(tm.tm_sec);
366       BIN_TO_BCD(tm.tm_min);
367       BIN_TO_BCD(tm.tm_hour);
368       BIN_TO_BCD(tm.tm_wday);
369       BIN_TO_BCD(tm.tm_mday);
370       BIN_TO_BCD(tm.tm_mon);
371       BIN_TO_BCD(tm.tm_year);
372       BIN_TO_BCD(century);
373   }
374
375   cmos_write (0, tm.tm_sec);
376   cmos_write (2, tm.tm_min);
377   cmos_write (4, tm.tm_hour | pmbit);
378   cmos_write (6, tm.tm_wday);
379   cmos_write (7, tm.tm_mday);
380   cmos_write (8, tm.tm_mon);
381   cmos_write (9, tm.tm_year);
382   if (century_byte)
383           cmos_write (century_byte, century);
384
385
386     /* The kernel sources, linux/arch/i386/kernel/time.c, have the
387        following comment:
388
389        The following flags have to be released exactly in this order,
390        otherwise the DS12887 (popular MC146818A clone with integrated
391        battery and quartz) will not reset the oscillator and will not
392        update precisely 500 ms later.  You won't find this mentioned
393        in the Dallas Semiconductor data sheets, but who believes data
394        sheets anyway ...  -- Markus Kuhn
395     */
396
397   cmos_write (11, save_control);
398   cmos_write (10, save_freq_select);
399   return 0;
400 }
401
402 static int
403 hclock_read(unsigned long reg) {
404         return atomic("clock read", cmos_read, (reg));
405 }
406
407 static void
408 hclock_set_time(const struct tm *tm) {
409         atomic("set time", cmos_set_time, (unsigned long)(tm));
410 }
411
412 static inline int
413 cmos_clock_busy(void) {
414         return
415 #ifdef __alpha__
416                         /* poll bit 4 (UF) of Control Register C */
417             funkyTOY ? (hclock_read(12) & 0x10) :
418 #endif
419                         /* poll bit 7 (UIP) of Control Register A */
420             (hclock_read(10) & 0x80);
421 }
422
423
424 static int
425 synchronize_to_clock_tick_cmos(void) {
426   int i;
427
428   /* Wait for rise.  Should be within a second, but in case something
429      weird happens, we have a limit on this loop to reduce the impact
430      of this failure.
431      */
432   for (i = 0; !cmos_clock_busy(); i++)
433           if (i >= 10000000)
434                   return 1;
435
436   /* Wait for fall.  Should be within 2.228 ms. */
437   for (i = 0; cmos_clock_busy(); i++)
438           if (i >= 1000000)
439                   return 1;
440   return 0;
441 }
442
443
444
445 static int
446 read_hardware_clock_cmos(struct tm *tm) {
447 /*----------------------------------------------------------------------------
448   Read the hardware clock and return the current time via <tm> argument.
449   Assume we have an ISA machine and read the clock directly with CPU I/O
450   instructions.
451
452   This function is not totally reliable.  It takes a finite and
453   unpredictable amount of time to execute the code below.  During that
454   time, the clock may change and we may even read an invalid value in
455   the middle of an update.  We do a few checks to minimize this
456   possibility, but only the kernel can actually read the clock
457   properly, since it can execute code in a short and predictable
458   amount of time (by turning of interrupts).
459
460   In practice, the chance of this function returning the wrong time is
461   extremely remote.
462
463 -----------------------------------------------------------------------------*/
464   bool got_time = FALSE;
465   unsigned char status, pmbit;
466
467   status = pmbit = 0;           /* just for gcc */
468
469   while (!got_time) {
470     /* Bit 7 of Byte 10 of the Hardware Clock value is the Update In Progress
471        (UIP) bit, which is on while and 244 uS before the Hardware Clock
472        updates itself.  It updates the counters individually, so reading
473        them during an update would produce garbage.  The update takes 2mS,
474        so we could be spinning here that long waiting for this bit to turn
475        off.
476
477        Furthermore, it is pathologically possible for us to be in this
478        code so long that even if the UIP bit is not on at first, the
479        clock has changed while we were running.  We check for that too,
480        and if it happens, we start over.
481        */
482
483     if (!cmos_clock_busy()) {
484       /* No clock update in progress, go ahead and read */
485       tm->tm_sec = hclock_read(0);
486       tm->tm_min = hclock_read(2);
487       tm->tm_hour = hclock_read(4);
488       tm->tm_wday = hclock_read(6);
489       tm->tm_mday = hclock_read(7);
490       tm->tm_mon = hclock_read(8);
491       tm->tm_year = hclock_read(9);
492       status = hclock_read(11);
493 #if 0
494       if (century_byte)
495           century = hclock_read(century_byte);
496 #endif
497
498       /* Unless the clock changed while we were reading, consider this
499          a good clock read .
500        */
501       if (tm->tm_sec == hclock_read (0))
502         got_time = TRUE;
503     }
504     /* Yes, in theory we could have been running for 60 seconds and
505        the above test wouldn't work!
506        */
507   }
508
509   if (!(status & 0x04)) { /* BCD mode - the default */
510       BCD_TO_BIN(tm->tm_sec);
511       BCD_TO_BIN(tm->tm_min);
512       pmbit = (tm->tm_hour & 0x80);
513       tm->tm_hour &= 0x7f;
514       BCD_TO_BIN(tm->tm_hour);
515       BCD_TO_BIN(tm->tm_wday);
516       BCD_TO_BIN(tm->tm_mday);
517       BCD_TO_BIN(tm->tm_mon);
518       BCD_TO_BIN(tm->tm_year);
519 #if 0
520       BCD_TO_BIN(century);
521 #endif
522   }
523
524   /* We don't use the century byte of the Hardware Clock
525      since we don't know its address (usually 50 or 55).
526      Here, we follow the advice of the X/Open Base Working Group:
527      "if century is not specified, then values in the range [69-99]
528       refer to years in the twentieth century (1969 to 1999 inclusive),
529       and values in the range [00-68] refer to years in the twenty-first
530       century (2000 to 2068 inclusive)."
531    */
532
533   tm->tm_wday -= 1;
534   tm->tm_mon -= 1;
535   tm->tm_year += (cmos_epoch - TM_EPOCH);
536   if (tm->tm_year < 69)
537           tm->tm_year += 100;
538   if (pmbit) {
539           tm->tm_hour += 12;
540           if (tm->tm_hour == 24)
541                   tm->tm_hour = 0;
542   }
543
544   tm->tm_isdst = -1;        /* don't know whether it's daylight */
545   return 0;
546 }
547
548
549
550 static int
551 set_hardware_clock_cmos(const struct tm *new_broken_time) {
552
553     hclock_set_time(new_broken_time);
554     return 0;
555 }
556
557 static int
558 i386_iopl(const int level) {
559 #if defined(__i386__) || defined(__alpha__)
560   extern int iopl(const int lvl);
561   return iopl(level);
562 #else
563   return -2;
564 #endif
565 }
566
567 static int
568 get_permissions_cmos(void) {
569   int rc;
570
571   if (use_dev_port) {
572     if ((dev_port_fd = open("/dev/port", O_RDWR)) < 0) {
573       int errsv = errno;
574       fprintf(stderr, _("Cannot open /dev/port: %s"), strerror(errsv));
575       rc = 1;
576     } else
577       rc = 0;
578   } else {
579     rc = i386_iopl(3);
580     if (rc == -2) {
581       fprintf(stderr, _("I failed to get permission because I didn't try.\n"));
582     } else if (rc != 0) {
583       rc = errno;
584       fprintf(stderr, _("%s is unable to get I/O port access:  "
585               "the iopl(3) call failed.\n"), progname);
586       if(rc == EPERM && geteuid())
587         fprintf(stderr, _("Probably you need root privileges.\n"));
588     }
589   }
590   return rc ? 1 : 0;
591 }
592
593 static struct clock_ops cmos = {
594         "direct I/O instructions to ISA clock",
595         get_permissions_cmos,
596         read_hardware_clock_cmos,
597         set_hardware_clock_cmos,
598         synchronize_to_clock_tick_cmos,
599 };
600
601
602 /* return &cmos if cmos clock present, NULL otherwise */
603 /* choose this construction to avoid gcc messages about unused variables */
604
605 struct clock_ops *
606 probe_for_cmos_clock(void){
607     int have_cmos =
608 #if defined(__i386__) || defined(__alpha__)
609             TRUE;
610 #else
611             FALSE;
612 #endif
613     return have_cmos ? &cmos : NULL;
614 }