]> git.ipfire.org Git - thirdparty/util-linux.git/blame - sys-utils/rtcwake.c
setsid: add long options and fix coding style
[thirdparty/util-linux.git] / sys-utils / rtcwake.c
CommitLineData
76700389
BW
1/*
2 * rtcwake -- enter a system sleep state until specified wakeup time.
3 *
4 * This uses cross-platform Linux interfaces to enter a system sleep state,
5 * and leave it no later than a specified time. It uses any RTC framework
6 * driver that supports standard driver model wakeup flags.
7 *
8 * This is normally used like the old "apmsleep" utility, to wake from a
9 * suspend state like ACPI S1 (standby) or S3 (suspend-to-RAM). Most
10 * platforms can implement those without analogues of BIOS, APM, or ACPI.
11 *
12 * On some systems, this can also be used like "nvram-wakeup", waking
13 * from states like ACPI S4 (suspend to disk). Not all systems have
14 * persistent media that are appropriate for such suspend modes.
15 *
16 * The best way to set the system's RTC is so that it holds the current
17 * time in UTC. Use the "-l" flag to tell this program that the system
18 * RTC uses a local timezone instead (maybe you dual-boot MS-Windows).
2148b051 19 * That flag should not be needed on systems with adjtime support.
76700389
BW
20 */
21
22#include <stdio.h>
23#include <getopt.h>
24#include <fcntl.h>
c41e1340 25#include <libgen.h>
76700389
BW
26#include <stdlib.h>
27#include <string.h>
28#include <unistd.h>
29#include <errno.h>
30#include <time.h>
31
32#include <sys/ioctl.h>
33#include <sys/time.h>
34#include <sys/types.h>
35
36#include <linux/rtc.h>
37
38#include "nls.h"
2ab428f6 39#include "xalloc.h"
77f5744c 40#include "pathnames.h"
437fa54f 41#include "usleep.h"
07b336c9 42#include "strutils.h"
eb76ca98 43#include "c.h"
76700389
BW
44
45/* constants from legacy PC/AT hardware */
46#define RTC_PF 0x40
47#define RTC_AF 0x20
48#define RTC_UF 0x10
49
50#define MAX_LINE 1024
51
76700389
BW
52#define VERSION_STRING "rtcwake from " PACKAGE_STRING
53#define RTC_PATH "/sys/class/rtc/%s/device/power/wakeup"
d3cf5414 54#define SYS_POWER_STATE_PATH "/sys/power/state"
76700389
BW
55#define ADJTIME_PATH "/etc/adjtime"
56#define DEFAULT_DEVICE "/dev/rtc0"
47bf8ef7 57#define DEFAULT_MODE "standby"
76700389
BW
58
59enum ClockMode {
60 CM_AUTO,
61 CM_UTC,
62 CM_LOCAL
63};
64
65static unsigned verbose;
569f3ca2 66static unsigned dryrun;
76700389
BW
67enum ClockMode clock_mode = CM_AUTO;
68
69static struct option long_options[] = {
70 {"auto", no_argument, 0, 'a'},
569f3ca2 71 {"dry-run", no_argument, 0, 'n'},
76700389
BW
72 {"local", no_argument, 0, 'l'},
73 {"utc", no_argument, 0, 'u'},
74 {"verbose", no_argument, 0, 'v'},
75 {"version", no_argument, 0, 'V'},
76 {"help", no_argument, 0, 'h'},
77 {"mode", required_argument, 0, 'm'},
78 {"device", required_argument, 0, 'd'},
79 {"seconds", required_argument, 0, 's'},
80 {"time", required_argument, 0, 't'},
81 {0, 0, 0, 0 }
82};
83
07b336c9 84static void __attribute__((__noreturn__)) usage(FILE *out)
76700389 85{
704c7705
KZ
86 fputs(_("\nUsage:\n"), out);
87 fprintf(out,
88 _(" %s [options]\n"), program_invocation_short_name);
89
90 fputs(_("\nOptions:\n"), out);
91 fputs(_(" -d, --device <device> select rtc device (rtc0|rtc1|...)\n"
92 " -n, --dry-run does everything, but suspend\n"
93 " -l, --local RTC uses local timezone\n"
94 " -m, --mode <mode> standby|mem|... sleep mode\n"
95 " -s, --seconds <seconds> seconds to sleep\n"
96 " -t, --time <time_t> time to wake\n"
97 " -u, --utc RTC uses UTC\n"
98 " -v, --verbose verbose messages\n"
99 " -V, --version show version\n"), out);
100
101 fputs(_("\nFor more information see rtcwake(8).\n"), out);
07b336c9
KZ
102
103 exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
76700389
BW
104}
105
f8d87ab1 106static int is_wakeup_enabled(const char *devname)
76700389
BW
107{
108 char buf[128], *s;
109 FILE *f;
110
111 /* strip the '/dev/' from the devname here */
112 snprintf(buf, sizeof buf, RTC_PATH, devname + strlen("/dev/"));
113 f = fopen(buf, "r");
114 if (!f) {
07b336c9 115 warn(_("open failed: %s"), buf);
76700389
BW
116 return 0;
117 }
118 s = fgets(buf, sizeof buf, f);
119 fclose(f);
120 if (!s)
121 return 0;
122
123 s = strchr(buf, '\n');
124 if (!s)
125 return 0;
126 *s = 0;
127
128 /* wakeup events could be disabled or not supported */
129 return strcmp(buf, "enabled") == 0;
130}
131
132/* all times should be in UTC */
133static time_t sys_time;
134static time_t rtc_time;
135
136static int get_basetimes(int fd)
137{
138 struct tm tm;
139 struct rtc_time rtc;
140
141 /* this process works in RTC time, except when working
142 * with the system clock (which always uses UTC).
143 */
144 if (clock_mode == CM_UTC)
145 setenv("TZ", "UTC", 1);
146 tzset();
147
148 /* read rtc and system clocks "at the same time", or as
149 * precisely (+/- a second) as we can read them.
150 */
151 if (ioctl(fd, RTC_RD_TIME, &rtc) < 0) {
07b336c9 152 warn(_("read rtc time failed"));
f8d87ab1 153 return -1;
76700389
BW
154 }
155 sys_time = time(0);
156 if (sys_time == (time_t)-1) {
07b336c9 157 warn(_("read system time failed"));
f8d87ab1 158 return -1;
76700389
BW
159 }
160
161 /* convert rtc_time to normal arithmetic-friendly form,
162 * updating tm.tm_wday as used by asctime().
163 */
164 memset(&tm, 0, sizeof tm);
165 tm.tm_sec = rtc.tm_sec;
166 tm.tm_min = rtc.tm_min;
167 tm.tm_hour = rtc.tm_hour;
168 tm.tm_mday = rtc.tm_mday;
169 tm.tm_mon = rtc.tm_mon;
170 tm.tm_year = rtc.tm_year;
1da17ec6 171 tm.tm_isdst = -1; /* assume the system knows better than the RTC */
76700389
BW
172 rtc_time = mktime(&tm);
173
174 if (rtc_time == (time_t)-1) {
07b336c9 175 warn(_("convert rtc time failed"));
f8d87ab1 176 return -1;
76700389
BW
177 }
178
179 if (verbose) {
2148b051
DB
180 /* Unless the system uses UTC, either delta or tzone
181 * reflects a seconds offset from UTC. The value can
182 * help sort out problems like bugs in your C library.
183 */
184 printf("\tdelta = %ld\n", sys_time - rtc_time);
185 printf("\ttzone = %ld\n", timezone);
186
187 printf("\ttzname = %s\n", tzname[daylight]);
188 gmtime_r(&rtc_time, &tm);
189 printf("\tsystime = %ld, (UTC) %s",
76700389 190 (long) sys_time, asctime(gmtime(&sys_time)));
2148b051 191 printf("\trtctime = %ld, (UTC) %s",
76700389
BW
192 (long) rtc_time, asctime(&tm));
193 }
194
f8d87ab1 195 return 0;
76700389
BW
196}
197
198static int setup_alarm(int fd, time_t *wakeup)
199{
200 struct tm *tm;
201 struct rtc_wkalrm wake;
202
1b7c164c
DB
203 /* The wakeup time is in POSIX time (more or less UTC).
204 * Ideally RTCs use that same time; but PCs can't do that
205 * if they need to boot MS-Windows. Messy...
206 *
207 * When clock_mode == CM_UTC this process's timezone is UTC,
208 * so we'll pass a UTC date to the RTC.
209 *
210 * Else clock_mode == CM_LOCAL so the time given to the RTC
211 * will instead use the local time zone.
212 */
213 tm = localtime(wakeup);
76700389
BW
214
215 wake.time.tm_sec = tm->tm_sec;
216 wake.time.tm_min = tm->tm_min;
217 wake.time.tm_hour = tm->tm_hour;
218 wake.time.tm_mday = tm->tm_mday;
219 wake.time.tm_mon = tm->tm_mon;
220 wake.time.tm_year = tm->tm_year;
2148b051
DB
221 /* wday, yday, and isdst fields are unused by Linux */
222 wake.time.tm_wday = -1;
223 wake.time.tm_yday = -1;
224 wake.time.tm_isdst = -1;
76700389 225
fc181184 226 wake.enabled = 1;
569f3ca2 227
fc181184 228 /* First try the preferred RTC_WKALM_SET */
569f3ca2 229 if (!dryrun && ioctl(fd, RTC_WKALM_SET, &wake) < 0) {
fc181184
GB
230 wake.enabled = 0;
231 /* Fall back on the non-preferred way of setting wakeups; only
232 * works for alarms < 24 hours from now */
233 if ((rtc_time + (24 * 60 * 60)) > *wakeup) {
234 if (ioctl(fd, RTC_ALM_SET, &wake.time) < 0) {
07b336c9 235 warn(_("set rtc alarm failed"));
fc181184
GB
236 return -1;
237 }
238 if (ioctl(fd, RTC_AIE_ON, 0) < 0) {
07b336c9 239 warn(_("enable rtc alarm failed"));
fc181184
GB
240 return -1;
241 }
242 } else {
07b336c9 243 warn(_("set rtc wake alarm failed"));
fc181184 244 return -1;
76700389
BW
245 }
246 }
247
f8d87ab1 248 return 0;
76700389
BW
249}
250
e6d1dc94
LR
251static int is_suspend_available(const char *suspend)
252{
253 int rc;
254 char buf[32];
255 FILE *f = fopen(SYS_POWER_STATE_PATH, "r");
256
257 if (!f)
258 return -1;
259
260 if (fgets(buf, sizeof buf, f) == NULL)
261 rc = -1;
262 else
263 rc = strstr(buf, suspend) != NULL;
264
265 fclose(f);
266 return rc;
267}
268
76700389
BW
269static void suspend_system(const char *suspend)
270{
d3cf5414 271 FILE *f = fopen(SYS_POWER_STATE_PATH, "w");
76700389
BW
272
273 if (!f) {
07b336c9 274 warn(_("open failed: %s"), SYS_POWER_STATE_PATH);
76700389
BW
275 return;
276 }
277
569f3ca2
KZ
278 if (!dryrun) {
279 fprintf(f, "%s\n", suspend);
280 fflush(f);
281 }
76700389
BW
282
283 /* this executes after wake from suspend */
284 fclose(f);
285}
286
287
288static int read_clock_mode(void)
289{
290 FILE *fp;
291 char linebuf[MAX_LINE];
292
293 fp = fopen(ADJTIME_PATH, "r");
294 if (!fp)
f8d87ab1 295 return -1;
76700389
BW
296
297 /* skip first line */
298 if (!fgets(linebuf, MAX_LINE, fp)) {
299 fclose(fp);
f8d87ab1 300 return -1;
76700389
BW
301 }
302
303 /* skip second line */
304 if (!fgets(linebuf, MAX_LINE, fp)) {
305 fclose(fp);
f8d87ab1 306 return -1;
76700389
BW
307 }
308
309 /* read third line */
310 if (!fgets(linebuf, MAX_LINE, fp)) {
311 fclose(fp);
f8d87ab1 312 return -1;
76700389
BW
313 }
314
315 if (strncmp(linebuf, "UTC", 3) == 0)
316 clock_mode = CM_UTC;
317 else if (strncmp(linebuf, "LOCAL", 5) == 0)
318 clock_mode = CM_LOCAL;
319
320 fclose(fp);
321
f8d87ab1 322 return 0;
76700389
BW
323}
324
fcf67294
MO
325/**
326 * print basic alarm settings
327 */
328static int print_alarm(int fd)
329{
330 struct rtc_wkalrm wake;
331 struct rtc_time rtc;
332 struct tm tm;
333 time_t alarm;
334
335 /* First try the preferred RTC_WKALM_RD */
336 if (ioctl(fd, RTC_WKALM_RD, &wake) < 0) {
337 /* Fall back on the non-preferred way of reading wakeups; only
338 * works for alarms < 24 hours from now
339 *
340 * set wake.enabled to 1 and determine from value of the year-1
341 * means disabled
342 */
343 wake.enabled = 1;
344 if (ioctl(fd, RTC_ALM_READ, &wake.time) < 0) {
07b336c9 345 warn(_("read rtc alarm failed"));
fcf67294
MO
346 return -1;
347 }
348 }
349
350 if (wake.enabled != 1 || wake.time.tm_year == -1) {
351 printf(_("alarm: off\n"));
352 return 0;
353 }
354
355 rtc = wake.time;
356
357 memset(&tm, 0, sizeof tm);
358 tm.tm_sec = rtc.tm_sec;
359 tm.tm_min = rtc.tm_min;
360 tm.tm_hour = rtc.tm_hour;
361 tm.tm_mday = rtc.tm_mday;
362 tm.tm_mon = rtc.tm_mon;
363 tm.tm_year = rtc.tm_year;
364 tm.tm_isdst = -1; /* assume the system knows better than the RTC */
365
366 alarm = mktime(&tm);
367 if (alarm == (time_t)-1) {
07b336c9 368 warn(_("convert time failed"));
fcf67294
MO
369 return -1;
370 }
371
372 /* 0 if both UTC, or expresses diff if RTC in local time */
373 alarm += sys_time - rtc_time;
374
07b336c9 375 printf(_("alarm: on %s"), ctime(&alarm));
fcf67294
MO
376 return 0;
377}
378
76700389
BW
379int main(int argc, char **argv)
380{
381 char *devname = DEFAULT_DEVICE;
382 unsigned seconds = 0;
383 char *suspend = DEFAULT_MODE;
384
77f5744c 385 int rc = EXIT_SUCCESS;
76700389
BW
386 int t;
387 int fd;
388 time_t alarm = 0;
389
390 setlocale(LC_ALL, "");
391 bindtextdomain(PACKAGE, LOCALEDIR);
392 textdomain(PACKAGE);
393
569f3ca2 394 while ((t = getopt_long(argc, argv, "ahd:lm:ns:t:uVv",
76700389
BW
395 long_options, NULL)) != EOF) {
396 switch (t) {
397 case 'a':
398 /* CM_AUTO is default */
399 break;
400
401 case 'd':
c1196d3a 402 devname = optarg;
76700389
BW
403 break;
404
405 case 'l':
406 clock_mode = CM_LOCAL;
407 break;
408
409 /* what system power mode to use? for now handle only
410 * standardized mode names; eventually when systems
411 * define their own state names, parse
412 * /sys/power/state.
413 *
414 * "on" is used just to test the RTC alarm mechanism,
415 * bypassing all the wakeup-from-sleep infrastructure.
416 */
417 case 'm':
418 if (strcmp(optarg, "standby") == 0
419 || strcmp(optarg, "mem") == 0
420 || strcmp(optarg, "disk") == 0
421 || strcmp(optarg, "on") == 0
e4b0fc36 422 || strcmp(optarg, "no") == 0
77f5744c 423 || strcmp(optarg, "off") == 0
c15dd93b 424 || strcmp(optarg, "disable") == 0
fcf67294 425 || strcmp(optarg, "show") == 0
76700389 426 ) {
c1196d3a 427 suspend = optarg;
76700389
BW
428 break;
429 }
07b336c9
KZ
430
431 errx(EXIT_FAILURE, _("unrecognized suspend state '%s'"),
432 optarg);
433 break;
76700389 434
569f3ca2
KZ
435 case 'n':
436 dryrun = 1;
437 break;
438
76700389
BW
439 /* alarm time, seconds-to-sleep (relative) */
440 case 's':
07b336c9
KZ
441 seconds = strtol_or_err(optarg,
442 _("failed to parse seconds value"));
76700389
BW
443 break;
444
445 /* alarm time, time_t (absolute, seconds since
446 * 1/1 1970 UTC)
447 */
448 case 't':
07b336c9
KZ
449 alarm = strtol_or_err(optarg,
450 _("failed to parse time_t value"));
76700389
BW
451 break;
452
453 case 'u':
454 clock_mode = CM_UTC;
455 break;
456
457 case 'v':
458 verbose++;
459 break;
460
461 case 'V':
07b336c9 462 printf("%s\n", VERSION_STRING);
76700389
BW
463 exit(EXIT_SUCCESS);
464
465 case 'h':
07b336c9 466 usage(stdout);
76700389 467 default:
07b336c9 468 usage(stderr);
76700389
BW
469 }
470 }
471
472 if (clock_mode == CM_AUTO) {
f8d87ab1 473 if (read_clock_mode() < 0) {
07b336c9
KZ
474 printf(_("%s: assuming RTC uses UTC ...\n"),
475 program_invocation_short_name);
76700389
BW
476 clock_mode = CM_UTC;
477 }
76700389 478 }
2148b051
DB
479 if (verbose)
480 printf(clock_mode == CM_UTC ? _("Using UTC time.\n") :
481 _("Using local time.\n"));
76700389 482
fcf67294
MO
483 if (!alarm && !seconds && strcmp(suspend,"disable") &&
484 strcmp(suspend,"show")) {
485
07b336c9
KZ
486 warnx(_("must provide wake time (see -t and -s options)"));
487 usage(stderr);
76700389
BW
488 }
489
490 /* when devname doesn't start with /dev, append it */
491 if (strncmp(devname, "/dev/", strlen("/dev/")) != 0) {
492 char *new_devname;
493
2ab428f6 494 new_devname = xmalloc(strlen(devname) + strlen("/dev/") + 1);
76700389
BW
495
496 strcpy(new_devname, "/dev/");
497 strcat(new_devname, devname);
76700389
BW
498 devname = new_devname;
499 }
500
e4b0fc36 501 if (strcmp(suspend, "on") != 0 && strcmp(suspend, "no") != 0
07b336c9
KZ
502 && !is_wakeup_enabled(devname))
503 errx(EXIT_FAILURE, _("%s not enabled for wakeup events"), devname);
76700389
BW
504
505 /* this RTC must exist and (if we'll sleep) be wakeup-enabled */
77f5744c
KZ
506#ifdef O_CLOEXEC
507 fd = open(devname, O_RDONLY | O_CLOEXEC);
508#else
76700389 509 fd = open(devname, O_RDONLY);
77f5744c 510#endif
07b336c9
KZ
511 if (fd < 0)
512 err(EXIT_FAILURE, _("open failed: %s"), devname);
76700389
BW
513
514 /* relative or absolute alarm time, normalized to time_t */
f8d87ab1 515 if (get_basetimes(fd) < 0)
76700389
BW
516 exit(EXIT_FAILURE);
517 if (verbose)
518 printf(_("alarm %ld, sys_time %ld, rtc_time %ld, seconds %u\n"),
519 alarm, sys_time, rtc_time, seconds);
77f5744c 520
fcf67294 521 if (strcmp(suspend, "show") && strcmp(suspend, "disable")) {
e6d1dc94
LR
522 if (strcmp(suspend, "no") && strcmp(suspend, "on") &&
523 strcmp(suspend, "off") && is_suspend_available(suspend) <= 0) {
524 errx(EXIT_FAILURE, _("suspend to \"%s\" unavailable"), suspend);
525 }
526
fcf67294
MO
527 /* care about alarm setup only if the show|disable
528 * modes are not set
529 */
530 if (alarm) {
07b336c9
KZ
531 if (alarm < sys_time)
532 errx(EXIT_FAILURE, _("time doesn't go backward to %s"),
533 ctime(&alarm));
fcf67294
MO
534 alarm += sys_time - rtc_time;
535 } else
536 alarm = rtc_time + seconds + 1;
537
538 if (setup_alarm(fd, &alarm) < 0)
539 exit(EXIT_FAILURE);
76700389 540
07b336c9
KZ
541 if (strcmp(suspend, "no") == 0 || strcmp(suspend, "on") == 0)
542 printf(_("%s: wakeup using %s at %s"),
543 program_invocation_short_name, devname,
544 ctime(&alarm));
545 else
546 printf(_("%s: wakeup from \"%s\" using %s at %s"),
547 program_invocation_short_name, suspend, devname,
fcf67294
MO
548 ctime(&alarm));
549 fflush(stdout);
550 usleep(10 * 1000);
551 }
76700389 552
ecd55f96
KZ
553 if (strcmp(suspend, "no") == 0) {
554 if (verbose)
555 printf(_("suspend mode: no; leaving\n"));
07b336c9 556 dryrun = 1; /* to skip disabling alarm at the end */
ecd55f96 557
77f5744c
KZ
558 } else if (strcmp(suspend, "off") == 0) {
559 char *arg[4];
560 int i = 0;
561
ecd55f96
KZ
562 if (verbose)
563 printf(_("suspend mode: off; executing %s\n"),
564 _PATH_SHUTDOWN);
77f5744c
KZ
565 arg[i++] = _PATH_SHUTDOWN;
566 arg[i++] = "-P";
567 arg[i++] = "now";
568 arg[i] = NULL;
569
569f3ca2
KZ
570 if (!dryrun) {
571 execv(arg[0], arg);
77f5744c 572
07b336c9 573 warn(_("unable to execute %s"), _PATH_SHUTDOWN);
569f3ca2
KZ
574 rc = EXIT_FAILURE;
575 }
ecd55f96
KZ
576
577 } else if (strcmp(suspend, "on") == 0) {
76700389
BW
578 unsigned long data;
579
ecd55f96
KZ
580 if (verbose)
581 printf(_("suspend mode: on; reading rtc\n"));
582
569f3ca2
KZ
583 if (!dryrun) {
584 do {
585 t = read(fd, &data, sizeof data);
586 if (t < 0) {
07b336c9 587 warn(_("rtc read failed"));
569f3ca2
KZ
588 break;
589 }
590 if (verbose)
591 printf("... %s: %03lx\n", devname, data);
592 } while (!(data & RTC_AF));
593 }
ecd55f96 594
c15dd93b
MO
595 } else if (strcmp(suspend, "disable") == 0) {
596 /* just break, alarm gets disabled in the end */
597 if (verbose)
598 printf(_("suspend mode: disable; disabling alarm\n"));
fcf67294
MO
599
600 } else if(strcmp(suspend,"show") == 0) {
601 if (verbose)
602 printf(_("suspend mode: show; printing alarm info\n"));
603 if (print_alarm(fd))
604 rc = EXIT_FAILURE;
605 dryrun = 1; /* don't really disable alarm in the end, just show */
606
ecd55f96
KZ
607 } else {
608 if (verbose)
609 printf(_("suspend mode: %s; suspending system\n"), suspend);
610 sync();
611 suspend_system(suspend);
76700389
BW
612 }
613
569f3ca2 614 if (!dryrun && ioctl(fd, RTC_AIE_OFF, 0) < 0)
07b336c9 615 warn(_("disable rtc alarm interrupt failed"));
76700389
BW
616
617 close(fd);
77f5744c 618 return rc;
76700389 619}