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 int minfreq, int maxfreq);
85 static int set_freq(int freq);
86 static void acline_init(void);
87 static void acline_read(void);
88 static int devd_init(void);
89 static void devd_close(void);
90 static void handle_sigs(int sig);
91 static void parse_mode(char *arg, int *mode, int ch);
92 static void usage(void);
94 /* Sysctl data structures. */
95 static int cp_times_mib[2];
96 static int freq_mib[4];
97 static int levels_mib[4];
98 static int acline_mib[4];
99 static size_t acline_mib_len;
102 static int cpu_running_mark;
103 static int cpu_idle_mark;
104 static int poll_ival;
107 static volatile sig_atomic_t exit_requested;
108 static power_src_t acline_status;
118 static int apm_fd = -1;
120 static int devd_pipe = -1;
122 #define DEVD_RETRY_INTERVAL 60 /* seconds */
123 static struct timeval tried_devd;
126 read_usage_times(int *load)
128 static long *cp_times = NULL, *cp_times_old = NULL;
129 static int ncpus = 0;
131 int error, cpu, i, total;
133 if (cp_times == NULL) {
135 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
138 if ((cp_times = malloc(cp_times_len)) == NULL)
140 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
145 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
148 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
149 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
155 for (cpu = 0; cpu < ncpus; cpu++) {
157 for (i = 0; i < CPUSTATES; i++) {
158 total += cp_times[cpu * CPUSTATES + i] -
159 cp_times_old[cpu * CPUSTATES + i];
163 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
164 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
168 memcpy(cp_times_old, cp_times, cp_times_len);
174 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
176 char *freqstr, *p, *q;
180 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
182 if ((freqstr = malloc(len)) == NULL)
184 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
188 for (p = freqstr; *p != '\0'; p++)
192 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
196 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
201 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
205 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
211 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
212 ((*freqs)[j] <= maxfreq || maxfreq == -1))
218 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
235 len = sizeof(curfreq);
236 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
238 warn("error reading current CPU frequency");
248 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
257 get_freq_id(int freq, int *freqs, int numfreqs)
261 while (i < numfreqs) {
270 * Try to use ACPI to find the AC line status. If this fails, fall back
271 * to APM. If nothing succeeds, we'll just run in default mode.
278 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
279 acline_mode = ac_sysctl;
281 warnx("using sysctl for AC line status");
283 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
284 acline_mode = ac_sysctl;
286 warnx("using sysctl for AC line status");
289 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
291 warnx("using APM for AC line status");
292 acline_mode = ac_apm;
295 warnx("unable to determine AC line status");
296 acline_mode = ac_none;
303 if (acline_mode == ac_acpi_devd) {
304 char buf[DEVCTL_MAXBUF], *ptr;
308 rlen = read(devd_pipe, buf, sizeof(buf));
309 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
311 warnx("lost devd connection, switching to sysctl");
313 acline_mode = ac_sysctl;
317 (ptr = strstr(buf, "system=ACPI")) != NULL &&
318 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
319 (ptr = strstr(ptr, "notify=")) != NULL &&
320 sscanf(ptr, "notify=%x", ¬ify) == 1)
321 acline_status = (notify ? SRC_AC : SRC_BATTERY);
323 if (acline_mode == ac_sysctl) {
327 len = sizeof(acline);
328 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
330 acline_status = (acline ? SRC_AC : SRC_BATTERY);
332 acline_status = SRC_UNKNOWN;
335 if (acline_mode == ac_apm) {
336 struct apm_info info;
338 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
339 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
343 acline_mode = ac_none;
344 acline_status = SRC_UNKNOWN;
348 /* try to (re)connect to devd */
349 if (acline_mode == ac_sysctl) {
352 gettimeofday(&now, NULL);
353 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
354 if (devd_init() >= 0) {
356 warnx("using devd for AC line status");
357 acline_mode = ac_acpi_devd;
367 struct sockaddr_un devd_addr;
369 bzero(&devd_addr, sizeof(devd_addr));
370 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
372 warn("%s(): socket()", __func__);
376 devd_addr.sun_family = PF_LOCAL;
377 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
378 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
379 sizeof(devd_addr)) == -1) {
381 warn("%s(): connect()", __func__);
387 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
389 warn("%s(): fcntl()", __func__);
406 parse_mode(char *arg, int *mode, int ch)
409 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
411 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
413 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
414 *mode = MODE_ADAPTIVE;
415 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
416 *mode = MODE_HIADAPTIVE;
418 errx(1, "bad option: -%c %s", (char)ch, optarg);
422 handle_sigs(int __unused sig)
433 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
438 main(int argc, char * argv[])
440 struct timeval timeout;
443 struct pidfh *pfh = NULL;
444 const char *pidfile = NULL;
445 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
446 int ch, mode, mode_ac, mode_battery, mode_none;
447 int minfreq = -1, maxfreq = -1;
448 uint64_t mjoules_used;
451 /* Default mode for all AC states is adaptive. */
452 mode_ac = mode_none = MODE_HIADAPTIVE;
453 mode_battery = MODE_ADAPTIVE;
454 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
455 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
456 poll_ival = DEFAULT_POLL_INTERVAL;
460 /* User must be root to control frequencies. */
462 errx(1, "must be root to run");
464 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
467 parse_mode(optarg, &mode_ac, ch);
470 parse_mode(optarg, &mode_battery, ch);
473 cpu_idle_mark = atoi(optarg);
474 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
475 warnx("%d is not a valid percent",
481 minfreq = atoi(optarg);
483 warnx("%d is not a valid CPU frequency",
489 maxfreq = atoi(optarg);
491 warnx("%d is not a valid CPU frequency",
497 parse_mode(optarg, &mode_none, ch);
500 poll_ival = atoi(optarg);
502 warnx("poll interval is in units of ms");
510 cpu_running_mark = atoi(optarg);
511 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
512 warnx("%d is not a valid percent",
526 /* Poll interval is in units of ms. */
529 /* Look up various sysctl MIBs. */
531 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
532 err(1, "lookup kern.cp_times");
534 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
535 err(1, "lookup freq");
537 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
538 err(1, "lookup freq_levels");
540 /* Check if we can read the load and supported freqs. */
541 if (read_usage_times(NULL))
542 err(1, "read_usage_times");
543 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
544 err(1, "error reading supported CPU frequencies");
546 errx(1, "no CPU frequencies in user-specified range");
548 /* Run in the background unless in verbose mode. */
552 pfh = pidfile_open(pidfile, 0600, &otherpid);
554 if (errno == EEXIST) {
555 errx(1, "powerd already running, pid: %d",
558 warn("cannot open pid file");
560 if (daemon(0, 0) != 0) {
561 warn("cannot enter daemon mode, exiting");
569 /* Decide whether to use ACPI or APM to read the AC line status. */
573 * Exit cleanly on signals.
575 signal(SIGINT, handle_sigs);
576 signal(SIGTERM, handle_sigs);
578 freq = initfreq = get_freq();
583 * If we are in adaptive mode and the current frequency is outside the
584 * user-defined range, adjust it to be within the user-defined range.
587 if (acline_status > SRC_UNKNOWN)
588 errx(1, "invalid AC line status %d", acline_status);
589 if ((acline_status == SRC_AC &&
590 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
591 (acline_status == SRC_BATTERY &&
592 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
593 (acline_status == SRC_UNKNOWN &&
594 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
595 /* Read the current frequency. */
596 len = sizeof(curfreq);
597 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
599 warn("error reading current CPU frequency");
601 if (curfreq < freqs[numfreqs - 1]) {
603 printf("CPU frequency is below user-defined "
604 "minimum; changing frequency to %d "
605 "MHz\n", freqs[numfreqs - 1]);
607 if (set_freq(freqs[numfreqs - 1]) != 0) {
608 warn("error setting CPU freq %d",
609 freqs[numfreqs - 1]);
611 } else if (curfreq > freqs[0]) {
613 printf("CPU frequency is above user-defined "
614 "maximum; changing frequency to %d "
617 if (set_freq(freqs[0]) != 0) {
618 warn("error setting CPU freq %d",
627 if (devd_pipe >= 0) {
628 FD_SET(devd_pipe, &fdset);
629 nfds = devd_pipe + 1;
633 timeout.tv_sec = poll_ival / 1000000;
634 timeout.tv_usec = poll_ival % 1000000;
635 select(nfds, &fdset, NULL, &fdset, &timeout);
637 /* If the user requested we quit, print some statistics. */
638 if (exit_requested) {
639 if (vflag && mjoules_used != 0)
640 printf("total joules used: %u.%03u\n",
641 (u_int)(mjoules_used / 1000),
642 (int)mjoules_used % 1000);
646 /* Read the current AC status and record the mode. */
648 switch (acline_status) {
659 errx(1, "invalid AC line status %d", acline_status);
662 /* Read the current frequency. */
663 if ((curfreq = get_freq()) == 0)
666 i = get_freq_id(curfreq, freqs, numfreqs);
669 /* Keep a sum of all power actually used. */
672 (mwatts[i] * (poll_ival / 1000)) / 1000;
675 /* Always switch to the lowest frequency in min mode. */
676 if (mode == MODE_MIN) {
677 freq = freqs[numfreqs - 1];
678 if (curfreq != freq) {
680 printf("now operating on %s power; "
681 "changing frequency to %d MHz\n",
682 modes[acline_status], freq);
684 if (set_freq(freq) != 0) {
685 warn("error setting CPU freq %d",
693 /* Always switch to the highest frequency in max mode. */
694 if (mode == MODE_MAX) {
696 if (curfreq != freq) {
698 printf("now operating on %s power; "
699 "changing frequency to %d MHz\n",
700 modes[acline_status], freq);
702 if (set_freq(freq) != 0) {
703 warn("error setting CPU freq %d",
711 /* Adaptive mode; get the current CPU usage times. */
712 if (read_usage_times(&load)) {
714 warn("read_usage_times() failed");
718 if (mode == MODE_ADAPTIVE) {
719 if (load > cpu_running_mark) {
720 if (load > 95 || load > cpu_running_mark * 2)
723 freq = freq * load / cpu_running_mark;
726 } else if (load < cpu_idle_mark &&
727 curfreq * load < freqs[get_freq_id(
728 freq * 7 / 8, freqs, numfreqs)] *
731 if (freq < freqs[numfreqs - 1])
732 freq = freqs[numfreqs - 1];
734 } else { /* MODE_HIADAPTIVE */
735 if (load > cpu_running_mark / 2) {
736 if (load > 95 || load > cpu_running_mark)
739 freq = freq * load * 2 / cpu_running_mark;
740 if (freq > freqs[0] * 2)
742 } else if (load < cpu_idle_mark / 2 &&
743 curfreq * load < freqs[get_freq_id(
744 freq * 31 / 32, freqs, numfreqs)] *
745 cpu_running_mark / 2) {
746 freq = freq * 31 / 32;
747 if (freq < freqs[numfreqs - 1])
748 freq = freqs[numfreqs - 1];
752 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
753 load, curfreq, i, freq);
755 j = get_freq_id(freq, freqs, numfreqs);
758 printf("changing clock"
759 " speed from %d MHz to %d MHz\n",
762 if (set_freq(freqs[j]))
763 warn("error setting CPU frequency %d",
767 if (set_freq(initfreq))
768 warn("error setting CPU frequency %d", initfreq);