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))
203 for (p = freqstr; *p != '\0'; p++)
207 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
211 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
216 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
220 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
226 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
227 ((*freqs)[j] <= maxfreq || maxfreq == -1))
233 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
250 len = sizeof(curfreq);
251 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
253 warn("error reading current CPU frequency");
263 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
272 get_freq_id(int freq, int *freqs, int numfreqs)
276 while (i < numfreqs) {
285 * Try to use ACPI to find the AC line status. If this fails, fall back
286 * to APM. If nothing succeeds, we'll just run in default mode.
291 int skip_source_check;
294 acline_status = SRC_UNKNOWN;
295 skip_source_check = (acline_mode_user == ac_none ||
296 acline_mode_user == ac_acpi_devd);
298 if ((skip_source_check || acline_mode_user == ac_sysctl) &&
299 sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
300 acline_mode = ac_sysctl;
302 warnx("using sysctl for AC line status");
304 } else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
305 sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
306 acline_mode = ac_sysctl;
308 warnx("using sysctl for AC line status");
311 } else if ((skip_source_check || acline_mode_user == ac_apm) &&
312 (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
314 warnx("using APM for AC line status");
315 acline_mode = ac_apm;
318 warnx("unable to determine AC line status");
319 acline_mode = ac_none;
326 if (acline_mode == ac_acpi_devd) {
327 char buf[DEVCTL_MAXBUF], *ptr;
331 rlen = read(devd_pipe, buf, sizeof(buf));
332 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
334 warnx("lost devd connection, switching to sysctl");
336 acline_mode = ac_sysctl;
340 (ptr = strstr(buf, "system=ACPI")) != NULL &&
341 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
342 (ptr = strstr(ptr, "notify=")) != NULL &&
343 sscanf(ptr, "notify=%x", ¬ify) == 1)
344 acline_status = (notify ? SRC_AC : SRC_BATTERY);
346 if (acline_mode == ac_sysctl) {
350 len = sizeof(acline);
351 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
353 acline_status = (acline ? SRC_AC : SRC_BATTERY);
355 acline_status = SRC_UNKNOWN;
358 if (acline_mode == ac_apm) {
359 struct apm_info info;
361 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
362 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
366 acline_mode = ac_none;
367 acline_status = SRC_UNKNOWN;
371 /* try to (re)connect to devd */
373 if ((acline_mode == ac_sysctl &&
374 (acline_mode_user == ac_none ||
375 acline_mode_user == ac_acpi_devd)) ||
376 (acline_mode == ac_apm &&
377 acline_mode_user == ac_acpi_devd)) {
379 if (acline_mode == ac_sysctl &&
380 (acline_mode_user == ac_none ||
381 acline_mode_user == ac_acpi_devd)) {
385 gettimeofday(&now, NULL);
386 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
387 if (devd_init() >= 0) {
389 warnx("using devd for AC line status");
390 acline_mode = ac_acpi_devd;
400 struct sockaddr_un devd_addr;
402 bzero(&devd_addr, sizeof(devd_addr));
403 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
405 warn("%s(): socket()", __func__);
409 devd_addr.sun_family = PF_LOCAL;
410 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
411 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
412 sizeof(devd_addr)) == -1) {
414 warn("%s(): connect()", __func__);
432 parse_mode(char *arg, int *mode, int ch)
435 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
437 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
439 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
440 *mode = MODE_ADAPTIVE;
441 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
442 *mode = MODE_HIADAPTIVE;
444 errx(1, "bad option: -%c %s", (char)ch, optarg);
448 parse_acline_mode(char *arg, int ch)
450 if (strcmp(arg, "sysctl") == 0)
451 acline_mode_user = ac_sysctl;
452 else if (strcmp(arg, "devd") == 0)
453 acline_mode_user = ac_acpi_devd;
455 else if (strcmp(arg, "apm") == 0)
456 acline_mode_user = ac_apm;
459 errx(1, "bad option: -%c %s", (char)ch, optarg);
463 handle_sigs(int __unused sig)
474 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
479 main(int argc, char * argv[])
481 struct timeval timeout;
484 struct pidfh *pfh = NULL;
485 const char *pidfile = NULL;
486 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
487 int minfreq = -1, maxfreq = -1;
488 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
489 uint64_t mjoules_used;
492 /* Default mode for all AC states is adaptive. */
493 mode_ac = mode_none = MODE_HIADAPTIVE;
494 mode_battery = MODE_ADAPTIVE;
495 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
496 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
497 poll_ival = DEFAULT_POLL_INTERVAL;
501 /* User must be root to control frequencies. */
503 errx(1, "must be root to run");
505 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:s:v")) != -1)
508 parse_mode(optarg, &mode_ac, ch);
511 parse_mode(optarg, &mode_battery, ch);
514 parse_acline_mode(optarg, ch);
517 cpu_idle_mark = atoi(optarg);
518 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
519 warnx("%d is not a valid percent",
525 minfreq = atoi(optarg);
527 warnx("%d is not a valid CPU frequency",
533 maxfreq = atoi(optarg);
535 warnx("%d is not a valid CPU frequency",
541 parse_mode(optarg, &mode_none, ch);
544 poll_ival = atoi(optarg);
546 warnx("poll interval is in units of ms");
554 cpu_running_mark = atoi(optarg);
555 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
556 warnx("%d is not a valid percent",
570 /* Poll interval is in units of ms. */
573 /* Look up various sysctl MIBs. */
575 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
576 err(1, "lookup kern.cp_times");
578 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
579 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
581 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
582 err(1, "lookup freq_levels");
584 /* Check if we can read the load and supported freqs. */
585 if (read_usage_times(NULL))
586 err(1, "read_usage_times");
587 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
588 err(1, "error reading supported CPU frequencies");
590 errx(1, "no CPU frequencies in user-specified range");
592 /* Run in the background unless in verbose mode. */
596 pfh = pidfile_open(pidfile, 0600, &otherpid);
598 if (errno == EEXIST) {
599 errx(1, "powerd already running, pid: %d",
602 warn("cannot open pid file");
604 if (daemon(0, 0) != 0) {
605 warn("cannot enter daemon mode, exiting");
613 /* Decide whether to use ACPI or APM to read the AC line status. */
617 * Exit cleanly on signals.
619 signal(SIGINT, handle_sigs);
620 signal(SIGTERM, handle_sigs);
622 freq = initfreq = curfreq = get_freq();
623 i = get_freq_id(curfreq, freqs, numfreqs);
628 * If we are in adaptive mode and the current frequency is outside the
629 * user-defined range, adjust it to be within the user-defined range.
632 if (acline_status > SRC_UNKNOWN)
633 errx(1, "invalid AC line status %d", acline_status);
634 if ((acline_status == SRC_AC &&
635 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
636 (acline_status == SRC_BATTERY &&
637 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
638 (acline_status == SRC_UNKNOWN &&
639 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
640 /* Read the current frequency. */
641 len = sizeof(curfreq);
642 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
644 warn("error reading current CPU frequency");
646 if (curfreq < freqs[numfreqs - 1]) {
648 printf("CPU frequency is below user-defined "
649 "minimum; changing frequency to %d "
650 "MHz\n", freqs[numfreqs - 1]);
652 if (set_freq(freqs[numfreqs - 1]) != 0) {
653 warn("error setting CPU freq %d",
654 freqs[numfreqs - 1]);
656 } else if (curfreq > freqs[0]) {
658 printf("CPU frequency is above user-defined "
659 "maximum; changing frequency to %d "
662 if (set_freq(freqs[0]) != 0) {
663 warn("error setting CPU freq %d",
673 if (devd_pipe >= 0) {
674 FD_SET(devd_pipe, &fdset);
675 nfds = devd_pipe + 1;
679 if (mode == MODE_HIADAPTIVE || idle < 120)
685 timeout.tv_sec = to / 1000000;
686 timeout.tv_usec = to % 1000000;
687 select(nfds, &fdset, NULL, &fdset, &timeout);
689 /* If the user requested we quit, print some statistics. */
690 if (exit_requested) {
691 if (vflag && mjoules_used != 0)
692 printf("total joules used: %u.%03u\n",
693 (u_int)(mjoules_used / 1000),
694 (int)mjoules_used % 1000);
698 /* Read the current AC status and record the mode. */
700 switch (acline_status) {
711 errx(1, "invalid AC line status %d", acline_status);
714 /* Read the current frequency. */
715 if (idle % 32 == 0) {
716 if ((curfreq = get_freq()) == 0)
718 i = get_freq_id(curfreq, freqs, numfreqs);
722 /* Keep a sum of all power actually used. */
725 (mwatts[i] * (poll_ival / 1000)) / 1000;
728 /* Always switch to the lowest frequency in min mode. */
729 if (mode == MODE_MIN) {
730 freq = freqs[numfreqs - 1];
731 if (curfreq != freq) {
733 printf("now operating on %s power; "
734 "changing frequency to %d MHz\n",
735 modes[acline_status], freq);
738 if (set_freq(freq) != 0) {
739 warn("error setting CPU freq %d",
747 /* Always switch to the highest frequency in max mode. */
748 if (mode == MODE_MAX) {
750 if (curfreq != freq) {
752 printf("now operating on %s power; "
753 "changing frequency to %d MHz\n",
754 modes[acline_status], freq);
757 if (set_freq(freq) != 0) {
758 warn("error setting CPU freq %d",
766 /* Adaptive mode; get the current CPU usage times. */
767 if (read_usage_times(&load)) {
769 warn("read_usage_times() failed");
773 if (mode == MODE_ADAPTIVE) {
774 if (load > cpu_running_mark) {
775 if (load > 95 || load > cpu_running_mark * 2)
778 freq = freq * load / cpu_running_mark;
781 } else if (load < cpu_idle_mark &&
782 curfreq * load < freqs[get_freq_id(
783 freq * 7 / 8, freqs, numfreqs)] *
786 if (freq < freqs[numfreqs - 1])
787 freq = freqs[numfreqs - 1];
789 } else { /* MODE_HIADAPTIVE */
790 if (load > cpu_running_mark / 2) {
791 if (load > 95 || load > cpu_running_mark)
794 freq = freq * load * 2 / cpu_running_mark;
795 if (freq > freqs[0] * 2)
797 } else if (load < cpu_idle_mark / 2 &&
798 curfreq * load < freqs[get_freq_id(
799 freq * 31 / 32, freqs, numfreqs)] *
800 cpu_running_mark / 2) {
801 freq = freq * 31 / 32;
802 if (freq < freqs[numfreqs - 1])
803 freq = freqs[numfreqs - 1];
807 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
808 load, curfreq, i, freq);
810 j = get_freq_id(freq, freqs, numfreqs);
813 printf("changing clock"
814 " speed from %d MHz to %d MHz\n",
818 if (set_freq(freqs[j]))
819 warn("error setting CPU frequency %d",
823 if (set_freq(initfreq))
824 warn("error setting CPU frequency %d", initfreq);