2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2004 Colin Percival
5 * Copyright (c) 2005 Nate Lawson
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted providing that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
26 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 * POSSIBILITY OF SUCH DAMAGE.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include <sys/param.h>
34 #include <sys/ioctl.h>
35 #include <sys/sysctl.h>
36 #include <sys/resource.h>
37 #include <sys/socket.h>
57 #include <machine/apm_bios.h>
60 #define DEFAULT_ACTIVE_PERCENT 75
61 #define DEFAULT_IDLE_PERCENT 50
62 #define DEFAULT_POLL_INTERVAL 250 /* Poll interval in milliseconds */
77 static const char *modes[] = {
83 #define ACPIAC "hw.acpi.acline"
84 #define PMUAC "dev.pmu.0.acline"
85 #define APMDEV "/dev/apm"
86 #define DEVDPIPE "/var/run/devd.pipe"
87 #define DEVCTL_MAXBUF 1024
89 static int read_usage_times(int *load);
90 static int read_freqs(int *numfreqs, int **freqs, int **power,
91 int minfreq, int maxfreq);
92 static int set_freq(int freq);
93 static void acline_init(void);
94 static void acline_read(void);
95 static int devd_init(void);
96 static void devd_close(void);
97 static void handle_sigs(int sig);
98 static void parse_mode(char *arg, int *mode, int ch);
99 static void usage(void);
101 /* Sysctl data structures. */
102 static int cp_times_mib[2];
103 static int freq_mib[4];
104 static int levels_mib[4];
105 static int acline_mib[4];
106 static size_t acline_mib_len;
109 static int cpu_running_mark;
110 static int cpu_idle_mark;
111 static int poll_ival;
114 static volatile sig_atomic_t exit_requested;
115 static power_src_t acline_status;
124 static acline_mode_t acline_mode;
125 static acline_mode_t acline_mode_user = ac_none;
127 static int apm_fd = -1;
129 static int devd_pipe = -1;
131 #define DEVD_RETRY_INTERVAL 60 /* seconds */
132 static struct timeval tried_devd;
135 * This function returns summary load of all CPUs. It was made so
136 * intentionally to not reduce performance in scenarios when several
137 * threads are processing requests as a pipeline -- running one at
138 * a time on different CPUs and waiting for each other.
141 read_usage_times(int *load)
143 static long *cp_times = NULL, *cp_times_old = NULL;
144 static int ncpus = 0;
146 int error, cpu, i, total;
148 if (cp_times == NULL) {
150 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
153 if ((cp_times = malloc(cp_times_len)) == NULL)
155 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
160 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
163 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
164 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
170 for (cpu = 0; cpu < ncpus; cpu++) {
172 for (i = 0; i < CPUSTATES; i++) {
173 total += cp_times[cpu * CPUSTATES + i] -
174 cp_times_old[cpu * CPUSTATES + i];
178 *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
179 cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
183 memcpy(cp_times_old, cp_times, cp_times_len);
189 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
191 char *freqstr, *p, *q;
195 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
197 if ((freqstr = malloc(len)) == NULL)
199 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0)) {
205 for (p = freqstr; *p != '\0'; p++)
209 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
213 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
218 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
222 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
228 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
229 ((*freqs)[j] <= maxfreq || maxfreq == -1))
235 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
252 len = sizeof(curfreq);
253 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
255 warn("error reading current CPU frequency");
265 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
274 get_freq_id(int freq, int *freqs, int numfreqs)
278 while (i < numfreqs) {
287 * Try to use ACPI to find the AC line status. If this fails, fall back
288 * to APM. If nothing succeeds, we'll just run in default mode.
293 int skip_source_check;
296 acline_status = SRC_UNKNOWN;
297 skip_source_check = (acline_mode_user == ac_none ||
298 acline_mode_user == ac_acpi_devd);
300 if ((skip_source_check || acline_mode_user == ac_sysctl) &&
301 sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
302 acline_mode = ac_sysctl;
304 warnx("using sysctl for AC line status");
306 } else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
307 sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
308 acline_mode = ac_sysctl;
310 warnx("using sysctl for AC line status");
313 } else if ((skip_source_check || acline_mode_user == ac_apm) &&
314 (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
316 warnx("using APM for AC line status");
317 acline_mode = ac_apm;
320 warnx("unable to determine AC line status");
321 acline_mode = ac_none;
328 if (acline_mode == ac_acpi_devd) {
329 char buf[DEVCTL_MAXBUF], *ptr;
333 rlen = read(devd_pipe, buf, sizeof(buf));
334 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
336 warnx("lost devd connection, switching to sysctl");
338 acline_mode = ac_sysctl;
342 (ptr = strstr(buf, "system=ACPI")) != NULL &&
343 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
344 (ptr = strstr(ptr, "notify=")) != NULL &&
345 sscanf(ptr, "notify=%x", ¬ify) == 1)
346 acline_status = (notify ? SRC_AC : SRC_BATTERY);
348 if (acline_mode == ac_sysctl) {
352 len = sizeof(acline);
353 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
355 acline_status = (acline ? SRC_AC : SRC_BATTERY);
357 acline_status = SRC_UNKNOWN;
360 if (acline_mode == ac_apm) {
361 struct apm_info info;
363 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
364 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
368 acline_mode = ac_none;
369 acline_status = SRC_UNKNOWN;
373 /* try to (re)connect to devd */
375 if ((acline_mode == ac_sysctl &&
376 (acline_mode_user == ac_none ||
377 acline_mode_user == ac_acpi_devd)) ||
378 (acline_mode == ac_apm &&
379 acline_mode_user == ac_acpi_devd)) {
381 if (acline_mode == ac_sysctl &&
382 (acline_mode_user == ac_none ||
383 acline_mode_user == ac_acpi_devd)) {
387 gettimeofday(&now, NULL);
388 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
389 if (devd_init() >= 0) {
391 warnx("using devd for AC line status");
392 acline_mode = ac_acpi_devd;
402 struct sockaddr_un devd_addr;
404 bzero(&devd_addr, sizeof(devd_addr));
405 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
407 warn("%s(): socket()", __func__);
411 devd_addr.sun_family = PF_LOCAL;
412 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
413 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
414 sizeof(devd_addr)) == -1) {
416 warn("%s(): connect()", __func__);
434 parse_mode(char *arg, int *mode, int ch)
437 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
439 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
441 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
442 *mode = MODE_ADAPTIVE;
443 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
444 *mode = MODE_HIADAPTIVE;
446 errx(1, "bad option: -%c %s", (char)ch, optarg);
450 parse_acline_mode(char *arg, int ch)
452 if (strcmp(arg, "sysctl") == 0)
453 acline_mode_user = ac_sysctl;
454 else if (strcmp(arg, "devd") == 0)
455 acline_mode_user = ac_acpi_devd;
457 else if (strcmp(arg, "apm") == 0)
458 acline_mode_user = ac_apm;
461 errx(1, "bad option: -%c %s", (char)ch, optarg);
465 handle_sigs(int __unused sig)
476 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
481 main(int argc, char * argv[])
483 struct timeval timeout;
486 struct pidfh *pfh = NULL;
487 const char *pidfile = NULL;
488 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
489 int minfreq = -1, maxfreq = -1;
490 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
491 uint64_t mjoules_used;
494 /* Default mode for all AC states is adaptive. */
495 mode_ac = mode_none = MODE_HIADAPTIVE;
496 mode_battery = MODE_ADAPTIVE;
497 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
498 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
499 poll_ival = DEFAULT_POLL_INTERVAL;
503 /* User must be root to control frequencies. */
505 errx(1, "must be root to run");
507 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:s:v")) != -1)
510 parse_mode(optarg, &mode_ac, ch);
513 parse_mode(optarg, &mode_battery, ch);
516 parse_acline_mode(optarg, ch);
519 cpu_idle_mark = atoi(optarg);
520 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
521 warnx("%d is not a valid percent",
527 minfreq = atoi(optarg);
529 warnx("%d is not a valid CPU frequency",
535 maxfreq = atoi(optarg);
537 warnx("%d is not a valid CPU frequency",
543 parse_mode(optarg, &mode_none, ch);
546 poll_ival = atoi(optarg);
548 warnx("poll interval is in units of ms");
556 cpu_running_mark = atoi(optarg);
557 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
558 warnx("%d is not a valid percent",
572 /* Poll interval is in units of ms. */
575 /* Look up various sysctl MIBs. */
577 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
578 err(1, "lookup kern.cp_times");
580 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
581 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
583 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
584 err(1, "lookup freq_levels");
586 /* Check if we can read the load and supported freqs. */
587 if (read_usage_times(NULL))
588 err(1, "read_usage_times");
589 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
590 err(1, "error reading supported CPU frequencies");
592 errx(1, "no CPU frequencies in user-specified range");
594 /* Run in the background unless in verbose mode. */
598 pfh = pidfile_open(pidfile, 0600, &otherpid);
600 if (errno == EEXIST) {
601 errx(1, "powerd already running, pid: %d",
604 warn("cannot open pid file");
606 if (daemon(0, 0) != 0) {
607 warn("cannot enter daemon mode, exiting");
615 /* Decide whether to use ACPI or APM to read the AC line status. */
619 * Exit cleanly on signals.
621 signal(SIGINT, handle_sigs);
622 signal(SIGTERM, handle_sigs);
624 freq = initfreq = curfreq = get_freq();
625 i = get_freq_id(curfreq, freqs, numfreqs);
630 * If we are in adaptive mode and the current frequency is outside the
631 * user-defined range, adjust it to be within the user-defined range.
634 if (acline_status > SRC_UNKNOWN)
635 errx(1, "invalid AC line status %d", acline_status);
636 if ((acline_status == SRC_AC &&
637 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
638 (acline_status == SRC_BATTERY &&
639 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
640 (acline_status == SRC_UNKNOWN &&
641 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
642 /* Read the current frequency. */
643 len = sizeof(curfreq);
644 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
646 warn("error reading current CPU frequency");
648 if (curfreq < freqs[numfreqs - 1]) {
650 printf("CPU frequency is below user-defined "
651 "minimum; changing frequency to %d "
652 "MHz\n", freqs[numfreqs - 1]);
654 if (set_freq(freqs[numfreqs - 1]) != 0) {
655 warn("error setting CPU freq %d",
656 freqs[numfreqs - 1]);
658 } else if (curfreq > freqs[0]) {
660 printf("CPU frequency is above user-defined "
661 "maximum; changing frequency to %d "
664 if (set_freq(freqs[0]) != 0) {
665 warn("error setting CPU freq %d",
675 if (devd_pipe >= 0) {
676 FD_SET(devd_pipe, &fdset);
677 nfds = devd_pipe + 1;
681 if (mode == MODE_HIADAPTIVE || idle < 120)
687 timeout.tv_sec = to / 1000000;
688 timeout.tv_usec = to % 1000000;
689 select(nfds, &fdset, NULL, &fdset, &timeout);
691 /* If the user requested we quit, print some statistics. */
692 if (exit_requested) {
693 if (vflag && mjoules_used != 0)
694 printf("total joules used: %u.%03u\n",
695 (u_int)(mjoules_used / 1000),
696 (int)mjoules_used % 1000);
700 /* Read the current AC status and record the mode. */
702 switch (acline_status) {
713 errx(1, "invalid AC line status %d", acline_status);
716 /* Read the current frequency. */
717 if (idle % 32 == 0) {
718 if ((curfreq = get_freq()) == 0)
720 i = get_freq_id(curfreq, freqs, numfreqs);
724 /* Keep a sum of all power actually used. */
727 (mwatts[i] * (poll_ival / 1000)) / 1000;
730 /* Always switch to the lowest frequency in min mode. */
731 if (mode == MODE_MIN) {
732 freq = freqs[numfreqs - 1];
733 if (curfreq != freq) {
735 printf("now operating on %s power; "
736 "changing frequency to %d MHz\n",
737 modes[acline_status], freq);
740 if (set_freq(freq) != 0) {
741 warn("error setting CPU freq %d",
749 /* Always switch to the highest frequency in max mode. */
750 if (mode == MODE_MAX) {
752 if (curfreq != freq) {
754 printf("now operating on %s power; "
755 "changing frequency to %d MHz\n",
756 modes[acline_status], freq);
759 if (set_freq(freq) != 0) {
760 warn("error setting CPU freq %d",
768 /* Adaptive mode; get the current CPU usage times. */
769 if (read_usage_times(&load)) {
771 warn("read_usage_times() failed");
775 if (mode == MODE_ADAPTIVE) {
776 if (load > cpu_running_mark) {
777 if (load > 95 || load > cpu_running_mark * 2)
780 freq = freq * load / cpu_running_mark;
783 } else if (load < cpu_idle_mark &&
784 curfreq * load < freqs[get_freq_id(
785 freq * 7 / 8, freqs, numfreqs)] *
788 if (freq < freqs[numfreqs - 1])
789 freq = freqs[numfreqs - 1];
791 } else { /* MODE_HIADAPTIVE */
792 if (load > cpu_running_mark / 2) {
793 if (load > 95 || load > cpu_running_mark)
796 freq = freq * load * 2 / cpu_running_mark;
797 if (freq > freqs[0] * 2)
799 } else if (load < cpu_idle_mark / 2 &&
800 curfreq * load < freqs[get_freq_id(
801 freq * 31 / 32, freqs, numfreqs)] *
802 cpu_running_mark / 2) {
803 freq = freq * 31 / 32;
804 if (freq < freqs[numfreqs - 1])
805 freq = freqs[numfreqs - 1];
809 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
810 load, curfreq, i, freq);
812 j = get_freq_id(freq, freqs, numfreqs);
815 printf("changing clock"
816 " speed from %d MHz to %d MHz\n",
820 if (set_freq(freqs[j]))
821 warn("error setting CPU frequency %d",
825 if (set_freq(initfreq))
826 warn("error setting CPU frequency %d", initfreq);