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.
283 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
284 acline_mode = ac_sysctl;
286 warnx("using sysctl for AC line status");
288 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
289 acline_mode = ac_sysctl;
291 warnx("using sysctl for AC line status");
294 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
296 warnx("using APM for AC line status");
297 acline_mode = ac_apm;
300 warnx("unable to determine AC line status");
301 acline_mode = ac_none;
308 if (acline_mode == ac_acpi_devd) {
309 char buf[DEVCTL_MAXBUF], *ptr;
313 rlen = read(devd_pipe, buf, sizeof(buf));
314 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
316 warnx("lost devd connection, switching to sysctl");
318 acline_mode = ac_sysctl;
322 (ptr = strstr(buf, "system=ACPI")) != NULL &&
323 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
324 (ptr = strstr(ptr, "notify=")) != NULL &&
325 sscanf(ptr, "notify=%x", ¬ify) == 1)
326 acline_status = (notify ? SRC_AC : SRC_BATTERY);
328 if (acline_mode == ac_sysctl) {
332 len = sizeof(acline);
333 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
335 acline_status = (acline ? SRC_AC : SRC_BATTERY);
337 acline_status = SRC_UNKNOWN;
340 if (acline_mode == ac_apm) {
341 struct apm_info info;
343 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
344 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
348 acline_mode = ac_none;
349 acline_status = SRC_UNKNOWN;
353 /* try to (re)connect to devd */
354 if (acline_mode == ac_sysctl) {
357 gettimeofday(&now, NULL);
358 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
359 if (devd_init() >= 0) {
361 warnx("using devd for AC line status");
362 acline_mode = ac_acpi_devd;
372 struct sockaddr_un devd_addr;
374 bzero(&devd_addr, sizeof(devd_addr));
375 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
377 warn("%s(): socket()", __func__);
381 devd_addr.sun_family = PF_LOCAL;
382 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
383 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
384 sizeof(devd_addr)) == -1) {
386 warn("%s(): connect()", __func__);
392 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
394 warn("%s(): fcntl()", __func__);
411 parse_mode(char *arg, int *mode, int ch)
414 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
416 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
418 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
419 *mode = MODE_ADAPTIVE;
420 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
421 *mode = MODE_HIADAPTIVE;
423 errx(1, "bad option: -%c %s", (char)ch, optarg);
427 handle_sigs(int __unused sig)
438 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
443 main(int argc, char * argv[])
445 struct timeval timeout;
448 struct pidfh *pfh = NULL;
449 const char *pidfile = NULL;
450 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
451 int minfreq = -1, maxfreq = -1;
452 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
453 uint64_t mjoules_used;
456 /* Default mode for all AC states is adaptive. */
457 mode_ac = mode_none = MODE_HIADAPTIVE;
458 mode_battery = MODE_ADAPTIVE;
459 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
460 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
461 poll_ival = DEFAULT_POLL_INTERVAL;
465 /* User must be root to control frequencies. */
467 errx(1, "must be root to run");
469 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
472 parse_mode(optarg, &mode_ac, ch);
475 parse_mode(optarg, &mode_battery, ch);
478 cpu_idle_mark = atoi(optarg);
479 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
480 warnx("%d is not a valid percent",
486 minfreq = atoi(optarg);
488 warnx("%d is not a valid CPU frequency",
494 maxfreq = atoi(optarg);
496 warnx("%d is not a valid CPU frequency",
502 parse_mode(optarg, &mode_none, ch);
505 poll_ival = atoi(optarg);
507 warnx("poll interval is in units of ms");
515 cpu_running_mark = atoi(optarg);
516 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
517 warnx("%d is not a valid percent",
531 /* Poll interval is in units of ms. */
534 /* Look up various sysctl MIBs. */
536 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
537 err(1, "lookup kern.cp_times");
539 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
540 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
542 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
543 err(1, "lookup freq_levels");
545 /* Check if we can read the load and supported freqs. */
546 if (read_usage_times(NULL))
547 err(1, "read_usage_times");
548 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
549 err(1, "error reading supported CPU frequencies");
551 errx(1, "no CPU frequencies in user-specified range");
553 /* Run in the background unless in verbose mode. */
557 pfh = pidfile_open(pidfile, 0600, &otherpid);
559 if (errno == EEXIST) {
560 errx(1, "powerd already running, pid: %d",
563 warn("cannot open pid file");
565 if (daemon(0, 0) != 0) {
566 warn("cannot enter daemon mode, exiting");
574 /* Decide whether to use ACPI or APM to read the AC line status. */
578 * Exit cleanly on signals.
580 signal(SIGINT, handle_sigs);
581 signal(SIGTERM, handle_sigs);
583 freq = initfreq = curfreq = get_freq();
584 i = get_freq_id(curfreq, freqs, numfreqs);
589 * If we are in adaptive mode and the current frequency is outside the
590 * user-defined range, adjust it to be within the user-defined range.
593 if (acline_status > SRC_UNKNOWN)
594 errx(1, "invalid AC line status %d", acline_status);
595 if ((acline_status == SRC_AC &&
596 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
597 (acline_status == SRC_BATTERY &&
598 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
599 (acline_status == SRC_UNKNOWN &&
600 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
601 /* Read the current frequency. */
602 len = sizeof(curfreq);
603 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
605 warn("error reading current CPU frequency");
607 if (curfreq < freqs[numfreqs - 1]) {
609 printf("CPU frequency is below user-defined "
610 "minimum; changing frequency to %d "
611 "MHz\n", freqs[numfreqs - 1]);
613 if (set_freq(freqs[numfreqs - 1]) != 0) {
614 warn("error setting CPU freq %d",
615 freqs[numfreqs - 1]);
617 } else if (curfreq > freqs[0]) {
619 printf("CPU frequency is above user-defined "
620 "maximum; changing frequency to %d "
623 if (set_freq(freqs[0]) != 0) {
624 warn("error setting CPU freq %d",
634 if (devd_pipe >= 0) {
635 FD_SET(devd_pipe, &fdset);
636 nfds = devd_pipe + 1;
640 if (mode == MODE_HIADAPTIVE || idle < 120)
646 timeout.tv_sec = to / 1000000;
647 timeout.tv_usec = to % 1000000;
648 select(nfds, &fdset, NULL, &fdset, &timeout);
650 /* If the user requested we quit, print some statistics. */
651 if (exit_requested) {
652 if (vflag && mjoules_used != 0)
653 printf("total joules used: %u.%03u\n",
654 (u_int)(mjoules_used / 1000),
655 (int)mjoules_used % 1000);
659 /* Read the current AC status and record the mode. */
661 switch (acline_status) {
672 errx(1, "invalid AC line status %d", acline_status);
675 /* Read the current frequency. */
676 if (idle % 32 == 0) {
677 if ((curfreq = get_freq()) == 0)
679 i = get_freq_id(curfreq, freqs, numfreqs);
683 /* Keep a sum of all power actually used. */
686 (mwatts[i] * (poll_ival / 1000)) / 1000;
689 /* Always switch to the lowest frequency in min mode. */
690 if (mode == MODE_MIN) {
691 freq = freqs[numfreqs - 1];
692 if (curfreq != freq) {
694 printf("now operating on %s power; "
695 "changing frequency to %d MHz\n",
696 modes[acline_status], freq);
699 if (set_freq(freq) != 0) {
700 warn("error setting CPU freq %d",
708 /* Always switch to the highest frequency in max mode. */
709 if (mode == MODE_MAX) {
711 if (curfreq != freq) {
713 printf("now operating on %s power; "
714 "changing frequency to %d MHz\n",
715 modes[acline_status], freq);
718 if (set_freq(freq) != 0) {
719 warn("error setting CPU freq %d",
727 /* Adaptive mode; get the current CPU usage times. */
728 if (read_usage_times(&load)) {
730 warn("read_usage_times() failed");
734 if (mode == MODE_ADAPTIVE) {
735 if (load > cpu_running_mark) {
736 if (load > 95 || load > cpu_running_mark * 2)
739 freq = freq * load / cpu_running_mark;
742 } else if (load < cpu_idle_mark &&
743 curfreq * load < freqs[get_freq_id(
744 freq * 7 / 8, freqs, numfreqs)] *
747 if (freq < freqs[numfreqs - 1])
748 freq = freqs[numfreqs - 1];
750 } else { /* MODE_HIADAPTIVE */
751 if (load > cpu_running_mark / 2) {
752 if (load > 95 || load > cpu_running_mark)
755 freq = freq * load * 2 / cpu_running_mark;
756 if (freq > freqs[0] * 2)
758 } else if (load < cpu_idle_mark / 2 &&
759 curfreq * load < freqs[get_freq_id(
760 freq * 31 / 32, freqs, numfreqs)] *
761 cpu_running_mark / 2) {
762 freq = freq * 31 / 32;
763 if (freq < freqs[numfreqs - 1])
764 freq = freqs[numfreqs - 1];
768 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
769 load, curfreq, i, freq);
771 j = get_freq_id(freq, freqs, numfreqs);
774 printf("changing clock"
775 " speed from %d MHz to %d MHz\n",
779 if (set_freq(freqs[j]))
780 warn("error setting CPU frequency %d",
784 if (set_freq(initfreq))
785 warn("error setting CPU frequency %d", initfreq);