xref: /freebsd/usr.sbin/powerd/powerd.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
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>
38 #include <sys/time.h>
39 #include <sys/un.h>
40 
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <libutil.h>
45 #include <signal.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <unistd.h>
51 
52 #ifdef __i386__
53 #define USE_APM
54 #endif
55 
56 #ifdef USE_APM
57 #include <machine/apm_bios.h>
58 #endif
59 
60 #define DEFAULT_ACTIVE_PERCENT	75
61 #define DEFAULT_IDLE_PERCENT	50
62 #define DEFAULT_POLL_INTERVAL	250	/* Poll interval in milliseconds */
63 
64 typedef enum {
65 	MODE_MIN,
66 	MODE_ADAPTIVE,
67 	MODE_HIADAPTIVE,
68 	MODE_MAX,
69 } modes_t;
70 
71 typedef enum {
72 	SRC_AC,
73 	SRC_BATTERY,
74 	SRC_UNKNOWN,
75 } power_src_t;
76 
77 static const char *modes[] = {
78 	"AC",
79 	"battery",
80 	"unknown"
81 };
82 
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
88 
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);
100 
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;
107 
108 /* Configuration */
109 static int	cpu_running_mark;
110 static int	cpu_idle_mark;
111 static int	poll_ival;
112 static int	vflag;
113 
114 static volatile sig_atomic_t exit_requested;
115 static power_src_t acline_status;
116 typedef enum {
117 	ac_none,
118 	ac_sysctl,
119 	ac_acpi_devd,
120 #ifdef USE_APM
121 	ac_apm,
122 #endif
123 } acline_mode_t;
124 static acline_mode_t acline_mode;
125 static acline_mode_t acline_mode_user = ac_none;
126 #ifdef USE_APM
127 static int	apm_fd = -1;
128 #endif
129 static int	devd_pipe = -1;
130 
131 #define DEVD_RETRY_INTERVAL 60 /* seconds */
132 static struct timeval tried_devd;
133 
134 /*
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.
139  */
140 static int
141 read_usage_times(int *load)
142 {
143 	static long *cp_times = NULL, *cp_times_old = NULL;
144 	static int ncpus = 0;
145 	size_t cp_times_len;
146 	int error, cpu, i, total;
147 
148 	if (cp_times == NULL) {
149 		cp_times_len = 0;
150 		error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
151 		if (error)
152 			return (error);
153 		if ((cp_times = malloc(cp_times_len)) == NULL)
154 			return (errno);
155 		if ((cp_times_old = malloc(cp_times_len)) == NULL) {
156 			free(cp_times);
157 			cp_times = NULL;
158 			return (errno);
159 		}
160 		ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
161 	}
162 
163 	cp_times_len = sizeof(long) * CPUSTATES * ncpus;
164 	error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
165 	if (error)
166 		return (error);
167 
168 	if (load) {
169 		*load = 0;
170 		for (cpu = 0; cpu < ncpus; cpu++) {
171 			total = 0;
172 			for (i = 0; i < CPUSTATES; i++) {
173 			    total += cp_times[cpu * CPUSTATES + i] -
174 				cp_times_old[cpu * CPUSTATES + i];
175 			}
176 			if (total == 0)
177 				continue;
178 			*load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
179 			    cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
180 		}
181 	}
182 
183 	memcpy(cp_times_old, cp_times, cp_times_len);
184 
185 	return (0);
186 }
187 
188 static int
189 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
190 {
191 	char *freqstr, *p, *q;
192 	int i, j;
193 	size_t len = 0;
194 
195 	if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
196 		return (-1);
197 	if ((freqstr = malloc(len)) == NULL)
198 		return (-1);
199 	if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
200 		return (-1);
201 
202 	*numfreqs = 1;
203 	for (p = freqstr; *p != '\0'; p++)
204 		if (*p == ' ')
205 			(*numfreqs)++;
206 
207 	if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
208 		free(freqstr);
209 		return (-1);
210 	}
211 	if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
212 		free(freqstr);
213 		free(*freqs);
214 		return (-1);
215 	}
216 	for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
217 		q = strchr(p, ' ');
218 		if (q != NULL)
219 			*q = '\0';
220 		if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
221 			free(freqstr);
222 			free(*freqs);
223 			free(*power);
224 			return (-1);
225 		}
226 		if (((*freqs)[j] >= minfreq || minfreq == -1) &&
227 		    ((*freqs)[j] <= maxfreq || maxfreq == -1))
228 			j++;
229 		p = q + 1;
230 	}
231 
232 	*numfreqs = j;
233 	if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
234 		free(freqstr);
235 		free(*freqs);
236 		free(*power);
237 		return (-1);
238 	}
239 
240 	free(freqstr);
241 	return (0);
242 }
243 
244 static int
245 get_freq(void)
246 {
247 	size_t len;
248 	int curfreq;
249 
250 	len = sizeof(curfreq);
251 	if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
252 		if (vflag)
253 			warn("error reading current CPU frequency");
254 		curfreq = 0;
255 	}
256 	return (curfreq);
257 }
258 
259 static int
260 set_freq(int freq)
261 {
262 
263 	if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
264 		if (errno != EPERM)
265 			return (-1);
266 	}
267 
268 	return (0);
269 }
270 
271 static int
272 get_freq_id(int freq, int *freqs, int numfreqs)
273 {
274 	int i = 1;
275 
276 	while (i < numfreqs) {
277 		if (freqs[i] < freq)
278 			break;
279 		i++;
280 	}
281 	return (i - 1);
282 }
283 
284 /*
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.
287  */
288 static void
289 acline_init(void)
290 {
291 	int skip_source_check;
292 
293 	acline_mib_len = 4;
294 	acline_status = SRC_UNKNOWN;
295 	skip_source_check = (acline_mode_user == ac_none ||
296 			     acline_mode_user == ac_acpi_devd);
297 
298 	if ((skip_source_check || acline_mode_user == ac_sysctl) &&
299 	    sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
300 		acline_mode = ac_sysctl;
301 		if (vflag)
302 			warnx("using sysctl for AC line status");
303 #ifdef __powerpc__
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;
307 		if (vflag)
308 			warnx("using sysctl for AC line status");
309 #endif
310 #ifdef USE_APM
311 	} else if ((skip_source_check || acline_mode_user == ac_apm) &&
312 		   (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
313 		if (vflag)
314 			warnx("using APM for AC line status");
315 		acline_mode = ac_apm;
316 #endif
317 	} else {
318 		warnx("unable to determine AC line status");
319 		acline_mode = ac_none;
320 	}
321 }
322 
323 static void
324 acline_read(void)
325 {
326 	if (acline_mode == ac_acpi_devd) {
327 		char buf[DEVCTL_MAXBUF], *ptr;
328 		ssize_t rlen;
329 		int notify;
330 
331 		rlen = read(devd_pipe, buf, sizeof(buf));
332 		if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
333 			if (vflag)
334 				warnx("lost devd connection, switching to sysctl");
335 			devd_close();
336 			acline_mode = ac_sysctl;
337 			/* FALLTHROUGH */
338 		}
339 		if (rlen > 0 &&
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", &notify) == 1)
344 			acline_status = (notify ? SRC_AC : SRC_BATTERY);
345 	}
346 	if (acline_mode == ac_sysctl) {
347 		int acline;
348 		size_t len;
349 
350 		len = sizeof(acline);
351 		if (sysctl(acline_mib, acline_mib_len, &acline, &len,
352 		    NULL, 0) == 0)
353 			acline_status = (acline ? SRC_AC : SRC_BATTERY);
354 		else
355 			acline_status = SRC_UNKNOWN;
356 	}
357 #ifdef USE_APM
358 	if (acline_mode == ac_apm) {
359 		struct apm_info info;
360 
361 		if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
362 			acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
363 		} else {
364 			close(apm_fd);
365 			apm_fd = -1;
366 			acline_mode = ac_none;
367 			acline_status = SRC_UNKNOWN;
368 		}
369 	}
370 #endif
371 	/* try to (re)connect to devd */
372 #ifdef USE_APM
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)) {
378 #else
379 	if (acline_mode == ac_sysctl &&
380 	    (acline_mode_user == ac_none ||
381 	     acline_mode_user == ac_acpi_devd)) {
382 #endif
383 		struct timeval now;
384 
385 		gettimeofday(&now, NULL);
386 		if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
387 			if (devd_init() >= 0) {
388 				if (vflag)
389 					warnx("using devd for AC line status");
390 				acline_mode = ac_acpi_devd;
391 			}
392 			tried_devd = now;
393 		}
394 	}
395 }
396 
397 static int
398 devd_init(void)
399 {
400 	struct sockaddr_un devd_addr;
401 
402 	bzero(&devd_addr, sizeof(devd_addr));
403 	if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
404 		if (vflag)
405 			warn("%s(): socket()", __func__);
406 		return (-1);
407 	}
408 
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) {
413 		if (vflag)
414 			warn("%s(): connect()", __func__);
415 		close(devd_pipe);
416 		devd_pipe = -1;
417 		return (-1);
418 	}
419 
420 	return (devd_pipe);
421 }
422 
423 static void
424 devd_close(void)
425 {
426 
427 	close(devd_pipe);
428 	devd_pipe = -1;
429 }
430 
431 static void
432 parse_mode(char *arg, int *mode, int ch)
433 {
434 
435 	if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
436 		*mode = MODE_MIN;
437 	else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
438 		*mode = MODE_MAX;
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;
443 	else
444 		errx(1, "bad option: -%c %s", (char)ch, optarg);
445 }
446 
447 static void
448 parse_acline_mode(char *arg, int ch)
449 {
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;
454 #ifdef USE_APM
455 	else if (strcmp(arg, "apm") == 0)
456 		acline_mode_user = ac_apm;
457 #endif
458 	else
459 		errx(1, "bad option: -%c %s", (char)ch, optarg);
460 }
461 
462 static void
463 handle_sigs(int __unused sig)
464 {
465 
466 	exit_requested = 1;
467 }
468 
469 static void
470 usage(void)
471 {
472 
473 	fprintf(stderr,
474 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
475 	exit(1);
476 }
477 
478 int
479 main(int argc, char * argv[])
480 {
481 	struct timeval timeout;
482 	fd_set fdset;
483 	int nfds;
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;
490 	size_t len;
491 
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;
498 	mjoules_used = 0;
499 	vflag = 0;
500 
501 	/* User must be root to control frequencies. */
502 	if (geteuid() != 0)
503 		errx(1, "must be root to run");
504 
505 	while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:s:v")) != -1)
506 		switch (ch) {
507 		case 'a':
508 			parse_mode(optarg, &mode_ac, ch);
509 			break;
510 		case 'b':
511 			parse_mode(optarg, &mode_battery, ch);
512 			break;
513 		case 's':
514 			parse_acline_mode(optarg, ch);
515 			break;
516 		case 'i':
517 			cpu_idle_mark = atoi(optarg);
518 			if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
519 				warnx("%d is not a valid percent",
520 				    cpu_idle_mark);
521 				usage();
522 			}
523 			break;
524 		case 'm':
525 			minfreq = atoi(optarg);
526 			if (minfreq < 0) {
527 				warnx("%d is not a valid CPU frequency",
528 				    minfreq);
529 				usage();
530 			}
531 			break;
532 		case 'M':
533 			maxfreq = atoi(optarg);
534 			if (maxfreq < 0) {
535 				warnx("%d is not a valid CPU frequency",
536 				    maxfreq);
537 				usage();
538 			}
539 			break;
540 		case 'n':
541 			parse_mode(optarg, &mode_none, ch);
542 			break;
543 		case 'p':
544 			poll_ival = atoi(optarg);
545 			if (poll_ival < 5) {
546 				warnx("poll interval is in units of ms");
547 				usage();
548 			}
549 			break;
550 		case 'P':
551 			pidfile = optarg;
552 			break;
553 		case 'r':
554 			cpu_running_mark = atoi(optarg);
555 			if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
556 				warnx("%d is not a valid percent",
557 				    cpu_running_mark);
558 				usage();
559 			}
560 			break;
561 		case 'v':
562 			vflag = 1;
563 			break;
564 		default:
565 			usage();
566 		}
567 
568 	mode = mode_none;
569 
570 	/* Poll interval is in units of ms. */
571 	poll_ival *= 1000;
572 
573 	/* Look up various sysctl MIBs. */
574 	len = 2;
575 	if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
576 		err(1, "lookup kern.cp_times");
577 	len = 4;
578 	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
579 		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
580 	len = 4;
581 	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
582 		err(1, "lookup freq_levels");
583 
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");
589 	if (numfreqs == 0)
590 		errx(1, "no CPU frequencies in user-specified range");
591 
592 	/* Run in the background unless in verbose mode. */
593 	if (!vflag) {
594 		pid_t otherpid;
595 
596 		pfh = pidfile_open(pidfile, 0600, &otherpid);
597 		if (pfh == NULL) {
598 			if (errno == EEXIST) {
599 				errx(1, "powerd already running, pid: %d",
600 				    otherpid);
601 			}
602 			warn("cannot open pid file");
603 		}
604 		if (daemon(0, 0) != 0) {
605 			warn("cannot enter daemon mode, exiting");
606 			pidfile_remove(pfh);
607 			exit(EXIT_FAILURE);
608 
609 		}
610 		pidfile_write(pfh);
611 	}
612 
613 	/* Decide whether to use ACPI or APM to read the AC line status. */
614 	acline_init();
615 
616 	/*
617 	 * Exit cleanly on signals.
618 	 */
619 	signal(SIGINT, handle_sigs);
620 	signal(SIGTERM, handle_sigs);
621 
622 	freq = initfreq = curfreq = get_freq();
623 	i = get_freq_id(curfreq, freqs, numfreqs);
624 	if (freq < 1)
625 		freq = 1;
626 
627 	/*
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.
630 	 */
631 	acline_read();
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) {
643 			if (vflag)
644 				warn("error reading current CPU frequency");
645 		}
646 		if (curfreq < freqs[numfreqs - 1]) {
647 			if (vflag) {
648 				printf("CPU frequency is below user-defined "
649 				    "minimum; changing frequency to %d "
650 				    "MHz\n", freqs[numfreqs - 1]);
651 			}
652 			if (set_freq(freqs[numfreqs - 1]) != 0) {
653 				warn("error setting CPU freq %d",
654 				    freqs[numfreqs - 1]);
655 			}
656 		} else if (curfreq > freqs[0]) {
657 			if (vflag) {
658 				printf("CPU frequency is above user-defined "
659 				    "maximum; changing frequency to %d "
660 				    "MHz\n", freqs[0]);
661 			}
662 			if (set_freq(freqs[0]) != 0) {
663 				warn("error setting CPU freq %d",
664 				    freqs[0]);
665 			}
666 		}
667 	}
668 
669 	idle = 0;
670 	/* Main loop. */
671 	for (;;) {
672 		FD_ZERO(&fdset);
673 		if (devd_pipe >= 0) {
674 			FD_SET(devd_pipe, &fdset);
675 			nfds = devd_pipe + 1;
676 		} else {
677 			nfds = 0;
678 		}
679 		if (mode == MODE_HIADAPTIVE || idle < 120)
680 			to = poll_ival;
681 		else if (idle < 360)
682 			to = poll_ival * 2;
683 		else
684 			to = poll_ival * 4;
685 		timeout.tv_sec = to / 1000000;
686 		timeout.tv_usec = to % 1000000;
687 		select(nfds, &fdset, NULL, &fdset, &timeout);
688 
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);
695 			break;
696 		}
697 
698 		/* Read the current AC status and record the mode. */
699 		acline_read();
700 		switch (acline_status) {
701 		case SRC_AC:
702 			mode = mode_ac;
703 			break;
704 		case SRC_BATTERY:
705 			mode = mode_battery;
706 			break;
707 		case SRC_UNKNOWN:
708 			mode = mode_none;
709 			break;
710 		default:
711 			errx(1, "invalid AC line status %d", acline_status);
712 		}
713 
714 		/* Read the current frequency. */
715 		if (idle % 32 == 0) {
716 			if ((curfreq = get_freq()) == 0)
717 				continue;
718 			i = get_freq_id(curfreq, freqs, numfreqs);
719 		}
720 		idle++;
721 		if (vflag) {
722 			/* Keep a sum of all power actually used. */
723 			if (mwatts[i] != -1)
724 				mjoules_used +=
725 				    (mwatts[i] * (poll_ival / 1000)) / 1000;
726 		}
727 
728 		/* Always switch to the lowest frequency in min mode. */
729 		if (mode == MODE_MIN) {
730 			freq = freqs[numfreqs - 1];
731 			if (curfreq != freq) {
732 				if (vflag) {
733 					printf("now operating on %s power; "
734 					    "changing frequency to %d MHz\n",
735 					    modes[acline_status], freq);
736 				}
737 				idle = 0;
738 				if (set_freq(freq) != 0) {
739 					warn("error setting CPU freq %d",
740 					    freq);
741 					continue;
742 				}
743 			}
744 			continue;
745 		}
746 
747 		/* Always switch to the highest frequency in max mode. */
748 		if (mode == MODE_MAX) {
749 			freq = freqs[0];
750 			if (curfreq != freq) {
751 				if (vflag) {
752 					printf("now operating on %s power; "
753 					    "changing frequency to %d MHz\n",
754 					    modes[acline_status], freq);
755 				}
756 				idle = 0;
757 				if (set_freq(freq) != 0) {
758 					warn("error setting CPU freq %d",
759 					    freq);
760 					continue;
761 				}
762 			}
763 			continue;
764 		}
765 
766 		/* Adaptive mode; get the current CPU usage times. */
767 		if (read_usage_times(&load)) {
768 			if (vflag)
769 				warn("read_usage_times() failed");
770 			continue;
771 		}
772 
773 		if (mode == MODE_ADAPTIVE) {
774 			if (load > cpu_running_mark) {
775 				if (load > 95 || load > cpu_running_mark * 2)
776 					freq *= 2;
777 				else
778 					freq = freq * load / cpu_running_mark;
779 				if (freq > freqs[0])
780 					freq = freqs[0];
781 			} else if (load < cpu_idle_mark &&
782 			    curfreq * load < freqs[get_freq_id(
783 			    freq * 7 / 8, freqs, numfreqs)] *
784 			    cpu_running_mark) {
785 				freq = freq * 7 / 8;
786 				if (freq < freqs[numfreqs - 1])
787 					freq = freqs[numfreqs - 1];
788 			}
789 		} else { /* MODE_HIADAPTIVE */
790 			if (load > cpu_running_mark / 2) {
791 				if (load > 95 || load > cpu_running_mark)
792 					freq *= 4;
793 				else
794 					freq = freq * load * 2 / cpu_running_mark;
795 				if (freq > freqs[0] * 2)
796 					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];
804 			}
805 		}
806 		if (vflag) {
807 		    printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
808 			load, curfreq, i, freq);
809 		}
810 		j = get_freq_id(freq, freqs, numfreqs);
811 		if (i != j) {
812 			if (vflag) {
813 				printf("changing clock"
814 				    " speed from %d MHz to %d MHz\n",
815 				    freqs[i], freqs[j]);
816 			}
817 			idle = 0;
818 			if (set_freq(freqs[j]))
819 				warn("error setting CPU frequency %d",
820 				    freqs[j]);
821 		}
822 	}
823 	if (set_freq(initfreq))
824 		warn("error setting CPU frequency %d", initfreq);
825 	free(freqs);
826 	free(mwatts);
827 	devd_close();
828 	if (!vflag)
829 		pidfile_remove(pfh);
830 
831 	exit(0);
832 }
833