2 * Copyright (c) 2004 Colin Percival
3 * Copyright (c) 2005 Nate Lawson
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted providing that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
24 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25 * POSSIBILITY OF SUCH DAMAGE.
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
31 #include <sys/types.h>
32 #include <sys/param.h>
33 #include <sys/ioctl.h>
34 #include <sys/sysctl.h>
35 #include <sys/resource.h>
36 #include <sys/socket.h>
51 #include <machine/apm_bios.h>
54 #define DEFAULT_ACTIVE_PERCENT 65
55 #define DEFAULT_IDLE_PERCENT 90
56 #define DEFAULT_POLL_INTERVAL 500 /* Poll interval in milliseconds */
70 const char *modes[] = {
76 #define ACPIAC "hw.acpi.acline"
77 #define APMDEV "/dev/apm"
78 #define DEVDPIPE "/var/run/devd.pipe"
79 #define DEVCTL_MAXBUF 1024
81 static int read_usage_times(long *idle, long *total);
82 static int read_freqs(int *numfreqs, int **freqs, int **power);
83 static int set_freq(int freq);
84 static void acline_init(void);
85 static int acline_read(void);
86 static int devd_init(void);
87 static void devd_close(void);
88 static void *devd_read(void *arg);
89 static void handle_sigs(int sig);
90 static void parse_mode(char *arg, int *mode, int ch);
91 static void usage(void);
93 /* Sysctl data structures. */
94 static int cp_time_mib[2];
95 static int freq_mib[4];
96 static int levels_mib[4];
97 static int acline_mib[3];
99 /* devd-cached value provided by our thread. */
100 static int devd_acline;
103 static int cpu_running_mark;
104 static int cpu_idle_mark;
105 static int poll_ival;
109 static int devd_pipe;
110 static pthread_t devd_thread;
111 static int exit_requested;
114 read_usage_times(long *idle, long *total)
116 static long idle_old, total_old;
117 long cp_time[CPUSTATES], i, total_new;
121 cp_time_len = sizeof(cp_time);
122 error = sysctl(cp_time_mib, 2, cp_time, &cp_time_len, NULL, 0);
125 for (total_new = 0, i = 0; i < CPUSTATES; i++)
126 total_new += cp_time[i];
129 *idle = cp_time[CP_IDLE] - idle_old;
131 *total = total_new - total_old;
133 idle_old = cp_time[CP_IDLE];
134 total_old = total_new;
140 read_freqs(int *numfreqs, int **freqs, int **power)
142 char *freqstr, *p, *q;
146 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
148 if ((freqstr = malloc(len)) == NULL)
150 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
154 for (p = freqstr; *p != '\0'; p++)
158 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
162 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
167 for (i = 0, p = freqstr; i < *numfreqs; i++) {
171 if (sscanf(p, "%d/%d", &(*freqs)[i], &(*power)[i]) != 2) {
188 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
197 * Try to use ACPI to find the AC line status. If this fails, fall back
198 * to APM. If nothing succeeds, we'll just run in default mode. If we are
199 * using ACPI, try opening a pipe to devd to detect AC line events.
209 len = sizeof(acline);
210 if (sysctlbyname(ACPIAC, &acline, &len, NULL, 0) == 0) {
212 if (sysctlnametomib(ACPIAC, acline_mib, &len))
213 err(1, "lookup acline");
215 /* Read line status once so that we have an initial value. */
216 devd_acline = acline_read();
219 * Try connecting to the devd pipe and start a read thread
222 if ((devd_pipe = devd_init()) >= 0) {
223 if (pthread_create(&devd_thread, NULL, devd_read,
225 err(1, "pthread_create devd thread");
228 "unable to connect to devd pipe, using polling mode instead");
231 apm_fd = open(APMDEV, O_RDONLY);
234 "cannot read AC line status, using default settings");
244 struct apm_info info;
247 acline = SRC_UNKNOWN;
248 len = sizeof(acline);
251 * Get state from our devd thread, the ACPI sysctl, or APM. We
252 * prefer sources in this order.
255 acline = devd_acline;
256 else if (sysctl(acline_mib, 3, &acline, &len, NULL, 0) == 0)
257 acline = acline ? SRC_AC : SRC_BATTERY;
259 else if (apm_fd != -1 && ioctl(apm_fd, APMIO_GETINFO, &info) == 0)
260 acline = info.ai_acline ? SRC_AC : SRC_BATTERY;
269 struct sockaddr_un devd_addr;
272 bzero(&devd_addr, sizeof(devd_addr));
273 if ((devd_sock = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
275 warn("failed to create devd socket");
279 devd_addr.sun_family = PF_LOCAL;
280 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
281 if (connect(devd_sock, (struct sockaddr *)&devd_addr,
282 sizeof(devd_addr)) == -1) {
297 pthread_kill(devd_thread, SIGTERM);
302 * This loop runs as a separate thread. It reads events from devd, but
303 * spends most of its time blocked in select(2).
308 char buf[DEVCTL_MAXBUF], *ptr;
310 int fd, notify, rlen;
315 while (!exit_requested) {
317 if (select(fd + 1, &fdset, NULL, NULL, NULL) < 0)
319 if (!FD_ISSET(fd, &fdset))
322 /* Read the notify string, devd NULL-terminates it. */
323 rlen = read(fd, buf, sizeof(buf));
329 "devd disappeared, downgrading to polling mode");
332 * Keep trying to reconnect to devd but sleep in
333 * between to avoid wasting CPU cycles.
335 while (!exit_requested && (fd = devd_init()) < 0)
342 "devd came back, upgrading to event mode");
347 /* Loosely match the notify string. */
348 if ((ptr = strstr(buf, "system=ACPI")) != NULL &&
349 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
350 (ptr = strstr(ptr, "notify=")) != NULL) {
351 if (sscanf(ptr, "notify=%x", ¬ify) != 1) {
352 warnx("bad devd notify string");
355 devd_acline = notify ? SRC_AC : SRC_BATTERY;
363 parse_mode(char *arg, int *mode, int ch)
366 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
368 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
370 else if (strcmp(arg, "adaptive") == 0)
371 *mode = MODE_ADAPTIVE;
373 errx(1, "bad option: -%c %s", (char)ch, optarg);
377 handle_sigs(int __unused sig)
388 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
393 main(int argc, char * argv[])
395 struct pidfh *pfh = NULL;
396 const char *pidfile = NULL;
398 int acline, curfreq, *freqs, i, *mwatts, numfreqs;
399 int ch, mode, mode_ac, mode_battery, mode_none;
400 uint64_t mjoules_used;
403 /* Default mode for all AC states is adaptive. */
404 mode_ac = mode_battery = mode_none = MODE_ADAPTIVE;
405 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
406 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
407 poll_ival = DEFAULT_POLL_INTERVAL;
412 /* User must be root to control frequencies. */
414 errx(1, "must be root to run");
416 while ((ch = getopt(argc, argv, "a:b:i:n:p:P:r:v")) != EOF)
419 parse_mode(optarg, &mode_ac, ch);
422 parse_mode(optarg, &mode_battery, ch);
425 cpu_idle_mark = atoi(optarg);
426 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
427 warnx("%d is not a valid percent",
433 parse_mode(optarg, &mode_none, ch);
436 poll_ival = atoi(optarg);
438 warnx("poll interval is in units of ms");
446 cpu_running_mark = atoi(optarg);
447 if (cpu_running_mark < 0 || cpu_running_mark > 100) {
448 warnx("%d is not a valid percent",
462 /* Poll interval is in units of ms. */
465 /* Look up various sysctl MIBs. */
467 if (sysctlnametomib("kern.cp_time", cp_time_mib, &len))
468 err(1, "lookup kern.cp_time");
470 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
471 err(1, "lookup freq");
473 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
474 err(1, "lookup freq_levels");
476 /* Check if we can read the idle time and supported freqs. */
477 if (read_usage_times(NULL, NULL))
478 err(1, "read_usage_times");
479 if (read_freqs(&numfreqs, &freqs, &mwatts))
480 err(1, "error reading supported CPU frequencies");
483 * Exit cleanly on signals; devd may send a SIGPIPE if it dies. We
484 * do this before acline_init() since it may create a thread and we
485 * want it to inherit our signal mask.
487 signal(SIGINT, handle_sigs);
488 signal(SIGTERM, handle_sigs);
489 signal(SIGPIPE, SIG_IGN);
491 /* Decide whether to use ACPI or APM to read the AC line status. */
494 /* Run in the background unless in verbose mode. */
498 pfh = pidfile_open(pidfile, 0600, &otherpid);
500 if (errno == EEXIST) {
501 errx(1, "powerd already running, pid: %d",
504 warn("cannot open pid file");
506 if (daemon(0, 0) != 0) {
507 warn("cannot enter daemon mode, exiting");
517 /* Check status every few milliseconds. */
520 /* If the user requested we quit, print some statistics. */
521 if (exit_requested) {
522 if (vflag && mjoules_used != 0)
523 printf("total joules used: %u.%03u\n",
524 (u_int)(mjoules_used / 1000),
525 (int)mjoules_used % 1000);
529 /* Read the current AC status and record the mode. */
530 acline = acline_read();
542 errx(1, "invalid AC line status %d", acline);
545 /* Read the current frequency. */
546 len = sizeof(curfreq);
547 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
549 warn("error reading current CPU frequency");
554 for (i = 0; i < numfreqs; i++) {
555 if (freqs[i] == curfreq)
559 /* Keep a sum of all power actually used. */
560 if (i < numfreqs && mwatts[i] != -1)
562 (mwatts[i] * (poll_ival / 1000)) / 1000;
565 /* Always switch to the lowest frequency in min mode. */
566 if (mode == MODE_MIN) {
567 if (curfreq != freqs[numfreqs - 1]) {
569 printf("now operating on %s power; "
570 "changing frequency to %d MHz\n",
571 modes[acline], freqs[numfreqs - 1]);
573 if (set_freq(freqs[numfreqs - 1]) != 0) {
574 warn("error setting CPU freq %d",
575 freqs[numfreqs - 1]);
582 /* Always switch to the highest frequency in max mode. */
583 if (mode == MODE_MAX) {
584 if (curfreq != freqs[0]) {
586 printf("now operating on %s power; "
587 "changing frequency to %d MHz\n",
588 modes[acline], freqs[0]);
590 if (set_freq(freqs[0]) != 0) {
591 warn("error setting CPU freq %d",
599 /* Adaptive mode; get the current CPU usage times. */
600 if (read_usage_times(&idle, &total)) {
602 warn("read_usage_times() failed");
607 * If we're idle less than the active mark, bump up two levels.
608 * If we're idle more than the idle mark, drop down one level.
610 for (i = 0; i < numfreqs - 1; i++) {
611 if (freqs[i] == curfreq)
614 if (idle < (total * cpu_running_mark) / 100 &&
615 curfreq < freqs[0]) {
620 printf("idle time < %d%%, increasing clock"
621 " speed from %d MHz to %d MHz\n",
622 cpu_running_mark, curfreq, freqs[i]);
624 if (set_freq(freqs[i]))
625 err(1, "error setting CPU frequency %d",
627 } else if (idle > (total * cpu_idle_mark) / 100 &&
628 curfreq > freqs[numfreqs - 1]) {
631 printf("idle time > %d%%, decreasing clock"
632 " speed from %d MHz to %d MHz\n",
633 cpu_idle_mark, curfreq, freqs[i]);
635 if (set_freq(freqs[i]) != 0)
636 warn("error setting CPU frequency %d",