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>
55 #include <machine/apm_bios.h>
58 #define DEFAULT_ACTIVE_PERCENT 75
59 #define DEFAULT_IDLE_PERCENT 50
60 #define DEFAULT_POLL_INTERVAL 250 /* Poll interval in milliseconds */
75 static const char *modes[] = {
81 #define ACPIAC "hw.acpi.acline"
82 #define PMUAC "dev.pmu.0.acline"
83 #define APMDEV "/dev/apm"
84 #define DEVDPIPE "/var/run/devd.pipe"
85 #define DEVCTL_MAXBUF 1024
87 static int read_usage_times(int *load);
88 static int read_freqs(int *numfreqs, int **freqs, int **power,
89 int minfreq, int maxfreq);
90 static int set_freq(int freq);
91 static void acline_init(void);
92 static void acline_read(void);
93 static int devd_init(void);
94 static void devd_close(void);
95 static void handle_sigs(int sig);
96 static void parse_mode(char *arg, int *mode, int ch);
97 static void usage(void);
99 /* Sysctl data structures. */
100 static int cp_times_mib[2];
101 static int freq_mib[4];
102 static int levels_mib[4];
103 static int acline_mib[4];
104 static size_t acline_mib_len;
107 static int cpu_running_mark;
108 static int cpu_idle_mark;
109 static int poll_ival;
112 static volatile sig_atomic_t exit_requested;
113 static power_src_t acline_status;
123 static int apm_fd = -1;
125 static int devd_pipe = -1;
127 #define DEVD_RETRY_INTERVAL 60 /* seconds */
128 static struct timeval tried_devd;
131 * This function returns summary load of all CPUs. It was made so
132 * intentionally to not reduce performance in scenarios when several
133 * threads are processing requests as a pipeline -- running one at
134 * a time on different CPUs and waiting for each other.
137 read_usage_times(int *load)
139 static long *cp_times = NULL, *cp_times_old = NULL;
140 static int ncpus = 0;
142 int error, cpu, i, total;
144 if (cp_times == NULL) {
146 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
149 if ((cp_times = malloc(cp_times_len)) == NULL)
151 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
156 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
159 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
160 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
166 for (cpu = 0; cpu < ncpus; cpu++) {
168 for (i = 0; i < CPUSTATES; i++) {
169 total += cp_times[cpu * CPUSTATES + i] -
170 cp_times_old[cpu * CPUSTATES + i];
174 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
175 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
179 memcpy(cp_times_old, cp_times, cp_times_len);
185 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
187 char *freqstr, *p, *q;
191 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
193 if ((freqstr = malloc(len)) == NULL)
195 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
199 for (p = freqstr; *p != '\0'; p++)
203 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
207 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
212 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
216 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
222 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
223 ((*freqs)[j] <= maxfreq || maxfreq == -1))
229 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
246 len = sizeof(curfreq);
247 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
249 warn("error reading current CPU frequency");
259 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
268 get_freq_id(int freq, int *freqs, int numfreqs)
272 while (i < numfreqs) {
281 * Try to use ACPI to find the AC line status. If this fails, fall back
282 * to APM. If nothing succeeds, we'll just run in default mode.
288 acline_status = SRC_UNKNOWN;
290 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
291 acline_mode = ac_sysctl;
293 warnx("using sysctl for AC line status");
295 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
296 acline_mode = ac_sysctl;
298 warnx("using sysctl for AC line status");
301 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
303 warnx("using APM for AC line status");
304 acline_mode = ac_apm;
307 warnx("unable to determine AC line status");
308 acline_mode = ac_none;
315 if (acline_mode == ac_acpi_devd) {
316 char buf[DEVCTL_MAXBUF], *ptr;
320 rlen = read(devd_pipe, buf, sizeof(buf));
321 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
323 warnx("lost devd connection, switching to sysctl");
325 acline_mode = ac_sysctl;
329 (ptr = strstr(buf, "system=ACPI")) != NULL &&
330 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
331 (ptr = strstr(ptr, "notify=")) != NULL &&
332 sscanf(ptr, "notify=%x", ¬ify) == 1)
333 acline_status = (notify ? SRC_AC : SRC_BATTERY);
335 if (acline_mode == ac_sysctl) {
339 len = sizeof(acline);
340 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
342 acline_status = (acline ? SRC_AC : SRC_BATTERY);
344 acline_status = SRC_UNKNOWN;
347 if (acline_mode == ac_apm) {
348 struct apm_info info;
350 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
351 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
355 acline_mode = ac_none;
356 acline_status = SRC_UNKNOWN;
360 /* try to (re)connect to devd */
361 if (acline_mode == ac_sysctl) {
364 gettimeofday(&now, NULL);
365 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
366 if (devd_init() >= 0) {
368 warnx("using devd for AC line status");
369 acline_mode = ac_acpi_devd;
379 struct sockaddr_un devd_addr;
381 bzero(&devd_addr, sizeof(devd_addr));
382 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
384 warn("%s(): socket()", __func__);
388 devd_addr.sun_family = PF_LOCAL;
389 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
390 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
391 sizeof(devd_addr)) == -1) {
393 warn("%s(): connect()", __func__);
399 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
401 warn("%s(): fcntl()", __func__);
418 parse_mode(char *arg, int *mode, int ch)
421 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
423 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
425 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
426 *mode = MODE_ADAPTIVE;
427 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
428 *mode = MODE_HIADAPTIVE;
430 errx(1, "bad option: -%c %s", (char)ch, optarg);
434 handle_sigs(int __unused sig)
445 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
450 main(int argc, char * argv[])
452 struct timeval timeout;
455 struct pidfh *pfh = NULL;
456 const char *pidfile = NULL;
457 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
458 int minfreq = -1, maxfreq = -1;
459 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
460 uint64_t mjoules_used;
463 /* Default mode for all AC states is adaptive. */
464 mode_ac = mode_none = MODE_HIADAPTIVE;
465 mode_battery = MODE_ADAPTIVE;
466 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
467 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
468 poll_ival = DEFAULT_POLL_INTERVAL;
472 /* User must be root to control frequencies. */
474 errx(1, "must be root to run");
476 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
479 parse_mode(optarg, &mode_ac, ch);
482 parse_mode(optarg, &mode_battery, ch);
485 cpu_idle_mark = atoi(optarg);
486 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
487 warnx("%d is not a valid percent",
493 minfreq = atoi(optarg);
495 warnx("%d is not a valid CPU frequency",
501 maxfreq = atoi(optarg);
503 warnx("%d is not a valid CPU frequency",
509 parse_mode(optarg, &mode_none, ch);
512 poll_ival = atoi(optarg);
514 warnx("poll interval is in units of ms");
522 cpu_running_mark = atoi(optarg);
523 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
524 warnx("%d is not a valid percent",
538 /* Poll interval is in units of ms. */
541 /* Look up various sysctl MIBs. */
543 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
544 err(1, "lookup kern.cp_times");
546 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
547 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
549 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
550 err(1, "lookup freq_levels");
552 /* Check if we can read the load and supported freqs. */
553 if (read_usage_times(NULL))
554 err(1, "read_usage_times");
555 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
556 err(1, "error reading supported CPU frequencies");
558 errx(1, "no CPU frequencies in user-specified range");
560 /* Run in the background unless in verbose mode. */
564 pfh = pidfile_open(pidfile, 0600, &otherpid);
566 if (errno == EEXIST) {
567 errx(1, "powerd already running, pid: %d",
570 warn("cannot open pid file");
572 if (daemon(0, 0) != 0) {
573 warn("cannot enter daemon mode, exiting");
581 /* Decide whether to use ACPI or APM to read the AC line status. */
585 * Exit cleanly on signals.
587 signal(SIGINT, handle_sigs);
588 signal(SIGTERM, handle_sigs);
590 freq = initfreq = curfreq = get_freq();
591 i = get_freq_id(curfreq, freqs, numfreqs);
596 * If we are in adaptive mode and the current frequency is outside the
597 * user-defined range, adjust it to be within the user-defined range.
600 if (acline_status > SRC_UNKNOWN)
601 errx(1, "invalid AC line status %d", acline_status);
602 if ((acline_status == SRC_AC &&
603 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
604 (acline_status == SRC_BATTERY &&
605 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
606 (acline_status == SRC_UNKNOWN &&
607 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
608 /* Read the current frequency. */
609 len = sizeof(curfreq);
610 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
612 warn("error reading current CPU frequency");
614 if (curfreq < freqs[numfreqs - 1]) {
616 printf("CPU frequency is below user-defined "
617 "minimum; changing frequency to %d "
618 "MHz\n", freqs[numfreqs - 1]);
620 if (set_freq(freqs[numfreqs - 1]) != 0) {
621 warn("error setting CPU freq %d",
622 freqs[numfreqs - 1]);
624 } else if (curfreq > freqs[0]) {
626 printf("CPU frequency is above user-defined "
627 "maximum; changing frequency to %d "
630 if (set_freq(freqs[0]) != 0) {
631 warn("error setting CPU freq %d",
641 if (devd_pipe >= 0) {
642 FD_SET(devd_pipe, &fdset);
643 nfds = devd_pipe + 1;
647 if (mode == MODE_HIADAPTIVE || idle < 120)
653 timeout.tv_sec = to / 1000000;
654 timeout.tv_usec = to % 1000000;
655 select(nfds, &fdset, NULL, &fdset, &timeout);
657 /* If the user requested we quit, print some statistics. */
658 if (exit_requested) {
659 if (vflag && mjoules_used != 0)
660 printf("total joules used: %u.%03u\n",
661 (u_int)(mjoules_used / 1000),
662 (int)mjoules_used % 1000);
666 /* Read the current AC status and record the mode. */
668 switch (acline_status) {
679 errx(1, "invalid AC line status %d", acline_status);
682 /* Read the current frequency. */
683 if (idle % 32 == 0) {
684 if ((curfreq = get_freq()) == 0)
686 i = get_freq_id(curfreq, freqs, numfreqs);
690 /* Keep a sum of all power actually used. */
693 (mwatts[i] * (poll_ival / 1000)) / 1000;
696 /* Always switch to the lowest frequency in min mode. */
697 if (mode == MODE_MIN) {
698 freq = freqs[numfreqs - 1];
699 if (curfreq != freq) {
701 printf("now operating on %s power; "
702 "changing frequency to %d MHz\n",
703 modes[acline_status], freq);
706 if (set_freq(freq) != 0) {
707 warn("error setting CPU freq %d",
715 /* Always switch to the highest frequency in max mode. */
716 if (mode == MODE_MAX) {
718 if (curfreq != freq) {
720 printf("now operating on %s power; "
721 "changing frequency to %d MHz\n",
722 modes[acline_status], freq);
725 if (set_freq(freq) != 0) {
726 warn("error setting CPU freq %d",
734 /* Adaptive mode; get the current CPU usage times. */
735 if (read_usage_times(&load)) {
737 warn("read_usage_times() failed");
741 if (mode == MODE_ADAPTIVE) {
742 if (load > cpu_running_mark) {
743 if (load > 95 || load > cpu_running_mark * 2)
746 freq = freq * load / cpu_running_mark;
749 } else if (load < cpu_idle_mark &&
750 curfreq * load < freqs[get_freq_id(
751 freq * 7 / 8, freqs, numfreqs)] *
754 if (freq < freqs[numfreqs - 1])
755 freq = freqs[numfreqs - 1];
757 } else { /* MODE_HIADAPTIVE */
758 if (load > cpu_running_mark / 2) {
759 if (load > 95 || load > cpu_running_mark)
762 freq = freq * load * 2 / cpu_running_mark;
763 if (freq > freqs[0] * 2)
765 } else if (load < cpu_idle_mark / 2 &&
766 curfreq * load < freqs[get_freq_id(
767 freq * 31 / 32, freqs, numfreqs)] *
768 cpu_running_mark / 2) {
769 freq = freq * 31 / 32;
770 if (freq < freqs[numfreqs - 1])
771 freq = freqs[numfreqs - 1];
775 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
776 load, curfreq, i, freq);
778 j = get_freq_id(freq, freqs, numfreqs);
781 printf("changing clock"
782 " speed from %d MHz to %d MHz\n",
786 if (set_freq(freqs[j]))
787 warn("error setting CPU frequency %d",
791 if (set_freq(initfreq))
792 warn("error setting CPU frequency %d", initfreq);