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 PMUAC "dev.pmu.0.acline"
78 #define APMDEV "/dev/apm"
79 #define DEVDPIPE "/var/run/devd.pipe"
80 #define DEVCTL_MAXBUF 1024
82 static int read_usage_times(int *load);
83 static int read_freqs(int *numfreqs, int **freqs, int **power);
84 static int set_freq(int freq);
85 static void acline_init(void);
86 static void acline_read(void);
87 static int devd_init(void);
88 static void devd_close(void);
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_times_mib[2];
95 static int freq_mib[4];
96 static int levels_mib[4];
97 static int acline_mib[4];
98 static size_t acline_mib_len;
101 static int cpu_running_mark;
102 static int cpu_idle_mark;
103 static int poll_ival;
106 static volatile sig_atomic_t exit_requested;
107 static power_src_t acline_status;
117 static int apm_fd = -1;
119 static int devd_pipe = -1;
121 #define DEVD_RETRY_INTERVAL 60 /* seconds */
122 static struct timeval tried_devd;
125 read_usage_times(int *load)
127 static long *cp_times = NULL, *cp_times_old = NULL;
128 static int ncpus = 0;
130 int error, cpu, i, total;
132 if (cp_times == NULL) {
134 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
137 if ((cp_times = malloc(cp_times_len)) == NULL)
139 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
144 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
147 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
148 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
154 for (cpu = 0; cpu < ncpus; cpu++) {
156 for (i = 0; i < CPUSTATES; i++) {
157 total += cp_times[cpu * CPUSTATES + i] -
158 cp_times_old[cpu * CPUSTATES + i];
162 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
163 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
167 memcpy(cp_times_old, cp_times, cp_times_len);
173 read_freqs(int *numfreqs, int **freqs, int **power)
175 char *freqstr, *p, *q;
179 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
181 if ((freqstr = malloc(len)) == NULL)
183 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
187 for (p = freqstr; *p != '\0'; p++)
191 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
195 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
200 for (i = 0, p = freqstr; i < *numfreqs; i++) {
204 if (sscanf(p, "%d/%d", &(*freqs)[i], &(*power)[i]) != 2) {
223 len = sizeof(curfreq);
224 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
226 warn("error reading current CPU frequency");
236 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
245 get_freq_id(int freq, int *freqs, int numfreqs)
249 while (i < numfreqs) {
258 * Try to use ACPI to find the AC line status. If this fails, fall back
259 * to APM. If nothing succeeds, we'll just run in default mode.
266 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
267 acline_mode = ac_sysctl;
269 warnx("using sysctl for AC line status");
271 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
272 acline_mode = ac_sysctl;
274 warnx("using sysctl for AC line status");
277 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
279 warnx("using APM for AC line status");
280 acline_mode = ac_apm;
283 warnx("unable to determine AC line status");
284 acline_mode = ac_none;
291 if (acline_mode == ac_acpi_devd) {
292 char buf[DEVCTL_MAXBUF], *ptr;
296 rlen = read(devd_pipe, buf, sizeof(buf));
297 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
299 warnx("lost devd connection, switching to sysctl");
301 acline_mode = ac_sysctl;
305 (ptr = strstr(buf, "system=ACPI")) != NULL &&
306 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
307 (ptr = strstr(ptr, "notify=")) != NULL &&
308 sscanf(ptr, "notify=%x", ¬ify) == 1)
309 acline_status = (notify ? SRC_AC : SRC_BATTERY);
311 if (acline_mode == ac_sysctl) {
315 len = sizeof(acline);
316 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
318 acline_status = (acline ? SRC_AC : SRC_BATTERY);
320 acline_status = SRC_UNKNOWN;
323 if (acline_mode == ac_apm) {
324 struct apm_info info;
326 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
327 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
331 acline_mode = ac_none;
332 acline_status = SRC_UNKNOWN;
336 /* try to (re)connect to devd */
337 if (acline_mode == ac_sysctl) {
340 gettimeofday(&now, NULL);
341 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
342 if (devd_init() >= 0) {
344 warnx("using devd for AC line status");
345 acline_mode = ac_acpi_devd;
355 struct sockaddr_un devd_addr;
357 bzero(&devd_addr, sizeof(devd_addr));
358 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
360 warn("%s(): socket()", __func__);
364 devd_addr.sun_family = PF_LOCAL;
365 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
366 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
367 sizeof(devd_addr)) == -1) {
369 warn("%s(): connect()", __func__);
375 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
377 warn("%s(): fcntl()", __func__);
394 parse_mode(char *arg, int *mode, int ch)
397 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
399 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
401 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
402 *mode = MODE_ADAPTIVE;
403 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
404 *mode = MODE_HIADAPTIVE;
406 errx(1, "bad option: -%c %s", (char)ch, optarg);
410 handle_sigs(int __unused sig)
421 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
426 main(int argc, char * argv[])
428 struct timeval timeout;
431 struct pidfh *pfh = NULL;
432 const char *pidfile = NULL;
433 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
434 int ch, mode, mode_ac, mode_battery, mode_none;
435 uint64_t mjoules_used;
438 /* Default mode for all AC states is adaptive. */
439 mode_ac = mode_none = MODE_HIADAPTIVE;
440 mode_battery = MODE_ADAPTIVE;
441 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
442 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
443 poll_ival = DEFAULT_POLL_INTERVAL;
447 /* User must be root to control frequencies. */
449 errx(1, "must be root to run");
451 while ((ch = getopt(argc, argv, "a:b:i:n:p:P:r:v")) != -1)
454 parse_mode(optarg, &mode_ac, ch);
457 parse_mode(optarg, &mode_battery, ch);
460 cpu_idle_mark = atoi(optarg);
461 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
462 warnx("%d is not a valid percent",
468 parse_mode(optarg, &mode_none, ch);
471 poll_ival = atoi(optarg);
473 warnx("poll interval is in units of ms");
481 cpu_running_mark = atoi(optarg);
482 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
483 warnx("%d is not a valid percent",
497 /* Poll interval is in units of ms. */
500 /* Look up various sysctl MIBs. */
502 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
503 err(1, "lookup kern.cp_times");
505 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
506 err(1, "lookup freq");
508 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
509 err(1, "lookup freq_levels");
511 /* Check if we can read the load and supported freqs. */
512 if (read_usage_times(NULL))
513 err(1, "read_usage_times");
514 if (read_freqs(&numfreqs, &freqs, &mwatts))
515 err(1, "error reading supported CPU frequencies");
517 /* Run in the background unless in verbose mode. */
521 pfh = pidfile_open(pidfile, 0600, &otherpid);
523 if (errno == EEXIST) {
524 errx(1, "powerd already running, pid: %d",
527 warn("cannot open pid file");
529 if (daemon(0, 0) != 0) {
530 warn("cannot enter daemon mode, exiting");
538 /* Decide whether to use ACPI or APM to read the AC line status. */
542 * Exit cleanly on signals.
544 signal(SIGINT, handle_sigs);
545 signal(SIGTERM, handle_sigs);
547 freq = initfreq = get_freq();
553 if (devd_pipe >= 0) {
554 FD_SET(devd_pipe, &fdset);
555 nfds = devd_pipe + 1;
559 timeout.tv_sec = poll_ival / 1000000;
560 timeout.tv_usec = poll_ival % 1000000;
561 select(nfds, &fdset, NULL, &fdset, &timeout);
563 /* If the user requested we quit, print some statistics. */
564 if (exit_requested) {
565 if (vflag && mjoules_used != 0)
566 printf("total joules used: %u.%03u\n",
567 (u_int)(mjoules_used / 1000),
568 (int)mjoules_used % 1000);
572 /* Read the current AC status and record the mode. */
574 switch (acline_status) {
585 errx(1, "invalid AC line status %d", acline_status);
588 /* Read the current frequency. */
589 if ((curfreq = get_freq()) == 0)
592 i = get_freq_id(curfreq, freqs, numfreqs);
595 /* Keep a sum of all power actually used. */
598 (mwatts[i] * (poll_ival / 1000)) / 1000;
601 /* Always switch to the lowest frequency in min mode. */
602 if (mode == MODE_MIN) {
603 freq = freqs[numfreqs - 1];
604 if (curfreq != freq) {
606 printf("now operating on %s power; "
607 "changing frequency to %d MHz\n",
608 modes[acline_status], freq);
610 if (set_freq(freq) != 0) {
611 warn("error setting CPU freq %d",
619 /* Always switch to the highest frequency in max mode. */
620 if (mode == MODE_MAX) {
622 if (curfreq != freq) {
624 printf("now operating on %s power; "
625 "changing frequency to %d MHz\n",
626 modes[acline_status], freq);
628 if (set_freq(freq) != 0) {
629 warn("error setting CPU freq %d",
637 /* Adaptive mode; get the current CPU usage times. */
638 if (read_usage_times(&load)) {
640 warn("read_usage_times() failed");
644 if (mode == MODE_ADAPTIVE) {
645 if (load > cpu_running_mark) {
646 if (load > 95 || load > cpu_running_mark * 2)
649 freq = freq * load / cpu_running_mark;
652 } else if (load < cpu_idle_mark &&
653 curfreq * load < freqs[get_freq_id(
654 freq * 7 / 8, freqs, numfreqs)] *
657 if (freq < freqs[numfreqs - 1])
658 freq = freqs[numfreqs - 1];
660 } else { /* MODE_HIADAPTIVE */
661 if (load > cpu_running_mark / 2) {
662 if (load > 95 || load > cpu_running_mark)
665 freq = freq * load * 2 / cpu_running_mark;
666 if (freq > freqs[0] * 2)
668 } else if (load < cpu_idle_mark / 2 &&
669 curfreq * load < freqs[get_freq_id(
670 freq * 31 / 32, freqs, numfreqs)] *
671 cpu_running_mark / 2) {
672 freq = freq * 31 / 32;
673 if (freq < freqs[numfreqs - 1])
674 freq = freqs[numfreqs - 1];
678 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
679 load, curfreq, i, freq);
681 j = get_freq_id(freq, freqs, numfreqs);
684 printf("changing clock"
685 " speed from %d MHz to %d MHz\n",
688 if (set_freq(freqs[j]))
689 warn("error setting CPU frequency %d",
693 if (set_freq(initfreq))
694 warn("error setting CPU frequency %d", initfreq);