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/param.h>
32 #include <sys/ioctl.h>
33 #include <sys/sysctl.h>
34 #include <sys/resource.h>
35 #include <sys/socket.h>
50 #include <machine/apm_bios.h>
53 #define DEFAULT_ACTIVE_PERCENT 75
54 #define DEFAULT_IDLE_PERCENT 50
55 #define DEFAULT_POLL_INTERVAL 250 /* 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(int *load);
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 void acline_read(void);
86 static int devd_init(void);
87 static void devd_close(void);
88 static void handle_sigs(int sig);
89 static void parse_mode(char *arg, int *mode, int ch);
90 static void usage(void);
92 /* Sysctl data structures. */
93 static int cp_times_mib[2];
94 static int freq_mib[4];
95 static int levels_mib[4];
96 static int acline_mib[3];
99 static int cpu_running_mark;
100 static int cpu_idle_mark;
101 static int poll_ival;
104 static volatile sig_atomic_t exit_requested;
105 static power_src_t acline_status;
115 static int apm_fd = -1;
117 static int devd_pipe = -1;
119 #define DEVD_RETRY_INTERVAL 60 /* seconds */
120 static struct timeval tried_devd;
123 read_usage_times(int *load)
125 static long *cp_times = NULL, *cp_times_old = NULL;
126 static int ncpus = 0;
128 int error, cpu, i, total;
130 if (cp_times == NULL) {
132 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
135 if ((cp_times = malloc(cp_times_len)) == NULL)
137 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
142 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
145 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
146 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
152 for (cpu = 0; cpu < ncpus; cpu++) {
154 for (i = 0; i < CPUSTATES; i++) {
155 total += cp_times[cpu * CPUSTATES + i] -
156 cp_times_old[cpu * CPUSTATES + i];
160 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
161 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
165 memcpy(cp_times_old, cp_times, cp_times_len);
171 read_freqs(int *numfreqs, int **freqs, int **power)
173 char *freqstr, *p, *q;
177 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
179 if ((freqstr = malloc(len)) == NULL)
181 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
185 for (p = freqstr; *p != '\0'; p++)
189 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
193 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
198 for (i = 0, p = freqstr; i < *numfreqs; i++) {
202 if (sscanf(p, "%d/%d", &(*freqs)[i], &(*power)[i]) != 2) {
221 len = sizeof(curfreq);
222 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
224 warn("error reading current CPU frequency");
234 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
243 get_freq_id(int freq, int *freqs, int numfreqs)
247 while (i < numfreqs) {
256 * Try to use ACPI to find the AC line status. If this fails, fall back
257 * to APM. If nothing succeeds, we'll just run in default mode.
265 if (sysctlnametomib(ACPIAC, acline_mib, &len) == 0) {
266 acline_mode = ac_acpi_sysctl;
268 warnx("using sysctl for AC line status");
270 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
272 warnx("using APM for AC line status");
273 acline_mode = ac_apm;
276 warnx("unable to determine AC line status");
277 acline_mode = ac_none;
284 if (acline_mode == ac_acpi_devd) {
285 char buf[DEVCTL_MAXBUF], *ptr;
289 rlen = read(devd_pipe, buf, sizeof(buf));
290 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
292 warnx("lost devd connection, switching to sysctl");
294 acline_mode = ac_acpi_sysctl;
298 (ptr = strstr(buf, "system=ACPI")) != NULL &&
299 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
300 (ptr = strstr(ptr, "notify=")) != NULL &&
301 sscanf(ptr, "notify=%x", ¬ify) == 1)
302 acline_status = (notify ? SRC_AC : SRC_BATTERY);
304 if (acline_mode == ac_acpi_sysctl) {
308 len = sizeof(acline);
309 if (sysctl(acline_mib, 3, &acline, &len, NULL, 0) == 0)
310 acline_status = (acline ? SRC_AC : SRC_BATTERY);
312 acline_status = SRC_UNKNOWN;
315 if (acline_mode == ac_apm) {
316 struct apm_info info;
318 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
319 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
323 acline_mode = ac_none;
324 acline_status = SRC_UNKNOWN;
328 /* try to (re)connect to devd */
329 if (acline_mode == ac_acpi_sysctl) {
332 gettimeofday(&now, NULL);
333 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
334 if (devd_init() >= 0) {
336 warnx("using devd for AC line status");
337 acline_mode = ac_acpi_devd;
347 struct sockaddr_un devd_addr;
349 bzero(&devd_addr, sizeof(devd_addr));
350 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
352 warn("%s(): socket()", __func__);
356 devd_addr.sun_family = PF_LOCAL;
357 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
358 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
359 sizeof(devd_addr)) == -1) {
361 warn("%s(): connect()", __func__);
367 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
369 warn("%s(): fcntl()", __func__);
386 parse_mode(char *arg, int *mode, int ch)
389 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
391 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
393 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
394 *mode = MODE_ADAPTIVE;
395 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
396 *mode = MODE_HIADAPTIVE;
398 errx(1, "bad option: -%c %s", (char)ch, optarg);
402 handle_sigs(int __unused sig)
413 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
418 main(int argc, char * argv[])
420 struct timeval timeout;
423 struct pidfh *pfh = NULL;
424 const char *pidfile = NULL;
425 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
426 int ch, mode, mode_ac, mode_battery, mode_none;
427 uint64_t mjoules_used;
430 /* Default mode for all AC states is adaptive. */
431 mode_ac = mode_none = MODE_HIADAPTIVE;
432 mode_battery = MODE_ADAPTIVE;
433 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
434 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
435 poll_ival = DEFAULT_POLL_INTERVAL;
439 /* User must be root to control frequencies. */
441 errx(1, "must be root to run");
443 while ((ch = getopt(argc, argv, "a:b:i:n:p:P:r:v")) != -1)
446 parse_mode(optarg, &mode_ac, ch);
449 parse_mode(optarg, &mode_battery, ch);
452 cpu_idle_mark = atoi(optarg);
453 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
454 warnx("%d is not a valid percent",
460 parse_mode(optarg, &mode_none, ch);
463 poll_ival = atoi(optarg);
465 warnx("poll interval is in units of ms");
473 cpu_running_mark = atoi(optarg);
474 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
475 warnx("%d is not a valid percent",
489 /* Poll interval is in units of ms. */
492 /* Look up various sysctl MIBs. */
494 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
495 err(1, "lookup kern.cp_times");
497 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
498 err(1, "lookup freq");
500 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
501 err(1, "lookup freq_levels");
503 /* Check if we can read the load and supported freqs. */
504 if (read_usage_times(NULL))
505 err(1, "read_usage_times");
506 if (read_freqs(&numfreqs, &freqs, &mwatts))
507 err(1, "error reading supported CPU frequencies");
509 /* Run in the background unless in verbose mode. */
513 pfh = pidfile_open(pidfile, 0600, &otherpid);
515 if (errno == EEXIST) {
516 errx(1, "powerd already running, pid: %d",
519 warn("cannot open pid file");
521 if (daemon(0, 0) != 0) {
522 warn("cannot enter daemon mode, exiting");
530 /* Decide whether to use ACPI or APM to read the AC line status. */
534 * Exit cleanly on signals.
536 signal(SIGINT, handle_sigs);
537 signal(SIGTERM, handle_sigs);
539 freq = initfreq = get_freq();
545 if (devd_pipe >= 0) {
546 FD_SET(devd_pipe, &fdset);
547 nfds = devd_pipe + 1;
551 timeout.tv_sec = poll_ival / 1000000;
552 timeout.tv_usec = poll_ival % 1000000;
553 select(nfds, &fdset, NULL, &fdset, &timeout);
555 /* If the user requested we quit, print some statistics. */
556 if (exit_requested) {
557 if (vflag && mjoules_used != 0)
558 printf("total joules used: %u.%03u\n",
559 (u_int)(mjoules_used / 1000),
560 (int)mjoules_used % 1000);
564 /* Read the current AC status and record the mode. */
566 switch (acline_status) {
577 errx(1, "invalid AC line status %d", acline_status);
580 /* Read the current frequency. */
581 if ((curfreq = get_freq()) == 0)
584 i = get_freq_id(curfreq, freqs, numfreqs);
587 /* Keep a sum of all power actually used. */
590 (mwatts[i] * (poll_ival / 1000)) / 1000;
593 /* Always switch to the lowest frequency in min mode. */
594 if (mode == MODE_MIN) {
595 freq = freqs[numfreqs - 1];
596 if (curfreq != freq) {
598 printf("now operating on %s power; "
599 "changing frequency to %d MHz\n",
600 modes[acline_status], freq);
602 if (set_freq(freq) != 0) {
603 warn("error setting CPU freq %d",
611 /* Always switch to the highest frequency in max mode. */
612 if (mode == MODE_MAX) {
614 if (curfreq != freq) {
616 printf("now operating on %s power; "
617 "changing frequency to %d MHz\n",
618 modes[acline_status], freq);
620 if (set_freq(freq) != 0) {
621 warn("error setting CPU freq %d",
629 /* Adaptive mode; get the current CPU usage times. */
630 if (read_usage_times(&load)) {
632 warn("read_usage_times() failed");
636 if (mode == MODE_ADAPTIVE) {
637 if (load > cpu_running_mark) {
638 if (load > 95 || load > cpu_running_mark * 2)
641 freq = freq * load / cpu_running_mark;
644 } else if (load < cpu_idle_mark &&
645 curfreq * load < freqs[get_freq_id(
646 freq * 7 / 8, freqs, numfreqs)] *
649 if (freq < freqs[numfreqs - 1])
650 freq = freqs[numfreqs - 1];
652 } else { /* MODE_HIADAPTIVE */
653 if (load > cpu_running_mark / 2) {
654 if (load > 95 || load > cpu_running_mark)
657 freq = freq * load * 2 / cpu_running_mark;
658 if (freq > freqs[0] * 2)
660 } else if (load < cpu_idle_mark / 2 &&
661 curfreq * load < freqs[get_freq_id(
662 freq * 31 / 32, freqs, numfreqs)] *
663 cpu_running_mark / 2) {
664 freq = freq * 31 / 32;
665 if (freq < freqs[numfreqs - 1])
666 freq = freqs[numfreqs - 1];
670 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
671 load, curfreq, i, freq);
673 j = get_freq_id(freq, freqs, numfreqs);
676 printf("changing clock"
677 " speed from %d MHz to %d MHz\n",
680 if (set_freq(freqs[j]))
681 warn("error setting CPU frequency %d",
685 if (set_freq(initfreq))
686 warn("error setting CPU frequency %d", initfreq);