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