2 * SPDX-License-Identifier: BSD-2-Clause
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 #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, int nonice);
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. If nonice
137 * is nonzero, only user+sys+intr time will be counted as load; any
138 * nice time will be treated as if idle.
141 read_usage_times(int *load, int nonice)
143 static long *cp_times = NULL, *cp_times_old = NULL;
144 static int ncpus = 0;
146 int error, cpu, i, total, excl;
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 excl = cp_times[cpu * CPUSTATES + CP_IDLE] -
179 cp_times_old[cpu * CPUSTATES + CP_IDLE];
181 excl += cp_times[cpu * CPUSTATES + CP_NICE] -
182 cp_times_old[cpu * CPUSTATES + CP_NICE];
183 *load += 100 - excl * 100 / total;
187 memcpy(cp_times_old, cp_times, cp_times_len);
193 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
195 char *freqstr, *p, *q;
199 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
201 if ((freqstr = malloc(len)) == NULL)
203 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0)) {
209 for (p = freqstr; *p != '\0'; p++)
213 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
217 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
222 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
226 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
232 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
233 ((*freqs)[j] <= maxfreq || maxfreq == -1))
239 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
256 len = sizeof(curfreq);
257 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
259 warn("error reading current CPU frequency");
269 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
278 get_freq_id(int freq, int *freqs, int numfreqs)
282 while (i < numfreqs) {
291 * Try to use ACPI to find the AC line status. If this fails, fall back
292 * to APM. If nothing succeeds, we'll just run in default mode.
297 int skip_source_check;
300 acline_status = SRC_UNKNOWN;
301 skip_source_check = (acline_mode_user == ac_none ||
302 acline_mode_user == ac_acpi_devd);
304 if ((skip_source_check || acline_mode_user == ac_sysctl) &&
305 sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
306 acline_mode = ac_sysctl;
308 warnx("using sysctl for AC line status");
310 } else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
311 sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
312 acline_mode = ac_sysctl;
314 warnx("using sysctl for AC line status");
317 } else if ((skip_source_check || acline_mode_user == ac_apm) &&
318 (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
320 warnx("using APM for AC line status");
321 acline_mode = ac_apm;
324 warnx("unable to determine AC line status");
325 acline_mode = ac_none;
332 if (acline_mode == ac_acpi_devd) {
333 char buf[DEVCTL_MAXBUF], *ptr;
337 rlen = read(devd_pipe, buf, sizeof(buf));
338 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
340 warnx("lost devd connection, switching to sysctl");
342 acline_mode = ac_sysctl;
346 (ptr = strstr(buf, "system=ACPI")) != NULL &&
347 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
348 (ptr = strstr(ptr, "notify=")) != NULL &&
349 sscanf(ptr, "notify=%x", ¬ify) == 1)
350 acline_status = (notify ? SRC_AC : SRC_BATTERY);
352 if (acline_mode == ac_sysctl) {
356 len = sizeof(acline);
357 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
359 acline_status = (acline ? SRC_AC : SRC_BATTERY);
361 acline_status = SRC_UNKNOWN;
364 if (acline_mode == ac_apm) {
365 struct apm_info info;
367 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
368 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
372 acline_mode = ac_none;
373 acline_status = SRC_UNKNOWN;
377 /* try to (re)connect to devd */
379 if ((acline_mode == ac_sysctl &&
380 (acline_mode_user == ac_none ||
381 acline_mode_user == ac_acpi_devd)) ||
382 (acline_mode == ac_apm &&
383 acline_mode_user == ac_acpi_devd)) {
385 if (acline_mode == ac_sysctl &&
386 (acline_mode_user == ac_none ||
387 acline_mode_user == ac_acpi_devd)) {
391 gettimeofday(&now, NULL);
392 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
393 if (devd_init() >= 0) {
395 warnx("using devd for AC line status");
396 acline_mode = ac_acpi_devd;
406 struct sockaddr_un devd_addr;
408 bzero(&devd_addr, sizeof(devd_addr));
409 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
411 warn("%s(): socket()", __func__);
415 devd_addr.sun_family = PF_LOCAL;
416 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
417 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
418 sizeof(devd_addr)) == -1) {
420 warn("%s(): connect()", __func__);
438 parse_mode(char *arg, int *mode, int ch)
441 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
443 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
445 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
446 *mode = MODE_ADAPTIVE;
447 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
448 *mode = MODE_HIADAPTIVE;
450 errx(1, "bad option: -%c %s", (char)ch, optarg);
454 parse_acline_mode(char *arg, int ch)
456 if (strcmp(arg, "sysctl") == 0)
457 acline_mode_user = ac_sysctl;
458 else if (strcmp(arg, "devd") == 0)
459 acline_mode_user = ac_acpi_devd;
461 else if (strcmp(arg, "apm") == 0)
462 acline_mode_user = ac_apm;
465 errx(1, "bad option: -%c %s", (char)ch, optarg);
469 handle_sigs(int __unused sig)
480 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-N] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
485 main(int argc, char * argv[])
487 struct timeval timeout;
490 struct pidfh *pfh = NULL;
491 const char *pidfile = NULL;
492 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
493 int minfreq = -1, maxfreq = -1;
494 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
495 uint64_t mjoules_used;
499 /* Default mode for all AC states is adaptive. */
500 mode_ac = mode_none = MODE_HIADAPTIVE;
501 mode_battery = MODE_ADAPTIVE;
502 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
503 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
504 poll_ival = DEFAULT_POLL_INTERVAL;
509 /* User must be root to control frequencies. */
511 errx(1, "must be root to run");
513 while ((ch = getopt(argc, argv, "a:b:i:m:M:Nn:p:P:r:s:v")) != -1)
516 parse_mode(optarg, &mode_ac, ch);
519 parse_mode(optarg, &mode_battery, ch);
522 parse_acline_mode(optarg, ch);
525 cpu_idle_mark = atoi(optarg);
526 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
527 warnx("%d is not a valid percent",
533 minfreq = atoi(optarg);
535 warnx("%d is not a valid CPU frequency",
541 maxfreq = atoi(optarg);
543 warnx("%d is not a valid CPU frequency",
552 parse_mode(optarg, &mode_none, ch);
555 poll_ival = atoi(optarg);
557 warnx("poll interval is in units of ms");
565 cpu_running_mark = atoi(optarg);
566 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
567 warnx("%d is not a valid percent",
581 /* Poll interval is in units of ms. */
584 /* Look up various sysctl MIBs. */
586 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
587 err(1, "lookup kern.cp_times");
589 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
590 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
592 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
593 err(1, "lookup freq_levels");
595 /* Check if we can read the load and supported freqs. */
596 if (read_usage_times(NULL, nonice))
597 err(1, "read_usage_times");
598 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
599 err(1, "error reading supported CPU frequencies");
601 errx(1, "no CPU frequencies in user-specified range");
603 /* Run in the background unless in verbose mode. */
607 pfh = pidfile_open(pidfile, 0600, &otherpid);
609 if (errno == EEXIST) {
610 errx(1, "powerd already running, pid: %d",
613 warn("cannot open pid file");
615 if (daemon(0, 0) != 0) {
616 warn("cannot enter daemon mode, exiting");
624 /* Decide whether to use ACPI or APM to read the AC line status. */
628 * Exit cleanly on signals.
630 signal(SIGINT, handle_sigs);
631 signal(SIGTERM, handle_sigs);
633 freq = initfreq = curfreq = get_freq();
634 i = get_freq_id(curfreq, freqs, numfreqs);
639 * If we are in adaptive mode and the current frequency is outside the
640 * user-defined range, adjust it to be within the user-defined range.
643 if (acline_status > SRC_UNKNOWN)
644 errx(1, "invalid AC line status %d", acline_status);
645 if ((acline_status == SRC_AC &&
646 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
647 (acline_status == SRC_BATTERY &&
648 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
649 (acline_status == SRC_UNKNOWN &&
650 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
651 /* Read the current frequency. */
652 len = sizeof(curfreq);
653 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
655 warn("error reading current CPU frequency");
657 if (curfreq < freqs[numfreqs - 1]) {
659 printf("CPU frequency is below user-defined "
660 "minimum; changing frequency to %d "
661 "MHz\n", freqs[numfreqs - 1]);
663 if (set_freq(freqs[numfreqs - 1]) != 0) {
664 warn("error setting CPU freq %d",
665 freqs[numfreqs - 1]);
667 } else if (curfreq > freqs[0]) {
669 printf("CPU frequency is above user-defined "
670 "maximum; changing frequency to %d "
673 if (set_freq(freqs[0]) != 0) {
674 warn("error setting CPU freq %d",
684 if (devd_pipe >= 0) {
685 FD_SET(devd_pipe, &fdset);
686 nfds = devd_pipe + 1;
690 if (mode == MODE_HIADAPTIVE || idle < 120)
696 timeout.tv_sec = to / 1000000;
697 timeout.tv_usec = to % 1000000;
698 select(nfds, &fdset, NULL, &fdset, &timeout);
700 /* If the user requested we quit, print some statistics. */
701 if (exit_requested) {
702 if (vflag && mjoules_used != 0)
703 printf("total joules used: %u.%03u\n",
704 (u_int)(mjoules_used / 1000),
705 (int)mjoules_used % 1000);
709 /* Read the current AC status and record the mode. */
711 switch (acline_status) {
722 errx(1, "invalid AC line status %d", acline_status);
725 /* Read the current frequency. */
726 if (idle % 32 == 0) {
727 if ((curfreq = get_freq()) == 0)
729 i = get_freq_id(curfreq, freqs, numfreqs);
733 /* Keep a sum of all power actually used. */
736 (mwatts[i] * (poll_ival / 1000)) / 1000;
739 /* Always switch to the lowest frequency in min mode. */
740 if (mode == MODE_MIN) {
741 freq = freqs[numfreqs - 1];
742 if (curfreq != freq) {
744 printf("now operating on %s power; "
745 "changing frequency to %d MHz\n",
746 modes[acline_status], freq);
749 if (set_freq(freq) != 0) {
750 warn("error setting CPU freq %d",
758 /* Always switch to the highest frequency in max mode. */
759 if (mode == MODE_MAX) {
761 if (curfreq != freq) {
763 printf("now operating on %s power; "
764 "changing frequency to %d MHz\n",
765 modes[acline_status], freq);
768 if (set_freq(freq) != 0) {
769 warn("error setting CPU freq %d",
777 /* Adaptive mode; get the current CPU usage times. */
778 if (read_usage_times(&load, nonice)) {
780 warn("read_usage_times() failed");
784 if (mode == MODE_ADAPTIVE) {
785 if (load > cpu_running_mark) {
786 if (load > 95 || load > cpu_running_mark * 2)
789 freq = freq * load / cpu_running_mark;
792 } else if (load < cpu_idle_mark &&
793 curfreq * load < freqs[get_freq_id(
794 freq * 7 / 8, freqs, numfreqs)] *
797 if (freq < freqs[numfreqs - 1])
798 freq = freqs[numfreqs - 1];
800 } else { /* MODE_HIADAPTIVE */
801 if (load > cpu_running_mark / 2) {
802 if (load > 95 || load > cpu_running_mark)
805 freq = freq * load * 2 / cpu_running_mark;
806 if (freq > freqs[0] * 2)
808 } else if (load < cpu_idle_mark / 2 &&
809 curfreq * load < freqs[get_freq_id(
810 freq * 31 / 32, freqs, numfreqs)] *
811 cpu_running_mark / 2) {
812 freq = freq * 31 / 32;
813 if (freq < freqs[numfreqs - 1])
814 freq = freqs[numfreqs - 1];
818 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
819 load, curfreq, i, freq);
821 j = get_freq_id(freq, freqs, numfreqs);
824 printf("changing clock"
825 " speed from %d MHz to %d MHz\n",
829 if (set_freq(freqs[j]))
830 warn("error setting CPU frequency %d",
834 if (set_freq(initfreq))
835 warn("error setting CPU frequency %d", initfreq);