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