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.
277 acline_status = SRC_UNKNOWN;
279 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
280 acline_mode = ac_sysctl;
282 warnx("using sysctl for AC line status");
284 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
285 acline_mode = ac_sysctl;
287 warnx("using sysctl for AC line status");
290 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
292 warnx("using APM for AC line status");
293 acline_mode = ac_apm;
296 warnx("unable to determine AC line status");
297 acline_mode = ac_none;
304 if (acline_mode == ac_acpi_devd) {
305 char buf[DEVCTL_MAXBUF], *ptr;
309 rlen = read(devd_pipe, buf, sizeof(buf));
310 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
312 warnx("lost devd connection, switching to sysctl");
314 acline_mode = ac_sysctl;
318 (ptr = strstr(buf, "system=ACPI")) != NULL &&
319 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
320 (ptr = strstr(ptr, "notify=")) != NULL &&
321 sscanf(ptr, "notify=%x", ¬ify) == 1)
322 acline_status = (notify ? SRC_AC : SRC_BATTERY);
324 if (acline_mode == ac_sysctl) {
328 len = sizeof(acline);
329 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
331 acline_status = (acline ? SRC_AC : SRC_BATTERY);
333 acline_status = SRC_UNKNOWN;
336 if (acline_mode == ac_apm) {
337 struct apm_info info;
339 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
340 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
344 acline_mode = ac_none;
345 acline_status = SRC_UNKNOWN;
349 /* try to (re)connect to devd */
350 if (acline_mode == ac_sysctl) {
353 gettimeofday(&now, NULL);
354 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
355 if (devd_init() >= 0) {
357 warnx("using devd for AC line status");
358 acline_mode = ac_acpi_devd;
368 struct sockaddr_un devd_addr;
370 bzero(&devd_addr, sizeof(devd_addr));
371 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
373 warn("%s(): socket()", __func__);
377 devd_addr.sun_family = PF_LOCAL;
378 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
379 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
380 sizeof(devd_addr)) == -1) {
382 warn("%s(): connect()", __func__);
388 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
390 warn("%s(): fcntl()", __func__);
407 parse_mode(char *arg, int *mode, int ch)
410 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
412 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
414 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
415 *mode = MODE_ADAPTIVE;
416 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
417 *mode = MODE_HIADAPTIVE;
419 errx(1, "bad option: -%c %s", (char)ch, optarg);
423 handle_sigs(int __unused sig)
434 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
439 main(int argc, char * argv[])
441 struct timeval timeout;
444 struct pidfh *pfh = NULL;
445 const char *pidfile = NULL;
446 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
447 int ch, mode, mode_ac, mode_battery, mode_none;
448 int minfreq = -1, maxfreq = -1;
449 uint64_t mjoules_used;
452 /* Default mode for all AC states is adaptive. */
453 mode_ac = mode_none = MODE_HIADAPTIVE;
454 mode_battery = MODE_ADAPTIVE;
455 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
456 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
457 poll_ival = DEFAULT_POLL_INTERVAL;
461 /* User must be root to control frequencies. */
463 errx(1, "must be root to run");
465 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
468 parse_mode(optarg, &mode_ac, ch);
471 parse_mode(optarg, &mode_battery, ch);
474 cpu_idle_mark = atoi(optarg);
475 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
476 warnx("%d is not a valid percent",
482 minfreq = atoi(optarg);
484 warnx("%d is not a valid CPU frequency",
490 maxfreq = atoi(optarg);
492 warnx("%d is not a valid CPU frequency",
498 parse_mode(optarg, &mode_none, ch);
501 poll_ival = atoi(optarg);
503 warnx("poll interval is in units of ms");
511 cpu_running_mark = atoi(optarg);
512 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
513 warnx("%d is not a valid percent",
527 /* Poll interval is in units of ms. */
530 /* Look up various sysctl MIBs. */
532 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
533 err(1, "lookup kern.cp_times");
535 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
536 err(1, "lookup freq");
538 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
539 err(1, "lookup freq_levels");
541 /* Check if we can read the load and supported freqs. */
542 if (read_usage_times(NULL))
543 err(1, "read_usage_times");
544 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
545 err(1, "error reading supported CPU frequencies");
547 errx(1, "no CPU frequencies in user-specified range");
549 /* Run in the background unless in verbose mode. */
553 pfh = pidfile_open(pidfile, 0600, &otherpid);
555 if (errno == EEXIST) {
556 errx(1, "powerd already running, pid: %d",
559 warn("cannot open pid file");
561 if (daemon(0, 0) != 0) {
562 warn("cannot enter daemon mode, exiting");
570 /* Decide whether to use ACPI or APM to read the AC line status. */
574 * Exit cleanly on signals.
576 signal(SIGINT, handle_sigs);
577 signal(SIGTERM, handle_sigs);
579 freq = initfreq = get_freq();
584 * If we are in adaptive mode and the current frequency is outside the
585 * user-defined range, adjust it to be within the user-defined range.
588 if (acline_status > SRC_UNKNOWN)
589 errx(1, "invalid AC line status %d", acline_status);
590 if ((acline_status == SRC_AC &&
591 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
592 (acline_status == SRC_BATTERY &&
593 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
594 (acline_status == SRC_UNKNOWN &&
595 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
596 /* Read the current frequency. */
597 len = sizeof(curfreq);
598 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
600 warn("error reading current CPU frequency");
602 if (curfreq < freqs[numfreqs - 1]) {
604 printf("CPU frequency is below user-defined "
605 "minimum; changing frequency to %d "
606 "MHz\n", freqs[numfreqs - 1]);
608 if (set_freq(freqs[numfreqs - 1]) != 0) {
609 warn("error setting CPU freq %d",
610 freqs[numfreqs - 1]);
612 } else if (curfreq > freqs[0]) {
614 printf("CPU frequency is above user-defined "
615 "maximum; changing frequency to %d "
618 if (set_freq(freqs[0]) != 0) {
619 warn("error setting CPU freq %d",
628 if (devd_pipe >= 0) {
629 FD_SET(devd_pipe, &fdset);
630 nfds = devd_pipe + 1;
634 timeout.tv_sec = poll_ival / 1000000;
635 timeout.tv_usec = poll_ival % 1000000;
636 select(nfds, &fdset, NULL, &fdset, &timeout);
638 /* If the user requested we quit, print some statistics. */
639 if (exit_requested) {
640 if (vflag && mjoules_used != 0)
641 printf("total joules used: %u.%03u\n",
642 (u_int)(mjoules_used / 1000),
643 (int)mjoules_used % 1000);
647 /* Read the current AC status and record the mode. */
649 switch (acline_status) {
660 errx(1, "invalid AC line status %d", acline_status);
663 /* Read the current frequency. */
664 if ((curfreq = get_freq()) == 0)
667 i = get_freq_id(curfreq, freqs, numfreqs);
670 /* Keep a sum of all power actually used. */
673 (mwatts[i] * (poll_ival / 1000)) / 1000;
676 /* Always switch to the lowest frequency in min mode. */
677 if (mode == MODE_MIN) {
678 freq = freqs[numfreqs - 1];
679 if (curfreq != freq) {
681 printf("now operating on %s power; "
682 "changing frequency to %d MHz\n",
683 modes[acline_status], freq);
685 if (set_freq(freq) != 0) {
686 warn("error setting CPU freq %d",
694 /* Always switch to the highest frequency in max mode. */
695 if (mode == MODE_MAX) {
697 if (curfreq != freq) {
699 printf("now operating on %s power; "
700 "changing frequency to %d MHz\n",
701 modes[acline_status], freq);
703 if (set_freq(freq) != 0) {
704 warn("error setting CPU freq %d",
712 /* Adaptive mode; get the current CPU usage times. */
713 if (read_usage_times(&load)) {
715 warn("read_usage_times() failed");
719 if (mode == MODE_ADAPTIVE) {
720 if (load > cpu_running_mark) {
721 if (load > 95 || load > cpu_running_mark * 2)
724 freq = freq * load / cpu_running_mark;
727 } else if (load < cpu_idle_mark &&
728 curfreq * load < freqs[get_freq_id(
729 freq * 7 / 8, freqs, numfreqs)] *
732 if (freq < freqs[numfreqs - 1])
733 freq = freqs[numfreqs - 1];
735 } else { /* MODE_HIADAPTIVE */
736 if (load > cpu_running_mark / 2) {
737 if (load > 95 || load > cpu_running_mark)
740 freq = freq * load * 2 / cpu_running_mark;
741 if (freq > freqs[0] * 2)
743 } else if (load < cpu_idle_mark / 2 &&
744 curfreq * load < freqs[get_freq_id(
745 freq * 31 / 32, freqs, numfreqs)] *
746 cpu_running_mark / 2) {
747 freq = freq * 31 / 32;
748 if (freq < freqs[numfreqs - 1])
749 freq = freqs[numfreqs - 1];
753 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
754 load, curfreq, i, freq);
756 j = get_freq_id(freq, freqs, numfreqs);
759 printf("changing clock"
760 " speed from %d MHz to %d MHz\n",
763 if (set_freq(freqs[j]))
764 warn("error setting CPU frequency %d",
768 if (set_freq(initfreq))
769 warn("error setting CPU frequency %d", initfreq);