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;
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.
290 acline_status = SRC_UNKNOWN;
292 if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
293 acline_mode = ac_sysctl;
295 warnx("using sysctl for AC line status");
297 } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
298 acline_mode = ac_sysctl;
300 warnx("using sysctl for AC line status");
303 } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
305 warnx("using APM for AC line status");
306 acline_mode = ac_apm;
309 warnx("unable to determine AC line status");
310 acline_mode = ac_none;
317 if (acline_mode == ac_acpi_devd) {
318 char buf[DEVCTL_MAXBUF], *ptr;
322 rlen = read(devd_pipe, buf, sizeof(buf));
323 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
325 warnx("lost devd connection, switching to sysctl");
327 acline_mode = ac_sysctl;
331 (ptr = strstr(buf, "system=ACPI")) != NULL &&
332 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
333 (ptr = strstr(ptr, "notify=")) != NULL &&
334 sscanf(ptr, "notify=%x", ¬ify) == 1)
335 acline_status = (notify ? SRC_AC : SRC_BATTERY);
337 if (acline_mode == ac_sysctl) {
341 len = sizeof(acline);
342 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
344 acline_status = (acline ? SRC_AC : SRC_BATTERY);
346 acline_status = SRC_UNKNOWN;
349 if (acline_mode == ac_apm) {
350 struct apm_info info;
352 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
353 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
357 acline_mode = ac_none;
358 acline_status = SRC_UNKNOWN;
362 /* try to (re)connect to devd */
363 if (acline_mode == ac_sysctl) {
366 gettimeofday(&now, NULL);
367 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
368 if (devd_init() >= 0) {
370 warnx("using devd for AC line status");
371 acline_mode = ac_acpi_devd;
381 struct sockaddr_un devd_addr;
383 bzero(&devd_addr, sizeof(devd_addr));
384 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
386 warn("%s(): socket()", __func__);
390 devd_addr.sun_family = PF_LOCAL;
391 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
392 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
393 sizeof(devd_addr)) == -1) {
395 warn("%s(): connect()", __func__);
413 parse_mode(char *arg, int *mode, int ch)
416 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
418 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
420 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
421 *mode = MODE_ADAPTIVE;
422 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
423 *mode = MODE_HIADAPTIVE;
425 errx(1, "bad option: -%c %s", (char)ch, optarg);
429 handle_sigs(int __unused sig)
440 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
445 main(int argc, char * argv[])
447 struct timeval timeout;
450 struct pidfh *pfh = NULL;
451 const char *pidfile = NULL;
452 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
453 int minfreq = -1, maxfreq = -1;
454 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
455 uint64_t mjoules_used;
458 /* Default mode for all AC states is adaptive. */
459 mode_ac = mode_none = MODE_HIADAPTIVE;
460 mode_battery = MODE_ADAPTIVE;
461 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
462 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
463 poll_ival = DEFAULT_POLL_INTERVAL;
467 /* User must be root to control frequencies. */
469 errx(1, "must be root to run");
471 while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
474 parse_mode(optarg, &mode_ac, ch);
477 parse_mode(optarg, &mode_battery, ch);
480 cpu_idle_mark = atoi(optarg);
481 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
482 warnx("%d is not a valid percent",
488 minfreq = atoi(optarg);
490 warnx("%d is not a valid CPU frequency",
496 maxfreq = atoi(optarg);
498 warnx("%d is not a valid CPU frequency",
504 parse_mode(optarg, &mode_none, ch);
507 poll_ival = atoi(optarg);
509 warnx("poll interval is in units of ms");
517 cpu_running_mark = atoi(optarg);
518 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
519 warnx("%d is not a valid percent",
533 /* Poll interval is in units of ms. */
536 /* Look up various sysctl MIBs. */
538 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
539 err(1, "lookup kern.cp_times");
541 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
542 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
544 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
545 err(1, "lookup freq_levels");
547 /* Check if we can read the load and supported freqs. */
548 if (read_usage_times(NULL))
549 err(1, "read_usage_times");
550 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
551 err(1, "error reading supported CPU frequencies");
553 errx(1, "no CPU frequencies in user-specified range");
555 /* Run in the background unless in verbose mode. */
559 pfh = pidfile_open(pidfile, 0600, &otherpid);
561 if (errno == EEXIST) {
562 errx(1, "powerd already running, pid: %d",
565 warn("cannot open pid file");
567 if (daemon(0, 0) != 0) {
568 warn("cannot enter daemon mode, exiting");
576 /* Decide whether to use ACPI or APM to read the AC line status. */
580 * Exit cleanly on signals.
582 signal(SIGINT, handle_sigs);
583 signal(SIGTERM, handle_sigs);
585 freq = initfreq = curfreq = get_freq();
586 i = get_freq_id(curfreq, freqs, numfreqs);
591 * If we are in adaptive mode and the current frequency is outside the
592 * user-defined range, adjust it to be within the user-defined range.
595 if (acline_status > SRC_UNKNOWN)
596 errx(1, "invalid AC line status %d", acline_status);
597 if ((acline_status == SRC_AC &&
598 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
599 (acline_status == SRC_BATTERY &&
600 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
601 (acline_status == SRC_UNKNOWN &&
602 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
603 /* Read the current frequency. */
604 len = sizeof(curfreq);
605 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
607 warn("error reading current CPU frequency");
609 if (curfreq < freqs[numfreqs - 1]) {
611 printf("CPU frequency is below user-defined "
612 "minimum; changing frequency to %d "
613 "MHz\n", freqs[numfreqs - 1]);
615 if (set_freq(freqs[numfreqs - 1]) != 0) {
616 warn("error setting CPU freq %d",
617 freqs[numfreqs - 1]);
619 } else if (curfreq > freqs[0]) {
621 printf("CPU frequency is above user-defined "
622 "maximum; changing frequency to %d "
625 if (set_freq(freqs[0]) != 0) {
626 warn("error setting CPU freq %d",
636 if (devd_pipe >= 0) {
637 FD_SET(devd_pipe, &fdset);
638 nfds = devd_pipe + 1;
642 if (mode == MODE_HIADAPTIVE || idle < 120)
648 timeout.tv_sec = to / 1000000;
649 timeout.tv_usec = to % 1000000;
650 select(nfds, &fdset, NULL, &fdset, &timeout);
652 /* If the user requested we quit, print some statistics. */
653 if (exit_requested) {
654 if (vflag && mjoules_used != 0)
655 printf("total joules used: %u.%03u\n",
656 (u_int)(mjoules_used / 1000),
657 (int)mjoules_used % 1000);
661 /* Read the current AC status and record the mode. */
663 switch (acline_status) {
674 errx(1, "invalid AC line status %d", acline_status);
677 /* Read the current frequency. */
678 if (idle % 32 == 0) {
679 if ((curfreq = get_freq()) == 0)
681 i = get_freq_id(curfreq, freqs, numfreqs);
685 /* Keep a sum of all power actually used. */
688 (mwatts[i] * (poll_ival / 1000)) / 1000;
691 /* Always switch to the lowest frequency in min mode. */
692 if (mode == MODE_MIN) {
693 freq = freqs[numfreqs - 1];
694 if (curfreq != freq) {
696 printf("now operating on %s power; "
697 "changing frequency to %d MHz\n",
698 modes[acline_status], freq);
701 if (set_freq(freq) != 0) {
702 warn("error setting CPU freq %d",
710 /* Always switch to the highest frequency in max mode. */
711 if (mode == MODE_MAX) {
713 if (curfreq != freq) {
715 printf("now operating on %s power; "
716 "changing frequency to %d MHz\n",
717 modes[acline_status], freq);
720 if (set_freq(freq) != 0) {
721 warn("error setting CPU freq %d",
729 /* Adaptive mode; get the current CPU usage times. */
730 if (read_usage_times(&load)) {
732 warn("read_usage_times() failed");
736 if (mode == MODE_ADAPTIVE) {
737 if (load > cpu_running_mark) {
738 if (load > 95 || load > cpu_running_mark * 2)
741 freq = freq * load / cpu_running_mark;
744 } else if (load < cpu_idle_mark &&
745 curfreq * load < freqs[get_freq_id(
746 freq * 7 / 8, freqs, numfreqs)] *
749 if (freq < freqs[numfreqs - 1])
750 freq = freqs[numfreqs - 1];
752 } else { /* MODE_HIADAPTIVE */
753 if (load > cpu_running_mark / 2) {
754 if (load > 95 || load > cpu_running_mark)
757 freq = freq * load * 2 / cpu_running_mark;
758 if (freq > freqs[0] * 2)
760 } else if (load < cpu_idle_mark / 2 &&
761 curfreq * load < freqs[get_freq_id(
762 freq * 31 / 32, freqs, numfreqs)] *
763 cpu_running_mark / 2) {
764 freq = freq * 31 / 32;
765 if (freq < freqs[numfreqs - 1])
766 freq = freqs[numfreqs - 1];
770 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
771 load, curfreq, i, freq);
773 j = get_freq_id(freq, freqs, numfreqs);
776 printf("changing clock"
777 " speed from %d MHz to %d MHz\n",
781 if (set_freq(freqs[j]))
782 warn("error setting CPU frequency %d",
786 if (set_freq(initfreq))
787 warn("error setting CPU frequency %d", initfreq);