1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2004 Colin Percival
5 * Copyright (c) 2005 Nate Lawson
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted providing that the following conditions
10 * are met:
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.
16 *
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.
28 */
29
30 #include <sys/param.h>
31 #include <sys/ioctl.h>
32 #include <sys/linker.h>
33 #include <sys/module.h>
34 #include <sys/sysctl.h>
35 #include <sys/resource.h>
36 #include <sys/socket.h>
37 #include <sys/time.h>
38 #include <sys/un.h>
39
40 #include <netlink/netlink.h>
41 #include <netlink/netlink_generic.h>
42 #include <netlink/netlink_snl.h>
43 #include <netlink/netlink_snl_generic.h>
44 #include <netlink/netlink_sysevent.h>
45
46 #include <err.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <libutil.h>
50 #include <signal.h>
51 #include <stdbool.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <sysexits.h>
56 #include <unistd.h>
57
58 #ifdef __i386__
59 #define USE_APM
60 #endif
61
62 #ifdef USE_APM
63 #include <machine/apm_bios.h>
64 #endif
65
66 #define DEFAULT_ACTIVE_PERCENT 75
67 #define DEFAULT_IDLE_PERCENT 50
68 #define DEFAULT_POLL_INTERVAL 250 /* Poll interval in milliseconds */
69
70 typedef enum {
71 MODE_MIN,
72 MODE_ADAPTIVE,
73 MODE_HIADAPTIVE,
74 MODE_MAX,
75 } modes_t;
76
77 typedef enum {
78 SRC_AC,
79 SRC_BATTERY,
80 SRC_UNKNOWN,
81 } power_src_t;
82
83 static const char *modes[] = {
84 "AC",
85 "battery",
86 "unknown"
87 };
88
89 #define ACPIAC "hw.acpi.acline"
90 #define PMUAC "dev.pmu.0.acline"
91 #define APMDEV "/dev/apm"
92 #define DEVDPIPE "/var/run/devd.pipe"
93 #define DEVCTL_MAXBUF 1024
94
95 static int read_usage_times(int *load, int nonice);
96 static int read_freqs(int *numfreqs, int **freqs, int **power,
97 int minfreq, int maxfreq);
98 static int set_freq(int freq);
99 static void acline_init(void);
100 static void acline_read(int rfds);
101 static bool netlink_init(void);
102 static int devd_init(void);
103 static void devd_close(void);
104 static void handle_sigs(int sig);
105 static void parse_mode(char *arg, int *mode, int ch);
106 static void usage(void);
107
108 /* Sysctl data structures. */
109 static int cp_times_mib[2];
110 static int freq_mib[4];
111 static int levels_mib[4];
112 static int acline_mib[4];
113 static size_t acline_mib_len;
114
115 /* Configuration */
116 static int cpu_running_mark;
117 static int cpu_idle_mark;
118 static int poll_ival;
119 static int vflag;
120
121 static volatile sig_atomic_t exit_requested;
122 static power_src_t acline_status;
123 typedef enum {
124 ac_none,
125 ac_sysctl,
126 ac_acpi_devd,
127 #ifdef USE_APM
128 ac_apm,
129 #endif
130 ac_acpi_netlink,
131 } acline_mode_t;
132 static acline_mode_t acline_mode;
133 static acline_mode_t acline_mode_user = ac_none;
134 #ifdef USE_APM
135 static int apm_fd = -1;
136 #endif
137 static int devd_pipe = -1;
138 static bool try_netlink = true;
139 static struct snl_state ss;
140
141 #define DEVD_RETRY_INTERVAL 60 /* seconds */
142 static struct timeval tried_devd;
143
144 /*
145 * This function returns summary load of all CPUs. It was made so
146 * intentionally to not reduce performance in scenarios when several
147 * threads are processing requests as a pipeline -- running one at
148 * a time on different CPUs and waiting for each other. If nonice
149 * is nonzero, only user+sys+intr time will be counted as load; any
150 * nice time will be treated as if idle.
151 */
152 static int
read_usage_times(int * load,int nonice)153 read_usage_times(int *load, int nonice)
154 {
155 static long *cp_times = NULL, *cp_times_old = NULL;
156 static int ncpus = 0;
157 size_t cp_times_len;
158 int error, cpu, i, total, excl;
159
160 if (cp_times == NULL) {
161 cp_times_len = 0;
162 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
163 if (error)
164 return (error);
165 if ((cp_times = malloc(cp_times_len)) == NULL)
166 return (errno);
167 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
168 free(cp_times);
169 cp_times = NULL;
170 return (errno);
171 }
172 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
173 }
174
175 cp_times_len = sizeof(long) * CPUSTATES * ncpus;
176 error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
177 if (error)
178 return (error);
179
180 if (load) {
181 *load = 0;
182 for (cpu = 0; cpu < ncpus; cpu++) {
183 total = 0;
184 for (i = 0; i < CPUSTATES; i++) {
185 total += cp_times[cpu * CPUSTATES + i] -
186 cp_times_old[cpu * CPUSTATES + i];
187 }
188 if (total == 0)
189 continue;
190 excl = cp_times[cpu * CPUSTATES + CP_IDLE] -
191 cp_times_old[cpu * CPUSTATES + CP_IDLE];
192 if (nonice)
193 excl += cp_times[cpu * CPUSTATES + CP_NICE] -
194 cp_times_old[cpu * CPUSTATES + CP_NICE];
195 *load += 100 - excl * 100 / total;
196 }
197 }
198
199 memcpy(cp_times_old, cp_times, cp_times_len);
200
201 return (0);
202 }
203
204 static int
read_freqs(int * numfreqs,int ** freqs,int ** power,int minfreq,int maxfreq)205 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
206 {
207 char *freqstr, *p, *q;
208 int i, j;
209 size_t len = 0;
210
211 if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
212 return (-1);
213 if ((freqstr = malloc(len)) == NULL)
214 return (-1);
215 if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0)) {
216 free(freqstr);
217 return (-1);
218 }
219
220 *numfreqs = 1;
221 for (p = freqstr; *p != '\0'; p++)
222 if (*p == ' ')
223 (*numfreqs)++;
224
225 if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
226 free(freqstr);
227 return (-1);
228 }
229 if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
230 free(freqstr);
231 free(*freqs);
232 return (-1);
233 }
234 for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
235 q = strchr(p, ' ');
236 if (q != NULL)
237 *q = '\0';
238 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
239 free(freqstr);
240 free(*freqs);
241 free(*power);
242 return (-1);
243 }
244 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
245 ((*freqs)[j] <= maxfreq || maxfreq == -1))
246 j++;
247 p = q + 1;
248 }
249
250 *numfreqs = j;
251 if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
252 free(freqstr);
253 free(*freqs);
254 free(*power);
255 return (-1);
256 }
257
258 free(freqstr);
259 return (0);
260 }
261
262 static int
get_freq(void)263 get_freq(void)
264 {
265 size_t len;
266 int curfreq;
267
268 len = sizeof(curfreq);
269 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
270 if (vflag)
271 warn("error reading current CPU frequency");
272 curfreq = 0;
273 }
274 return (curfreq);
275 }
276
277 static int
set_freq(int freq)278 set_freq(int freq)
279 {
280
281 if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
282 if (errno != EPERM)
283 return (-1);
284 }
285
286 return (0);
287 }
288
289 static int
get_freq_id(int freq,int * freqs,int numfreqs)290 get_freq_id(int freq, int *freqs, int numfreqs)
291 {
292 int i = 1;
293
294 while (i < numfreqs) {
295 if (freqs[i] < freq)
296 break;
297 i++;
298 }
299 return (i - 1);
300 }
301
302 /*
303 * Try to use ACPI to find the AC line status. If this fails, fall back
304 * to APM. If nothing succeeds, we'll just run in default mode.
305 */
306 static void
acline_init(void)307 acline_init(void)
308 {
309 int skip_source_check;
310
311 acline_mib_len = 4;
312 acline_status = SRC_UNKNOWN;
313 skip_source_check = (acline_mode_user == ac_none ||
314 acline_mode_user == ac_acpi_devd);
315
316 if ((skip_source_check || acline_mode_user == ac_sysctl) &&
317 sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
318 acline_mode = ac_sysctl;
319 if (vflag)
320 warnx("using sysctl for AC line status");
321 #ifdef __powerpc__
322 } else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
323 sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
324 acline_mode = ac_sysctl;
325 if (vflag)
326 warnx("using sysctl for AC line status");
327 #endif
328 #ifdef USE_APM
329 } else if ((skip_source_check || acline_mode_user == ac_apm) &&
330 (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
331 if (vflag)
332 warnx("using APM for AC line status");
333 acline_mode = ac_apm;
334 #endif
335 } else {
336 warnx("unable to determine AC line status");
337 acline_mode = ac_none;
338 }
339 }
340
341 struct nlevent {
342 const char *name;
343 const char *subsystem;
344 const char *type;
345 const char *data;
346 };
347 #define _OUT(_field) offsetof(struct nlevent, _field)
348 static struct snl_attr_parser ap_nlevent_get[] = {
349 { .type = NLSE_ATTR_SYSTEM, .off = _OUT(name), .cb = snl_attr_get_string },
350 { .type = NLSE_ATTR_SUBSYSTEM, .off = _OUT(subsystem), .cb = snl_attr_get_string },
351 { .type = NLSE_ATTR_TYPE, .off = _OUT(type), .cb = snl_attr_get_string },
352 { .type = NLSE_ATTR_DATA, .off = _OUT(data), .cb = snl_attr_get_string },
353 };
354 #undef _OUT
355
356 SNL_DECLARE_GENL_PARSER(nlevent_get_parser, ap_nlevent_get);
357
358 static void
acline_read(int rfds)359 acline_read(int rfds)
360 {
361 if (acline_mode == ac_acpi_netlink) {
362 struct nlmsghdr *hdr;
363 struct nlevent ne;
364 char *ptr;
365 int notify;
366
367 if (rfds == 0)
368 return;
369 hdr = snl_read_message(&ss);
370 if (hdr != NULL && hdr->nlmsg_type != NLMSG_ERROR) {
371 memset(&ne, 0, sizeof(ne));
372 if (!snl_parse_nlmsg(&ss, hdr, &nlevent_get_parser, &ne))
373 return;
374 if (strcmp(ne.subsystem, "ACAD") != 0)
375 return;
376 if ((ptr = strstr(ne.data, "notify=")) != NULL &&
377 sscanf(ptr, "notify=%x", ¬ify) == 1)
378 acline_status = (notify ? SRC_AC : SRC_BATTERY);
379 }
380 return;
381
382 }
383 if (acline_mode == ac_acpi_devd) {
384 char buf[DEVCTL_MAXBUF], *ptr;
385 ssize_t rlen;
386 int notify;
387
388 rlen = read(devd_pipe, buf, sizeof(buf));
389 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
390 if (vflag)
391 warnx("lost devd connection, switching to sysctl");
392 devd_close();
393 acline_mode = ac_sysctl;
394 /* FALLTHROUGH */
395 }
396 if (rlen > 0 &&
397 (ptr = strstr(buf, "system=ACPI")) != NULL &&
398 (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
399 (ptr = strstr(ptr, "notify=")) != NULL &&
400 sscanf(ptr, "notify=%x", ¬ify) == 1)
401 acline_status = (notify ? SRC_AC : SRC_BATTERY);
402 }
403 if (acline_mode == ac_sysctl) {
404 int acline;
405 size_t len;
406
407 len = sizeof(acline);
408 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
409 NULL, 0) == 0)
410 acline_status = (acline ? SRC_AC : SRC_BATTERY);
411 else
412 acline_status = SRC_UNKNOWN;
413 }
414 #ifdef USE_APM
415 if (acline_mode == ac_apm) {
416 struct apm_info info;
417
418 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
419 acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
420 } else {
421 close(apm_fd);
422 apm_fd = -1;
423 acline_mode = ac_none;
424 acline_status = SRC_UNKNOWN;
425 }
426 }
427 #endif
428 /* try to (re)connect to devd */
429 #ifdef USE_APM
430 if ((acline_mode == ac_sysctl &&
431 (acline_mode_user == ac_none ||
432 acline_mode_user == ac_acpi_devd)) ||
433 (acline_mode == ac_apm &&
434 acline_mode_user == ac_acpi_devd)) {
435 #else
436 if (acline_mode == ac_sysctl &&
437 (acline_mode_user == ac_none ||
438 acline_mode_user == ac_acpi_devd ||
439 acline_mode_user == ac_acpi_netlink)) {
440 #endif
441 struct timeval now;
442
443 if (acline_mode_user != ac_acpi_devd && try_netlink) {
444 try_netlink = false; /* only try once */
445 if (netlink_init()) {
446 if (vflag)
447 warnx("using netlink for AC line status");
448 acline_mode = ac_acpi_netlink;
449 }
450 return;
451 }
452 gettimeofday(&now, NULL);
453 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
454 if (devd_init() >= 0) {
455 if (vflag)
456 warnx("using devd for AC line status");
457 acline_mode = ac_acpi_devd;
458 }
459 tried_devd = now;
460 }
461 }
462 }
463
464 bool
465 netlink_init(void)
466 {
467 uint32_t group;
468
469 if (modfind("nlsysevent") < 0)
470 kldload("nlsysevent");
471 if (modfind("nlsysevent") < 0)
472 return (false);
473
474 if (!snl_init(&ss, NETLINK_GENERIC) || (group =
475 snl_get_genl_mcast_group(&ss, "nlsysevent", "ACPI", NULL)) == 0) {
476 warnx("Cannot find \"nlsysevent\" family \"ACPI\" group");
477 return (false);
478 }
479
480 if (setsockopt(ss.fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group,
481 sizeof(group)) == -1) {
482 warnx("Cannot subscribe to \"ACPI\"");
483 return (false);
484 }
485 return (true);
486 }
487
488 static int
489 devd_init(void)
490 {
491 struct sockaddr_un devd_addr;
492
493 bzero(&devd_addr, sizeof(devd_addr));
494 if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
495 if (vflag)
496 warn("%s(): socket()", __func__);
497 return (-1);
498 }
499
500 devd_addr.sun_family = PF_LOCAL;
501 strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
502 if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
503 sizeof(devd_addr)) == -1) {
504 if (vflag)
505 warn("%s(): connect()", __func__);
506 close(devd_pipe);
507 devd_pipe = -1;
508 return (-1);
509 }
510
511 return (devd_pipe);
512 }
513
514 static void
515 devd_close(void)
516 {
517
518 close(devd_pipe);
519 devd_pipe = -1;
520 }
521
522 static void
523 parse_mode(char *arg, int *mode, int ch)
524 {
525
526 if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
527 *mode = MODE_MIN;
528 else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
529 *mode = MODE_MAX;
530 else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
531 *mode = MODE_ADAPTIVE;
532 else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
533 *mode = MODE_HIADAPTIVE;
534 else
535 errx(1, "bad option: -%c %s", (char)ch, optarg);
536 }
537
538 static void
539 parse_acline_mode(char *arg, int ch)
540 {
541 if (strcmp(arg, "sysctl") == 0)
542 acline_mode_user = ac_sysctl;
543 else if (strcmp(arg, "devd") == 0)
544 acline_mode_user = ac_acpi_devd;
545 #ifdef USE_APM
546 else if (strcmp(arg, "apm") == 0)
547 acline_mode_user = ac_apm;
548 #endif
549 else if (strcmp(arg, "netlink") == 0)
550 acline_mode_user = ac_acpi_netlink;
551 else
552 errx(1, "bad option: -%c %s", (char)ch, optarg);
553 }
554
555 static void
556 handle_sigs(int __unused sig)
557 {
558
559 exit_requested = 1;
560 }
561
562 static void
563 usage(void)
564 {
565
566 fprintf(stderr,
567 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-N] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
568 exit(1);
569 }
570
571 int
572 main(int argc, char * argv[])
573 {
574 struct timeval timeout;
575 fd_set fdset;
576 int nfds, rfds;
577 struct pidfh *pfh = NULL;
578 const char *pidfile = NULL;
579 int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
580 int minfreq = -1, maxfreq = -1;
581 int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
582 uint64_t mjoules_used;
583 size_t len;
584 int nonice;
585
586 /* Default mode for all AC states is adaptive. */
587 mode_ac = mode_none = MODE_HIADAPTIVE;
588 mode_battery = MODE_ADAPTIVE;
589 cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
590 cpu_idle_mark = DEFAULT_IDLE_PERCENT;
591 poll_ival = DEFAULT_POLL_INTERVAL;
592 mjoules_used = 0;
593 vflag = 0;
594 nonice = 0;
595
596 /* User must be root to control frequencies. */
597 if (geteuid() != 0)
598 errx(1, "must be root to run");
599
600 while ((ch = getopt(argc, argv, "a:b:i:m:M:Nn:p:P:r:s:v")) != -1)
601 switch (ch) {
602 case 'a':
603 parse_mode(optarg, &mode_ac, ch);
604 break;
605 case 'b':
606 parse_mode(optarg, &mode_battery, ch);
607 break;
608 case 's':
609 parse_acline_mode(optarg, ch);
610 break;
611 case 'i':
612 cpu_idle_mark = atoi(optarg);
613 if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
614 warnx("%d is not a valid percent",
615 cpu_idle_mark);
616 usage();
617 }
618 break;
619 case 'm':
620 minfreq = atoi(optarg);
621 if (minfreq < 0) {
622 warnx("%d is not a valid CPU frequency",
623 minfreq);
624 usage();
625 }
626 break;
627 case 'M':
628 maxfreq = atoi(optarg);
629 if (maxfreq < 0) {
630 warnx("%d is not a valid CPU frequency",
631 maxfreq);
632 usage();
633 }
634 break;
635 case 'N':
636 nonice = 1;
637 break;
638 case 'n':
639 parse_mode(optarg, &mode_none, ch);
640 break;
641 case 'p':
642 poll_ival = atoi(optarg);
643 if (poll_ival < 5) {
644 warnx("poll interval is in units of ms");
645 usage();
646 }
647 break;
648 case 'P':
649 pidfile = optarg;
650 break;
651 case 'r':
652 cpu_running_mark = atoi(optarg);
653 if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
654 warnx("%d is not a valid percent",
655 cpu_running_mark);
656 usage();
657 }
658 break;
659 case 'v':
660 vflag = 1;
661 break;
662 default:
663 usage();
664 }
665
666 mode = mode_none;
667
668 /* Poll interval is in units of ms. */
669 poll_ival *= 1000;
670
671 /* Look up various sysctl MIBs. */
672 len = 2;
673 if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
674 err(1, "lookup kern.cp_times");
675 len = 4;
676 if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
677 err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
678 len = 4;
679 if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
680 err(1, "lookup freq_levels");
681
682 /* Check if we can read the load and supported freqs. */
683 if (read_usage_times(NULL, nonice))
684 err(1, "read_usage_times");
685 if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
686 err(1, "error reading supported CPU frequencies");
687 if (numfreqs == 0)
688 errx(1, "no CPU frequencies in user-specified range");
689
690 /* Run in the background unless in verbose mode. */
691 if (!vflag) {
692 pid_t otherpid;
693
694 pfh = pidfile_open(pidfile, 0600, &otherpid);
695 if (pfh == NULL) {
696 if (errno == EEXIST) {
697 errx(1, "powerd already running, pid: %d",
698 otherpid);
699 }
700 warn("cannot open pid file");
701 }
702 if (daemon(0, 0) != 0) {
703 warn("cannot enter daemon mode, exiting");
704 pidfile_remove(pfh);
705 exit(EXIT_FAILURE);
706
707 }
708 pidfile_write(pfh);
709 }
710
711 /* Decide whether to use ACPI or APM to read the AC line status. */
712 acline_init();
713
714 /*
715 * Exit cleanly on signals.
716 */
717 signal(SIGINT, handle_sigs);
718 signal(SIGTERM, handle_sigs);
719
720 freq = initfreq = curfreq = get_freq();
721 i = get_freq_id(curfreq, freqs, numfreqs);
722 if (freq < 1)
723 freq = 1;
724
725 /*
726 * If we are in adaptive mode and the current frequency is outside the
727 * user-defined range, adjust it to be within the user-defined range.
728 */
729 acline_read(0);
730 if (acline_status > SRC_UNKNOWN)
731 errx(1, "invalid AC line status %d", acline_status);
732 if ((acline_status == SRC_AC &&
733 (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
734 (acline_status == SRC_BATTERY &&
735 (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
736 (acline_status == SRC_UNKNOWN &&
737 (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
738 /* Read the current frequency. */
739 len = sizeof(curfreq);
740 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
741 if (vflag)
742 warn("error reading current CPU frequency");
743 }
744 if (curfreq < freqs[numfreqs - 1]) {
745 if (vflag) {
746 printf("CPU frequency is below user-defined "
747 "minimum; changing frequency to %d "
748 "MHz\n", freqs[numfreqs - 1]);
749 }
750 if (set_freq(freqs[numfreqs - 1]) != 0) {
751 warn("error setting CPU freq %d",
752 freqs[numfreqs - 1]);
753 }
754 } else if (curfreq > freqs[0]) {
755 if (vflag) {
756 printf("CPU frequency is above user-defined "
757 "maximum; changing frequency to %d "
758 "MHz\n", freqs[0]);
759 }
760 if (set_freq(freqs[0]) != 0) {
761 warn("error setting CPU freq %d",
762 freqs[0]);
763 }
764 }
765 }
766
767 idle = 0;
768 /* Main loop. */
769 for (;;) {
770 FD_ZERO(&fdset);
771 if (devd_pipe >= 0) {
772 FD_SET(devd_pipe, &fdset);
773 nfds = devd_pipe + 1;
774 } else if (acline_mode == ac_acpi_netlink) {
775 FD_SET(ss.fd, &fdset);
776 nfds = ss.fd + 1;
777 } else {
778 nfds = 0;
779 }
780 if (mode == MODE_HIADAPTIVE || idle < 120)
781 to = poll_ival;
782 else if (idle < 360)
783 to = poll_ival * 2;
784 else
785 to = poll_ival * 4;
786 timeout.tv_sec = to / 1000000;
787 timeout.tv_usec = to % 1000000;
788 rfds = select(nfds, &fdset, NULL, &fdset, &timeout);
789
790 /* If the user requested we quit, print some statistics. */
791 if (exit_requested) {
792 if (vflag && mjoules_used != 0)
793 printf("total joules used: %u.%03u\n",
794 (u_int)(mjoules_used / 1000),
795 (int)mjoules_used % 1000);
796 break;
797 }
798
799 /* Read the current AC status and record the mode. */
800 acline_read(rfds);
801 switch (acline_status) {
802 case SRC_AC:
803 mode = mode_ac;
804 break;
805 case SRC_BATTERY:
806 mode = mode_battery;
807 break;
808 case SRC_UNKNOWN:
809 mode = mode_none;
810 break;
811 default:
812 errx(1, "invalid AC line status %d", acline_status);
813 }
814
815 /* Read the current frequency. */
816 if (idle % 32 == 0) {
817 if ((curfreq = get_freq()) == 0)
818 continue;
819 i = get_freq_id(curfreq, freqs, numfreqs);
820 }
821 idle++;
822 if (vflag) {
823 /* Keep a sum of all power actually used. */
824 if (mwatts[i] != -1)
825 mjoules_used +=
826 (mwatts[i] * (poll_ival / 1000)) / 1000;
827 }
828
829 /* Always switch to the lowest frequency in min mode. */
830 if (mode == MODE_MIN) {
831 freq = freqs[numfreqs - 1];
832 if (curfreq != freq) {
833 if (vflag) {
834 printf("now operating on %s power; "
835 "changing frequency to %d MHz\n",
836 modes[acline_status], freq);
837 }
838 idle = 0;
839 if (set_freq(freq) != 0) {
840 warn("error setting CPU freq %d",
841 freq);
842 continue;
843 }
844 }
845 continue;
846 }
847
848 /* Always switch to the highest frequency in max mode. */
849 if (mode == MODE_MAX) {
850 freq = freqs[0];
851 if (curfreq != freq) {
852 if (vflag) {
853 printf("now operating on %s power; "
854 "changing frequency to %d MHz\n",
855 modes[acline_status], freq);
856 }
857 idle = 0;
858 if (set_freq(freq) != 0) {
859 warn("error setting CPU freq %d",
860 freq);
861 continue;
862 }
863 }
864 continue;
865 }
866
867 /* Adaptive mode; get the current CPU usage times. */
868 if (read_usage_times(&load, nonice)) {
869 if (vflag)
870 warn("read_usage_times() failed");
871 continue;
872 }
873
874 if (mode == MODE_ADAPTIVE) {
875 if (load > cpu_running_mark) {
876 if (load > 95 || load > cpu_running_mark * 2)
877 freq *= 2;
878 else
879 freq = freq * load / cpu_running_mark;
880 if (freq > freqs[0])
881 freq = freqs[0];
882 } else if (load < cpu_idle_mark &&
883 curfreq * load < freqs[get_freq_id(
884 freq * 7 / 8, freqs, numfreqs)] *
885 cpu_running_mark) {
886 freq = freq * 7 / 8;
887 if (freq < freqs[numfreqs - 1])
888 freq = freqs[numfreqs - 1];
889 }
890 } else { /* MODE_HIADAPTIVE */
891 if (load > cpu_running_mark / 2) {
892 if (load > 95 || load > cpu_running_mark)
893 freq *= 4;
894 else
895 freq = freq * load * 2 / cpu_running_mark;
896 if (freq > freqs[0] * 2)
897 freq = freqs[0] * 2;
898 } else if (load < cpu_idle_mark / 2 &&
899 curfreq * load < freqs[get_freq_id(
900 freq * 31 / 32, freqs, numfreqs)] *
901 cpu_running_mark / 2) {
902 freq = freq * 31 / 32;
903 if (freq < freqs[numfreqs - 1])
904 freq = freqs[numfreqs - 1];
905 }
906 }
907 if (vflag) {
908 printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
909 load, curfreq, i, freq);
910 }
911 j = get_freq_id(freq, freqs, numfreqs);
912 if (i != j) {
913 if (vflag) {
914 printf("changing clock"
915 " speed from %d MHz to %d MHz\n",
916 freqs[i], freqs[j]);
917 }
918 idle = 0;
919 if (set_freq(freqs[j]))
920 warn("error setting CPU frequency %d",
921 freqs[j]);
922 }
923 }
924 if (set_freq(initfreq))
925 warn("error setting CPU frequency %d", initfreq);
926 free(freqs);
927 free(mwatts);
928 devd_close();
929 if (!vflag)
930 pidfile_remove(pfh);
931
932 exit(0);
933 }
934