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