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;
122 static acline_mode_t acline_mode;
123 static acline_mode_t acline_mode_user = ac_none;
125 static int apm_fd = -1;
127 static int devd_pipe = -1;
129 #define DEVD_RETRY_INTERVAL 60 /* seconds */
130 static struct timeval tried_devd;
133 * This function returns summary load of all CPUs. It was made so
134 * intentionally to not reduce performance in scenarios when several
135 * threads are processing requests as a pipeline -- running one at
136 * a time on different CPUs and waiting for each other.
139 read_usage_times(int *load)
141 static long *cp_times = NULL, *cp_times_old = NULL;
142 static int ncpus = 0;
144 int error, cpu, i, total;
146 if (cp_times == NULL) {
148 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
151 if ((cp_times = malloc(cp_times_len)) == NULL)
153 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
158 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
161 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
162 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
168 for (cpu = 0; cpu < ncpus; cpu++) {
170 for (i = 0; i < CPUSTATES; i++) {
171 total += cp_times[cpu * CPUSTATES + i] -
172 cp_times_old[cpu * CPUSTATES + i];
176 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
177 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
181 memcpy(cp_times_old, cp_times, cp_times_len);
187 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
189 char *freqstr, *p, *q;
193 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
195 if ((freqstr = malloc(len)) == NULL)
197 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
201 for (p = freqstr; *p != '\0'; p++)
205 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
209 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
214 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
218 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
224 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
225 ((*freqs)[j] <= maxfreq || maxfreq == -1))
231 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
248 len = sizeof(curfreq);
249 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
251 warn("error reading current CPU frequency");
261 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
270 get_freq_id(int freq, int *freqs, int numfreqs)
274 while (i < numfreqs) {
283 * Try to use ACPI to find the AC line status. If this fails, fall back
284 * to APM. If nothing succeeds, we'll just run in default mode.
289 int skip_source_check;
292 acline_status = SRC_UNKNOWN;
293 skip_source_check = (acline_mode_user == ac_none ||
294 acline_mode_user == ac_acpi_devd);
296 if ((skip_source_check || acline_mode_user == ac_sysctl) &&
297 sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
298 acline_mode = ac_sysctl;
300 warnx("using sysctl for AC line status");
302 } else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
303 sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
304 acline_mode = ac_sysctl;
306 warnx("using sysctl for AC line status");
309 } else if ((skip_source_check || acline_mode_user == ac_apm) &&
310 (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
312 warnx("using APM for AC line status");
313 acline_mode = ac_apm;
316 warnx("unable to determine AC line status");
317 acline_mode = ac_none;
324 if (acline_mode == ac_acpi_devd) {
325 char buf[DEVCTL_MAXBUF], *ptr;
329 rlen = read(devd_pipe, buf, sizeof(buf));
330 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
332 warnx("lost devd connection, switching to sysctl");
334 acline_mode = ac_sysctl;
338 (ptr = strstr(buf, "system=ACPI")) != NULL &&
339 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
340 (ptr = strstr(ptr, "notify=")) != NULL &&
341 sscanf(ptr, "notify=%x", ¬ify) == 1)
342 acline_status = (notify ? SRC_AC : SRC_BATTERY);
344 if (acline_mode == ac_sysctl) {
348 len = sizeof(acline);
349 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
351 acline_status = (acline ? SRC_AC : SRC_BATTERY);
353 acline_status = SRC_UNKNOWN;
356 if (acline_mode == ac_apm) {
357 struct apm_info info;
359 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
360 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
364 acline_mode = ac_none;
365 acline_status = SRC_UNKNOWN;
369 /* try to (re)connect to devd */
371 if ((acline_mode == ac_sysctl &&
372 (acline_mode_user == ac_none ||
373 acline_mode_user == ac_acpi_devd)) ||
374 (acline_mode == ac_apm &&
375 acline_mode_user == ac_acpi_devd)) {
377 if (acline_mode == ac_sysctl &&
378 (acline_mode_user == ac_none ||
379 acline_mode_user == ac_acpi_devd)) {
383 gettimeofday(&now, NULL);
384 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
385 if (devd_init() >= 0) {
387 warnx("using devd for AC line status");
388 acline_mode = ac_acpi_devd;
398 struct sockaddr_un devd_addr;
400 bzero(&devd_addr, sizeof(devd_addr));
401 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
403 warn("%s(): socket()", __func__);
407 devd_addr.sun_family = PF_LOCAL;
408 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
409 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
410 sizeof(devd_addr)) == -1) {
412 warn("%s(): connect()", __func__);
418 if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
420 warn("%s(): fcntl()", __func__);
437 parse_mode(char *arg, int *mode, int ch)
440 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
442 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
444 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
445 *mode = MODE_ADAPTIVE;
446 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
447 *mode = MODE_HIADAPTIVE;
449 errx(1, "bad option: -%c %s", (char)ch, optarg);
453 parse_acline_mode(char *arg, int ch)
455 if (strcmp(arg, "sysctl") == 0)
456 acline_mode_user = ac_sysctl;
457 else if (strcmp(arg, "devd") == 0)
458 acline_mode_user = ac_acpi_devd;
460 else if (strcmp(arg, "apm") == 0)
461 acline_mode_user = ac_apm;
464 errx(1, "bad option: -%c %s", (char)ch, optarg);
468 handle_sigs(int __unused sig)
479 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
484 main(int argc, char * argv[])
486 struct timeval timeout;
489 struct pidfh *pfh = NULL;
490 const char *pidfile = NULL;
491 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
492 int minfreq = -1, maxfreq = -1;
493 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
494 uint64_t mjoules_used;
497 /* Default mode for all AC states is adaptive. */
498 mode_ac = mode_none = MODE_HIADAPTIVE;
499 mode_battery = MODE_ADAPTIVE;
500 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
501 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
502 poll_ival = DEFAULT_POLL_INTERVAL;
506 /* User must be root to control frequencies. */
508 errx(1, "must be root to run");
510 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:s:v")) != -1)
513 parse_mode(optarg, &mode_ac, ch);
516 parse_mode(optarg, &mode_battery, ch);
519 parse_acline_mode(optarg, ch);
522 cpu_idle_mark = atoi(optarg);
523 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
524 warnx("%d is not a valid percent",
530 minfreq = atoi(optarg);
532 warnx("%d is not a valid CPU frequency",
538 maxfreq = atoi(optarg);
540 warnx("%d is not a valid CPU frequency",
546 parse_mode(optarg, &mode_none, ch);
549 poll_ival = atoi(optarg);
551 warnx("poll interval is in units of ms");
559 cpu_running_mark = atoi(optarg);
560 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
561 warnx("%d is not a valid percent",
575 /* Poll interval is in units of ms. */
578 /* Look up various sysctl MIBs. */
580 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
581 err(1, "lookup kern.cp_times");
583 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
584 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
586 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
587 err(1, "lookup freq_levels");
589 /* Check if we can read the load and supported freqs. */
590 if (read_usage_times(NULL))
591 err(1, "read_usage_times");
592 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
593 err(1, "error reading supported CPU frequencies");
595 errx(1, "no CPU frequencies in user-specified range");
597 /* Run in the background unless in verbose mode. */
601 pfh = pidfile_open(pidfile, 0600, &otherpid);
603 if (errno == EEXIST) {
604 errx(1, "powerd already running, pid: %d",
607 warn("cannot open pid file");
609 if (daemon(0, 0) != 0) {
610 warn("cannot enter daemon mode, exiting");
618 /* Decide whether to use ACPI or APM to read the AC line status. */
622 * Exit cleanly on signals.
624 signal(SIGINT, handle_sigs);
625 signal(SIGTERM, handle_sigs);
627 freq = initfreq = curfreq = get_freq();
628 i = get_freq_id(curfreq, freqs, numfreqs);
633 * If we are in adaptive mode and the current frequency is outside the
634 * user-defined range, adjust it to be within the user-defined range.
637 if (acline_status > SRC_UNKNOWN)
638 errx(1, "invalid AC line status %d", acline_status);
639 if ((acline_status == SRC_AC &&
640 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
641 (acline_status == SRC_BATTERY &&
642 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
643 (acline_status == SRC_UNKNOWN &&
644 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
645 /* Read the current frequency. */
646 len = sizeof(curfreq);
647 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
649 warn("error reading current CPU frequency");
651 if (curfreq < freqs[numfreqs - 1]) {
653 printf("CPU frequency is below user-defined "
654 "minimum; changing frequency to %d "
655 "MHz\n", freqs[numfreqs - 1]);
657 if (set_freq(freqs[numfreqs - 1]) != 0) {
658 warn("error setting CPU freq %d",
659 freqs[numfreqs - 1]);
661 } else if (curfreq > freqs[0]) {
663 printf("CPU frequency is above user-defined "
664 "maximum; changing frequency to %d "
667 if (set_freq(freqs[0]) != 0) {
668 warn("error setting CPU freq %d",
678 if (devd_pipe >= 0) {
679 FD_SET(devd_pipe, &fdset);
680 nfds = devd_pipe + 1;
684 if (mode == MODE_HIADAPTIVE || idle < 120)
690 timeout.tv_sec = to / 1000000;
691 timeout.tv_usec = to % 1000000;
692 select(nfds, &fdset, NULL, &fdset, &timeout);
694 /* If the user requested we quit, print some statistics. */
695 if (exit_requested) {
696 if (vflag && mjoules_used != 0)
697 printf("total joules used: %u.%03u\n",
698 (u_int)(mjoules_used / 1000),
699 (int)mjoules_used % 1000);
703 /* Read the current AC status and record the mode. */
705 switch (acline_status) {
716 errx(1, "invalid AC line status %d", acline_status);
719 /* Read the current frequency. */
720 if (idle % 32 == 0) {
721 if ((curfreq = get_freq()) == 0)
723 i = get_freq_id(curfreq, freqs, numfreqs);
727 /* Keep a sum of all power actually used. */
730 (mwatts[i] * (poll_ival / 1000)) / 1000;
733 /* Always switch to the lowest frequency in min mode. */
734 if (mode == MODE_MIN) {
735 freq = freqs[numfreqs - 1];
736 if (curfreq != freq) {
738 printf("now operating on %s power; "
739 "changing frequency to %d MHz\n",
740 modes[acline_status], freq);
743 if (set_freq(freq) != 0) {
744 warn("error setting CPU freq %d",
752 /* Always switch to the highest frequency in max mode. */
753 if (mode == MODE_MAX) {
755 if (curfreq != freq) {
757 printf("now operating on %s power; "
758 "changing frequency to %d MHz\n",
759 modes[acline_status], freq);
762 if (set_freq(freq) != 0) {
763 warn("error setting CPU freq %d",
771 /* Adaptive mode; get the current CPU usage times. */
772 if (read_usage_times(&load)) {
774 warn("read_usage_times() failed");
778 if (mode == MODE_ADAPTIVE) {
779 if (load > cpu_running_mark) {
780 if (load > 95 || load > cpu_running_mark * 2)
783 freq = freq * load / cpu_running_mark;
786 } else if (load < cpu_idle_mark &&
787 curfreq * load < freqs[get_freq_id(
788 freq * 7 / 8, freqs, numfreqs)] *
791 if (freq < freqs[numfreqs - 1])
792 freq = freqs[numfreqs - 1];
794 } else { /* MODE_HIADAPTIVE */
795 if (load > cpu_running_mark / 2) {
796 if (load > 95 || load > cpu_running_mark)
799 freq = freq * load * 2 / cpu_running_mark;
800 if (freq > freqs[0] * 2)
802 } else if (load < cpu_idle_mark / 2 &&
803 curfreq * load < freqs[get_freq_id(
804 freq * 31 / 32, freqs, numfreqs)] *
805 cpu_running_mark / 2) {
806 freq = freq * 31 / 32;
807 if (freq < freqs[numfreqs - 1])
808 freq = freqs[numfreqs - 1];
812 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
813 load, curfreq, i, freq);
815 j = get_freq_id(freq, freqs, numfreqs);
818 printf("changing clock"
819 " speed from %d MHz to %d MHz\n",
823 if (set_freq(freqs[j]))
824 warn("error setting CPU frequency %d",
828 if (set_freq(initfreq))
829 warn("error setting CPU frequency %d", initfreq);