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 read_usage_times(int *load)
133 static long *cp_times = NULL, *cp_times_old = NULL;
134 static int ncpus = 0;
136 int error, cpu, i, total;
138 if (cp_times == NULL) {
140 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
143 if ((cp_times = malloc(cp_times_len)) == NULL)
145 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
150 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
153 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
154 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
160 for (cpu = 0; cpu < ncpus; cpu++) {
162 for (i = 0; i < CPUSTATES; i++) {
163 total += cp_times[cpu * CPUSTATES + i] -
164 cp_times_old[cpu * CPUSTATES + i];
168 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
169 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
173 memcpy(cp_times_old, cp_times, cp_times_len);
179 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
181 char *freqstr, *p, *q;
185 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
187 if ((freqstr = malloc(len)) == NULL)
189 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
193 for (p = freqstr; *p != '\0'; p++)
197 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
201 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
206 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
210 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
216 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
217 ((*freqs)[j] <= maxfreq || maxfreq == -1))
223 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
240 len = sizeof(curfreq);
241 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
243 warn("error reading current CPU frequency");
253 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
262 get_freq_id(int freq, int *freqs, int numfreqs)
266 while (i < numfreqs) {
275 * Try to use ACPI to find the AC line status. If this fails, fall back
276 * to APM. If nothing succeeds, we'll just run in default mode.
282 acline_status = SRC_UNKNOWN;
284 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
285 acline_mode = ac_sysctl;
287 warnx("using sysctl for AC line status");
289 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
290 acline_mode = ac_sysctl;
292 warnx("using sysctl for AC line status");
295 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
297 warnx("using APM for AC line status");
298 acline_mode = ac_apm;
301 warnx("unable to determine AC line status");
302 acline_mode = ac_none;
309 if (acline_mode == ac_acpi_devd) {
310 char buf[DEVCTL_MAXBUF], *ptr;
314 rlen = read(devd_pipe, buf, sizeof(buf));
315 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
317 warnx("lost devd connection, switching to sysctl");
319 acline_mode = ac_sysctl;
323 (ptr = strstr(buf, "system=ACPI")) != NULL &&
324 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
325 (ptr = strstr(ptr, "notify=")) != NULL &&
326 sscanf(ptr, "notify=%x", ¬ify) == 1)
327 acline_status = (notify ? SRC_AC : SRC_BATTERY);
329 if (acline_mode == ac_sysctl) {
333 len = sizeof(acline);
334 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
336 acline_status = (acline ? SRC_AC : SRC_BATTERY);
338 acline_status = SRC_UNKNOWN;
341 if (acline_mode == ac_apm) {
342 struct apm_info info;
344 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
345 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
349 acline_mode = ac_none;
350 acline_status = SRC_UNKNOWN;
354 /* try to (re)connect to devd */
355 if (acline_mode == ac_sysctl) {
358 gettimeofday(&now, NULL);
359 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
360 if (devd_init() >= 0) {
362 warnx("using devd for AC line status");
363 acline_mode = ac_acpi_devd;
373 struct sockaddr_un devd_addr;
375 bzero(&devd_addr, sizeof(devd_addr));
376 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
378 warn("%s(): socket()", __func__);
382 devd_addr.sun_family = PF_LOCAL;
383 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
384 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
385 sizeof(devd_addr)) == -1) {
387 warn("%s(): connect()", __func__);
393 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
395 warn("%s(): fcntl()", __func__);
412 parse_mode(char *arg, int *mode, int ch)
415 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
417 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
419 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
420 *mode = MODE_ADAPTIVE;
421 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
422 *mode = MODE_HIADAPTIVE;
424 errx(1, "bad option: -%c %s", (char)ch, optarg);
428 handle_sigs(int __unused sig)
439 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
444 main(int argc, char * argv[])
446 struct timeval timeout;
449 struct pidfh *pfh = NULL;
450 const char *pidfile = NULL;
451 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
452 int minfreq = -1, maxfreq = -1;
453 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
454 uint64_t mjoules_used;
457 /* Default mode for all AC states is adaptive. */
458 mode_ac = mode_none = MODE_HIADAPTIVE;
459 mode_battery = MODE_ADAPTIVE;
460 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
461 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
462 poll_ival = DEFAULT_POLL_INTERVAL;
466 /* User must be root to control frequencies. */
468 errx(1, "must be root to run");
470 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
473 parse_mode(optarg, &mode_ac, ch);
476 parse_mode(optarg, &mode_battery, ch);
479 cpu_idle_mark = atoi(optarg);
480 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
481 warnx("%d is not a valid percent",
487 minfreq = atoi(optarg);
489 warnx("%d is not a valid CPU frequency",
495 maxfreq = atoi(optarg);
497 warnx("%d is not a valid CPU frequency",
503 parse_mode(optarg, &mode_none, ch);
506 poll_ival = atoi(optarg);
508 warnx("poll interval is in units of ms");
516 cpu_running_mark = atoi(optarg);
517 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
518 warnx("%d is not a valid percent",
532 /* Poll interval is in units of ms. */
535 /* Look up various sysctl MIBs. */
537 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
538 err(1, "lookup kern.cp_times");
540 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
541 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
543 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
544 err(1, "lookup freq_levels");
546 /* Check if we can read the load and supported freqs. */
547 if (read_usage_times(NULL))
548 err(1, "read_usage_times");
549 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
550 err(1, "error reading supported CPU frequencies");
552 errx(1, "no CPU frequencies in user-specified range");
554 /* Run in the background unless in verbose mode. */
558 pfh = pidfile_open(pidfile, 0600, &otherpid);
560 if (errno == EEXIST) {
561 errx(1, "powerd already running, pid: %d",
564 warn("cannot open pid file");
566 if (daemon(0, 0) != 0) {
567 warn("cannot enter daemon mode, exiting");
575 /* Decide whether to use ACPI or APM to read the AC line status. */
579 * Exit cleanly on signals.
581 signal(SIGINT, handle_sigs);
582 signal(SIGTERM, handle_sigs);
584 freq = initfreq = curfreq = get_freq();
585 i = get_freq_id(curfreq, freqs, numfreqs);
590 * If we are in adaptive mode and the current frequency is outside the
591 * user-defined range, adjust it to be within the user-defined range.
594 if (acline_status > SRC_UNKNOWN)
595 errx(1, "invalid AC line status %d", acline_status);
596 if ((acline_status == SRC_AC &&
597 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
598 (acline_status == SRC_BATTERY &&
599 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
600 (acline_status == SRC_UNKNOWN &&
601 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
602 /* Read the current frequency. */
603 len = sizeof(curfreq);
604 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
606 warn("error reading current CPU frequency");
608 if (curfreq < freqs[numfreqs - 1]) {
610 printf("CPU frequency is below user-defined "
611 "minimum; changing frequency to %d "
612 "MHz\n", freqs[numfreqs - 1]);
614 if (set_freq(freqs[numfreqs - 1]) != 0) {
615 warn("error setting CPU freq %d",
616 freqs[numfreqs - 1]);
618 } else if (curfreq > freqs[0]) {
620 printf("CPU frequency is above user-defined "
621 "maximum; changing frequency to %d "
624 if (set_freq(freqs[0]) != 0) {
625 warn("error setting CPU freq %d",
635 if (devd_pipe >= 0) {
636 FD_SET(devd_pipe, &fdset);
637 nfds = devd_pipe + 1;
641 if (mode == MODE_HIADAPTIVE || idle < 120)
647 timeout.tv_sec = to / 1000000;
648 timeout.tv_usec = to % 1000000;
649 select(nfds, &fdset, NULL, &fdset, &timeout);
651 /* If the user requested we quit, print some statistics. */
652 if (exit_requested) {
653 if (vflag && mjoules_used != 0)
654 printf("total joules used: %u.%03u\n",
655 (u_int)(mjoules_used / 1000),
656 (int)mjoules_used % 1000);
660 /* Read the current AC status and record the mode. */
662 switch (acline_status) {
673 errx(1, "invalid AC line status %d", acline_status);
676 /* Read the current frequency. */
677 if (idle % 32 == 0) {
678 if ((curfreq = get_freq()) == 0)
680 i = get_freq_id(curfreq, freqs, numfreqs);
684 /* Keep a sum of all power actually used. */
687 (mwatts[i] * (poll_ival / 1000)) / 1000;
690 /* Always switch to the lowest frequency in min mode. */
691 if (mode == MODE_MIN) {
692 freq = freqs[numfreqs - 1];
693 if (curfreq != freq) {
695 printf("now operating on %s power; "
696 "changing frequency to %d MHz\n",
697 modes[acline_status], freq);
700 if (set_freq(freq) != 0) {
701 warn("error setting CPU freq %d",
709 /* Always switch to the highest frequency in max mode. */
710 if (mode == MODE_MAX) {
712 if (curfreq != freq) {
714 printf("now operating on %s power; "
715 "changing frequency to %d MHz\n",
716 modes[acline_status], freq);
719 if (set_freq(freq) != 0) {
720 warn("error setting CPU freq %d",
728 /* Adaptive mode; get the current CPU usage times. */
729 if (read_usage_times(&load)) {
731 warn("read_usage_times() failed");
735 if (mode == MODE_ADAPTIVE) {
736 if (load > cpu_running_mark) {
737 if (load > 95 || load > cpu_running_mark * 2)
740 freq = freq * load / cpu_running_mark;
743 } else if (load < cpu_idle_mark &&
744 curfreq * load < freqs[get_freq_id(
745 freq * 7 / 8, freqs, numfreqs)] *
748 if (freq < freqs[numfreqs - 1])
749 freq = freqs[numfreqs - 1];
751 } else { /* MODE_HIADAPTIVE */
752 if (load > cpu_running_mark / 2) {
753 if (load > 95 || load > cpu_running_mark)
756 freq = freq * load * 2 / cpu_running_mark;
757 if (freq > freqs[0] * 2)
759 } else if (load < cpu_idle_mark / 2 &&
760 curfreq * load < freqs[get_freq_id(
761 freq * 31 / 32, freqs, numfreqs)] *
762 cpu_running_mark / 2) {
763 freq = freq * 31 / 32;
764 if (freq < freqs[numfreqs - 1])
765 freq = freqs[numfreqs - 1];
769 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
770 load, curfreq, i, freq);
772 j = get_freq_id(freq, freqs, numfreqs);
775 printf("changing clock"
776 " speed from %d MHz to %d MHz\n",
780 if (set_freq(freqs[j]))
781 warn("error setting CPU frequency %d",
785 if (set_freq(initfreq))
786 warn("error setting CPU frequency %d", initfreq);