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>
54 #include <machine/apm_bios.h>
57 #define DEFAULT_ACTIVE_PERCENT 75
58 #define DEFAULT_IDLE_PERCENT 50
59 #define DEFAULT_POLL_INTERVAL 250 /* Poll interval in milliseconds */
74 const char *modes[] = {
80 #define ACPIAC "hw.acpi.acline"
81 #define PMUAC "dev.pmu.0.acline"
82 #define APMDEV "/dev/apm"
83 #define DEVDPIPE "/var/run/devd.pipe"
84 #define DEVCTL_MAXBUF 1024
86 static int read_usage_times(int *load);
87 static int read_freqs(int *numfreqs, int **freqs, int **power,
88 int minfreq, int maxfreq);
89 static int set_freq(int freq);
90 static void acline_init(void);
91 static void acline_read(void);
92 static int devd_init(void);
93 static void devd_close(void);
94 static void handle_sigs(int sig);
95 static void parse_mode(char *arg, int *mode, int ch);
96 static void usage(void);
98 /* Sysctl data structures. */
99 static int cp_times_mib[2];
100 static int freq_mib[4];
101 static int levels_mib[4];
102 static int acline_mib[4];
103 static size_t acline_mib_len;
106 static int cpu_running_mark;
107 static int cpu_idle_mark;
108 static int poll_ival;
111 static volatile sig_atomic_t exit_requested;
112 static power_src_t acline_status;
122 static int apm_fd = -1;
124 static int devd_pipe = -1;
126 #define DEVD_RETRY_INTERVAL 60 /* seconds */
127 static struct timeval tried_devd;
130 read_usage_times(int *load)
132 static long *cp_times = NULL, *cp_times_old = NULL;
133 static int ncpus = 0;
135 int error, cpu, i, total;
137 if (cp_times == NULL) {
139 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
142 if ((cp_times = malloc(cp_times_len)) == NULL)
144 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
149 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
152 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
153 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
159 for (cpu = 0; cpu < ncpus; cpu++) {
161 for (i = 0; i < CPUSTATES; i++) {
162 total += cp_times[cpu * CPUSTATES + i] -
163 cp_times_old[cpu * CPUSTATES + i];
167 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
168 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
172 memcpy(cp_times_old, cp_times, cp_times_len);
178 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
180 char *freqstr, *p, *q;
184 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
186 if ((freqstr = malloc(len)) == NULL)
188 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
192 for (p = freqstr; *p != '\0'; p++)
196 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
200 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
205 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
209 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
215 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
216 ((*freqs)[j] <= maxfreq || maxfreq == -1))
222 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
239 len = sizeof(curfreq);
240 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
242 warn("error reading current CPU frequency");
252 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
261 get_freq_id(int freq, int *freqs, int numfreqs)
265 while (i < numfreqs) {
274 * Try to use ACPI to find the AC line status. If this fails, fall back
275 * to APM. If nothing succeeds, we'll just run in default mode.
282 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
283 acline_mode = ac_sysctl;
285 warnx("using sysctl for AC line status");
287 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
288 acline_mode = ac_sysctl;
290 warnx("using sysctl for AC line status");
293 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
295 warnx("using APM for AC line status");
296 acline_mode = ac_apm;
299 warnx("unable to determine AC line status");
300 acline_mode = ac_none;
307 if (acline_mode == ac_acpi_devd) {
308 char buf[DEVCTL_MAXBUF], *ptr;
312 rlen = read(devd_pipe, buf, sizeof(buf));
313 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
315 warnx("lost devd connection, switching to sysctl");
317 acline_mode = ac_sysctl;
321 (ptr = strstr(buf, "system=ACPI")) != NULL &&
322 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
323 (ptr = strstr(ptr, "notify=")) != NULL &&
324 sscanf(ptr, "notify=%x", ¬ify) == 1)
325 acline_status = (notify ? SRC_AC : SRC_BATTERY);
327 if (acline_mode == ac_sysctl) {
331 len = sizeof(acline);
332 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
334 acline_status = (acline ? SRC_AC : SRC_BATTERY);
336 acline_status = SRC_UNKNOWN;
339 if (acline_mode == ac_apm) {
340 struct apm_info info;
342 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
343 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
347 acline_mode = ac_none;
348 acline_status = SRC_UNKNOWN;
352 /* try to (re)connect to devd */
353 if (acline_mode == ac_sysctl) {
356 gettimeofday(&now, NULL);
357 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
358 if (devd_init() >= 0) {
360 warnx("using devd for AC line status");
361 acline_mode = ac_acpi_devd;
371 struct sockaddr_un devd_addr;
373 bzero(&devd_addr, sizeof(devd_addr));
374 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
376 warn("%s(): socket()", __func__);
380 devd_addr.sun_family = PF_LOCAL;
381 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
382 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
383 sizeof(devd_addr)) == -1) {
385 warn("%s(): connect()", __func__);
391 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
393 warn("%s(): fcntl()", __func__);
410 parse_mode(char *arg, int *mode, int ch)
413 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
415 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
417 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
418 *mode = MODE_ADAPTIVE;
419 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
420 *mode = MODE_HIADAPTIVE;
422 errx(1, "bad option: -%c %s", (char)ch, optarg);
426 handle_sigs(int __unused sig)
437 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
442 main(int argc, char * argv[])
444 struct timeval timeout;
447 struct pidfh *pfh = NULL;
448 const char *pidfile = NULL;
449 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
450 int minfreq = -1, maxfreq = -1;
451 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
452 uint64_t mjoules_used;
455 /* Default mode for all AC states is adaptive. */
456 mode_ac = mode_none = MODE_HIADAPTIVE;
457 mode_battery = MODE_ADAPTIVE;
458 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
459 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
460 poll_ival = DEFAULT_POLL_INTERVAL;
464 /* User must be root to control frequencies. */
466 errx(1, "must be root to run");
468 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
471 parse_mode(optarg, &mode_ac, ch);
474 parse_mode(optarg, &mode_battery, ch);
477 cpu_idle_mark = atoi(optarg);
478 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
479 warnx("%d is not a valid percent",
485 minfreq = atoi(optarg);
487 warnx("%d is not a valid CPU frequency",
493 maxfreq = atoi(optarg);
495 warnx("%d is not a valid CPU frequency",
501 parse_mode(optarg, &mode_none, ch);
504 poll_ival = atoi(optarg);
506 warnx("poll interval is in units of ms");
514 cpu_running_mark = atoi(optarg);
515 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
516 warnx("%d is not a valid percent",
530 /* Poll interval is in units of ms. */
533 /* Look up various sysctl MIBs. */
535 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
536 err(1, "lookup kern.cp_times");
538 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
539 err(1, "lookup freq");
541 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
542 err(1, "lookup freq_levels");
544 /* Check if we can read the load and supported freqs. */
545 if (read_usage_times(NULL))
546 err(1, "read_usage_times");
547 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
548 err(1, "error reading supported CPU frequencies");
550 errx(1, "no CPU frequencies in user-specified range");
552 /* Run in the background unless in verbose mode. */
556 pfh = pidfile_open(pidfile, 0600, &otherpid);
558 if (errno == EEXIST) {
559 errx(1, "powerd already running, pid: %d",
562 warn("cannot open pid file");
564 if (daemon(0, 0) != 0) {
565 warn("cannot enter daemon mode, exiting");
573 /* Decide whether to use ACPI or APM to read the AC line status. */
577 * Exit cleanly on signals.
579 signal(SIGINT, handle_sigs);
580 signal(SIGTERM, handle_sigs);
582 freq = initfreq = curfreq = get_freq();
583 i = get_freq_id(curfreq, freqs, numfreqs);
588 * If we are in adaptive mode and the current frequency is outside the
589 * user-defined range, adjust it to be within the user-defined range.
592 if (acline_status > SRC_UNKNOWN)
593 errx(1, "invalid AC line status %d", acline_status);
594 if ((acline_status == SRC_AC &&
595 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
596 (acline_status == SRC_BATTERY &&
597 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
598 (acline_status == SRC_UNKNOWN &&
599 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
600 /* Read the current frequency. */
601 len = sizeof(curfreq);
602 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
604 warn("error reading current CPU frequency");
606 if (curfreq < freqs[numfreqs - 1]) {
608 printf("CPU frequency is below user-defined "
609 "minimum; changing frequency to %d "
610 "MHz\n", freqs[numfreqs - 1]);
612 if (set_freq(freqs[numfreqs - 1]) != 0) {
613 warn("error setting CPU freq %d",
614 freqs[numfreqs - 1]);
616 } else if (curfreq > freqs[0]) {
618 printf("CPU frequency is above user-defined "
619 "maximum; changing frequency to %d "
622 if (set_freq(freqs[0]) != 0) {
623 warn("error setting CPU freq %d",
633 if (devd_pipe >= 0) {
634 FD_SET(devd_pipe, &fdset);
635 nfds = devd_pipe + 1;
639 if (mode == MODE_HIADAPTIVE || idle < 120)
645 timeout.tv_sec = to / 1000000;
646 timeout.tv_usec = to % 1000000;
647 select(nfds, &fdset, NULL, &fdset, &timeout);
649 /* If the user requested we quit, print some statistics. */
650 if (exit_requested) {
651 if (vflag && mjoules_used != 0)
652 printf("total joules used: %u.%03u\n",
653 (u_int)(mjoules_used / 1000),
654 (int)mjoules_used % 1000);
658 /* Read the current AC status and record the mode. */
660 switch (acline_status) {
671 errx(1, "invalid AC line status %d", acline_status);
674 /* Read the current frequency. */
675 if (idle % 32 == 0) {
676 if ((curfreq = get_freq()) == 0)
678 i = get_freq_id(curfreq, freqs, numfreqs);
682 /* Keep a sum of all power actually used. */
685 (mwatts[i] * (poll_ival / 1000)) / 1000;
688 /* Always switch to the lowest frequency in min mode. */
689 if (mode == MODE_MIN) {
690 freq = freqs[numfreqs - 1];
691 if (curfreq != freq) {
693 printf("now operating on %s power; "
694 "changing frequency to %d MHz\n",
695 modes[acline_status], freq);
698 if (set_freq(freq) != 0) {
699 warn("error setting CPU freq %d",
707 /* Always switch to the highest frequency in max mode. */
708 if (mode == MODE_MAX) {
710 if (curfreq != freq) {
712 printf("now operating on %s power; "
713 "changing frequency to %d MHz\n",
714 modes[acline_status], freq);
717 if (set_freq(freq) != 0) {
718 warn("error setting CPU freq %d",
726 /* Adaptive mode; get the current CPU usage times. */
727 if (read_usage_times(&load)) {
729 warn("read_usage_times() failed");
733 if (mode == MODE_ADAPTIVE) {
734 if (load > cpu_running_mark) {
735 if (load > 95 || load > cpu_running_mark * 2)
738 freq = freq * load / cpu_running_mark;
741 } else if (load < cpu_idle_mark &&
742 curfreq * load < freqs[get_freq_id(
743 freq * 7 / 8, freqs, numfreqs)] *
746 if (freq < freqs[numfreqs - 1])
747 freq = freqs[numfreqs - 1];
749 } else { /* MODE_HIADAPTIVE */
750 if (load > cpu_running_mark / 2) {
751 if (load > 95 || load > cpu_running_mark)
754 freq = freq * load * 2 / cpu_running_mark;
755 if (freq > freqs[0] * 2)
757 } else if (load < cpu_idle_mark / 2 &&
758 curfreq * load < freqs[get_freq_id(
759 freq * 31 / 32, freqs, numfreqs)] *
760 cpu_running_mark / 2) {
761 freq = freq * 31 / 32;
762 if (freq < freqs[numfreqs - 1])
763 freq = freqs[numfreqs - 1];
767 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
768 load, curfreq, i, freq);
770 j = get_freq_id(freq, freqs, numfreqs);
773 printf("changing clock"
774 " speed from %d MHz to %d MHz\n",
778 if (set_freq(freqs[j]))
779 warn("error setting CPU frequency %d",
783 if (set_freq(initfreq))
784 warn("error setting CPU frequency %d", initfreq);