xref: /freebsd/usr.sbin/powerd/powerd.c (revision d8ffc21c5ca6f7d4f2d9a65dc6308699af0b6a01)
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 		free(freqstr);
201 		return (-1);
202 	}
203 
204 	*numfreqs = 1;
205 	for (p = freqstr; *p != '\0'; p++)
206 		if (*p == ' ')
207 			(*numfreqs)++;
208 
209 	if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
210 		free(freqstr);
211 		return (-1);
212 	}
213 	if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
214 		free(freqstr);
215 		free(*freqs);
216 		return (-1);
217 	}
218 	for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
219 		q = strchr(p, ' ');
220 		if (q != NULL)
221 			*q = '\0';
222 		if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
223 			free(freqstr);
224 			free(*freqs);
225 			free(*power);
226 			return (-1);
227 		}
228 		if (((*freqs)[j] >= minfreq || minfreq == -1) &&
229 		    ((*freqs)[j] <= maxfreq || maxfreq == -1))
230 			j++;
231 		p = q + 1;
232 	}
233 
234 	*numfreqs = j;
235 	if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
236 		free(freqstr);
237 		free(*freqs);
238 		free(*power);
239 		return (-1);
240 	}
241 
242 	free(freqstr);
243 	return (0);
244 }
245 
246 static int
247 get_freq(void)
248 {
249 	size_t len;
250 	int curfreq;
251 
252 	len = sizeof(curfreq);
253 	if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
254 		if (vflag)
255 			warn("error reading current CPU frequency");
256 		curfreq = 0;
257 	}
258 	return (curfreq);
259 }
260 
261 static int
262 set_freq(int freq)
263 {
264 
265 	if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
266 		if (errno != EPERM)
267 			return (-1);
268 	}
269 
270 	return (0);
271 }
272 
273 static int
274 get_freq_id(int freq, int *freqs, int numfreqs)
275 {
276 	int i = 1;
277 
278 	while (i < numfreqs) {
279 		if (freqs[i] < freq)
280 			break;
281 		i++;
282 	}
283 	return (i - 1);
284 }
285 
286 /*
287  * Try to use ACPI to find the AC line status.  If this fails, fall back
288  * to APM.  If nothing succeeds, we'll just run in default mode.
289  */
290 static void
291 acline_init(void)
292 {
293 	int skip_source_check;
294 
295 	acline_mib_len = 4;
296 	acline_status = SRC_UNKNOWN;
297 	skip_source_check = (acline_mode_user == ac_none ||
298 			     acline_mode_user == ac_acpi_devd);
299 
300 	if ((skip_source_check || acline_mode_user == ac_sysctl) &&
301 	    sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
302 		acline_mode = ac_sysctl;
303 		if (vflag)
304 			warnx("using sysctl for AC line status");
305 #ifdef __powerpc__
306 	} else if ((skip_source_check || acline_mode_user == ac_sysctl) &&
307 		   sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
308 		acline_mode = ac_sysctl;
309 		if (vflag)
310 			warnx("using sysctl for AC line status");
311 #endif
312 #ifdef USE_APM
313 	} else if ((skip_source_check || acline_mode_user == ac_apm) &&
314 		   (apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
315 		if (vflag)
316 			warnx("using APM for AC line status");
317 		acline_mode = ac_apm;
318 #endif
319 	} else {
320 		warnx("unable to determine AC line status");
321 		acline_mode = ac_none;
322 	}
323 }
324 
325 static void
326 acline_read(void)
327 {
328 	if (acline_mode == ac_acpi_devd) {
329 		char buf[DEVCTL_MAXBUF], *ptr;
330 		ssize_t rlen;
331 		int notify;
332 
333 		rlen = read(devd_pipe, buf, sizeof(buf));
334 		if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
335 			if (vflag)
336 				warnx("lost devd connection, switching to sysctl");
337 			devd_close();
338 			acline_mode = ac_sysctl;
339 			/* FALLTHROUGH */
340 		}
341 		if (rlen > 0 &&
342 		    (ptr = strstr(buf, "system=ACPI")) != NULL &&
343 		    (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
344 		    (ptr = strstr(ptr, "notify=")) != NULL &&
345 		    sscanf(ptr, "notify=%x", &notify) == 1)
346 			acline_status = (notify ? SRC_AC : SRC_BATTERY);
347 	}
348 	if (acline_mode == ac_sysctl) {
349 		int acline;
350 		size_t len;
351 
352 		len = sizeof(acline);
353 		if (sysctl(acline_mib, acline_mib_len, &acline, &len,
354 		    NULL, 0) == 0)
355 			acline_status = (acline ? SRC_AC : SRC_BATTERY);
356 		else
357 			acline_status = SRC_UNKNOWN;
358 	}
359 #ifdef USE_APM
360 	if (acline_mode == ac_apm) {
361 		struct apm_info info;
362 
363 		if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
364 			acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
365 		} else {
366 			close(apm_fd);
367 			apm_fd = -1;
368 			acline_mode = ac_none;
369 			acline_status = SRC_UNKNOWN;
370 		}
371 	}
372 #endif
373 	/* try to (re)connect to devd */
374 #ifdef USE_APM
375 	if ((acline_mode == ac_sysctl &&
376 	    (acline_mode_user == ac_none ||
377 	     acline_mode_user == ac_acpi_devd)) ||
378 	    (acline_mode == ac_apm &&
379 	     acline_mode_user == ac_acpi_devd)) {
380 #else
381 	if (acline_mode == ac_sysctl &&
382 	    (acline_mode_user == ac_none ||
383 	     acline_mode_user == ac_acpi_devd)) {
384 #endif
385 		struct timeval now;
386 
387 		gettimeofday(&now, NULL);
388 		if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
389 			if (devd_init() >= 0) {
390 				if (vflag)
391 					warnx("using devd for AC line status");
392 				acline_mode = ac_acpi_devd;
393 			}
394 			tried_devd = now;
395 		}
396 	}
397 }
398 
399 static int
400 devd_init(void)
401 {
402 	struct sockaddr_un devd_addr;
403 
404 	bzero(&devd_addr, sizeof(devd_addr));
405 	if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM|SOCK_NONBLOCK, 0)) < 0) {
406 		if (vflag)
407 			warn("%s(): socket()", __func__);
408 		return (-1);
409 	}
410 
411 	devd_addr.sun_family = PF_LOCAL;
412 	strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
413 	if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
414 	    sizeof(devd_addr)) == -1) {
415 		if (vflag)
416 			warn("%s(): connect()", __func__);
417 		close(devd_pipe);
418 		devd_pipe = -1;
419 		return (-1);
420 	}
421 
422 	return (devd_pipe);
423 }
424 
425 static void
426 devd_close(void)
427 {
428 
429 	close(devd_pipe);
430 	devd_pipe = -1;
431 }
432 
433 static void
434 parse_mode(char *arg, int *mode, int ch)
435 {
436 
437 	if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
438 		*mode = MODE_MIN;
439 	else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
440 		*mode = MODE_MAX;
441 	else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
442 		*mode = MODE_ADAPTIVE;
443 	else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
444 		*mode = MODE_HIADAPTIVE;
445 	else
446 		errx(1, "bad option: -%c %s", (char)ch, optarg);
447 }
448 
449 static void
450 parse_acline_mode(char *arg, int ch)
451 {
452 	if (strcmp(arg, "sysctl") == 0)
453 		acline_mode_user = ac_sysctl;
454 	else if (strcmp(arg, "devd") == 0)
455 		acline_mode_user = ac_acpi_devd;
456 #ifdef USE_APM
457 	else if (strcmp(arg, "apm") == 0)
458 		acline_mode_user = ac_apm;
459 #endif
460 	else
461 		errx(1, "bad option: -%c %s", (char)ch, optarg);
462 }
463 
464 static void
465 handle_sigs(int __unused sig)
466 {
467 
468 	exit_requested = 1;
469 }
470 
471 static void
472 usage(void)
473 {
474 
475 	fprintf(stderr,
476 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-s source] [-P pidfile]\n");
477 	exit(1);
478 }
479 
480 int
481 main(int argc, char * argv[])
482 {
483 	struct timeval timeout;
484 	fd_set fdset;
485 	int nfds;
486 	struct pidfh *pfh = NULL;
487 	const char *pidfile = NULL;
488 	int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
489 	int minfreq = -1, maxfreq = -1;
490 	int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
491 	uint64_t mjoules_used;
492 	size_t len;
493 
494 	/* Default mode for all AC states is adaptive. */
495 	mode_ac = mode_none = MODE_HIADAPTIVE;
496 	mode_battery = MODE_ADAPTIVE;
497 	cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
498 	cpu_idle_mark = DEFAULT_IDLE_PERCENT;
499 	poll_ival = DEFAULT_POLL_INTERVAL;
500 	mjoules_used = 0;
501 	vflag = 0;
502 
503 	/* User must be root to control frequencies. */
504 	if (geteuid() != 0)
505 		errx(1, "must be root to run");
506 
507 	while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:s:v")) != -1)
508 		switch (ch) {
509 		case 'a':
510 			parse_mode(optarg, &mode_ac, ch);
511 			break;
512 		case 'b':
513 			parse_mode(optarg, &mode_battery, ch);
514 			break;
515 		case 's':
516 			parse_acline_mode(optarg, ch);
517 			break;
518 		case 'i':
519 			cpu_idle_mark = atoi(optarg);
520 			if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
521 				warnx("%d is not a valid percent",
522 				    cpu_idle_mark);
523 				usage();
524 			}
525 			break;
526 		case 'm':
527 			minfreq = atoi(optarg);
528 			if (minfreq < 0) {
529 				warnx("%d is not a valid CPU frequency",
530 				    minfreq);
531 				usage();
532 			}
533 			break;
534 		case 'M':
535 			maxfreq = atoi(optarg);
536 			if (maxfreq < 0) {
537 				warnx("%d is not a valid CPU frequency",
538 				    maxfreq);
539 				usage();
540 			}
541 			break;
542 		case 'n':
543 			parse_mode(optarg, &mode_none, ch);
544 			break;
545 		case 'p':
546 			poll_ival = atoi(optarg);
547 			if (poll_ival < 5) {
548 				warnx("poll interval is in units of ms");
549 				usage();
550 			}
551 			break;
552 		case 'P':
553 			pidfile = optarg;
554 			break;
555 		case 'r':
556 			cpu_running_mark = atoi(optarg);
557 			if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
558 				warnx("%d is not a valid percent",
559 				    cpu_running_mark);
560 				usage();
561 			}
562 			break;
563 		case 'v':
564 			vflag = 1;
565 			break;
566 		default:
567 			usage();
568 		}
569 
570 	mode = mode_none;
571 
572 	/* Poll interval is in units of ms. */
573 	poll_ival *= 1000;
574 
575 	/* Look up various sysctl MIBs. */
576 	len = 2;
577 	if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
578 		err(1, "lookup kern.cp_times");
579 	len = 4;
580 	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
581 		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
582 	len = 4;
583 	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
584 		err(1, "lookup freq_levels");
585 
586 	/* Check if we can read the load and supported freqs. */
587 	if (read_usage_times(NULL))
588 		err(1, "read_usage_times");
589 	if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
590 		err(1, "error reading supported CPU frequencies");
591 	if (numfreqs == 0)
592 		errx(1, "no CPU frequencies in user-specified range");
593 
594 	/* Run in the background unless in verbose mode. */
595 	if (!vflag) {
596 		pid_t otherpid;
597 
598 		pfh = pidfile_open(pidfile, 0600, &otherpid);
599 		if (pfh == NULL) {
600 			if (errno == EEXIST) {
601 				errx(1, "powerd already running, pid: %d",
602 				    otherpid);
603 			}
604 			warn("cannot open pid file");
605 		}
606 		if (daemon(0, 0) != 0) {
607 			warn("cannot enter daemon mode, exiting");
608 			pidfile_remove(pfh);
609 			exit(EXIT_FAILURE);
610 
611 		}
612 		pidfile_write(pfh);
613 	}
614 
615 	/* Decide whether to use ACPI or APM to read the AC line status. */
616 	acline_init();
617 
618 	/*
619 	 * Exit cleanly on signals.
620 	 */
621 	signal(SIGINT, handle_sigs);
622 	signal(SIGTERM, handle_sigs);
623 
624 	freq = initfreq = curfreq = get_freq();
625 	i = get_freq_id(curfreq, freqs, numfreqs);
626 	if (freq < 1)
627 		freq = 1;
628 
629 	/*
630 	 * If we are in adaptive mode and the current frequency is outside the
631 	 * user-defined range, adjust it to be within the user-defined range.
632 	 */
633 	acline_read();
634 	if (acline_status > SRC_UNKNOWN)
635 		errx(1, "invalid AC line status %d", acline_status);
636 	if ((acline_status == SRC_AC &&
637 	    (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
638 	    (acline_status == SRC_BATTERY &&
639 	    (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
640 	    (acline_status == SRC_UNKNOWN &&
641 	    (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
642 		/* Read the current frequency. */
643 		len = sizeof(curfreq);
644 		if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
645 			if (vflag)
646 				warn("error reading current CPU frequency");
647 		}
648 		if (curfreq < freqs[numfreqs - 1]) {
649 			if (vflag) {
650 				printf("CPU frequency is below user-defined "
651 				    "minimum; changing frequency to %d "
652 				    "MHz\n", freqs[numfreqs - 1]);
653 			}
654 			if (set_freq(freqs[numfreqs - 1]) != 0) {
655 				warn("error setting CPU freq %d",
656 				    freqs[numfreqs - 1]);
657 			}
658 		} else if (curfreq > freqs[0]) {
659 			if (vflag) {
660 				printf("CPU frequency is above user-defined "
661 				    "maximum; changing frequency to %d "
662 				    "MHz\n", freqs[0]);
663 			}
664 			if (set_freq(freqs[0]) != 0) {
665 				warn("error setting CPU freq %d",
666 				    freqs[0]);
667 			}
668 		}
669 	}
670 
671 	idle = 0;
672 	/* Main loop. */
673 	for (;;) {
674 		FD_ZERO(&fdset);
675 		if (devd_pipe >= 0) {
676 			FD_SET(devd_pipe, &fdset);
677 			nfds = devd_pipe + 1;
678 		} else {
679 			nfds = 0;
680 		}
681 		if (mode == MODE_HIADAPTIVE || idle < 120)
682 			to = poll_ival;
683 		else if (idle < 360)
684 			to = poll_ival * 2;
685 		else
686 			to = poll_ival * 4;
687 		timeout.tv_sec = to / 1000000;
688 		timeout.tv_usec = to % 1000000;
689 		select(nfds, &fdset, NULL, &fdset, &timeout);
690 
691 		/* If the user requested we quit, print some statistics. */
692 		if (exit_requested) {
693 			if (vflag && mjoules_used != 0)
694 				printf("total joules used: %u.%03u\n",
695 				    (u_int)(mjoules_used / 1000),
696 				    (int)mjoules_used % 1000);
697 			break;
698 		}
699 
700 		/* Read the current AC status and record the mode. */
701 		acline_read();
702 		switch (acline_status) {
703 		case SRC_AC:
704 			mode = mode_ac;
705 			break;
706 		case SRC_BATTERY:
707 			mode = mode_battery;
708 			break;
709 		case SRC_UNKNOWN:
710 			mode = mode_none;
711 			break;
712 		default:
713 			errx(1, "invalid AC line status %d", acline_status);
714 		}
715 
716 		/* Read the current frequency. */
717 		if (idle % 32 == 0) {
718 			if ((curfreq = get_freq()) == 0)
719 				continue;
720 			i = get_freq_id(curfreq, freqs, numfreqs);
721 		}
722 		idle++;
723 		if (vflag) {
724 			/* Keep a sum of all power actually used. */
725 			if (mwatts[i] != -1)
726 				mjoules_used +=
727 				    (mwatts[i] * (poll_ival / 1000)) / 1000;
728 		}
729 
730 		/* Always switch to the lowest frequency in min mode. */
731 		if (mode == MODE_MIN) {
732 			freq = freqs[numfreqs - 1];
733 			if (curfreq != freq) {
734 				if (vflag) {
735 					printf("now operating on %s power; "
736 					    "changing frequency to %d MHz\n",
737 					    modes[acline_status], freq);
738 				}
739 				idle = 0;
740 				if (set_freq(freq) != 0) {
741 					warn("error setting CPU freq %d",
742 					    freq);
743 					continue;
744 				}
745 			}
746 			continue;
747 		}
748 
749 		/* Always switch to the highest frequency in max mode. */
750 		if (mode == MODE_MAX) {
751 			freq = freqs[0];
752 			if (curfreq != freq) {
753 				if (vflag) {
754 					printf("now operating on %s power; "
755 					    "changing frequency to %d MHz\n",
756 					    modes[acline_status], freq);
757 				}
758 				idle = 0;
759 				if (set_freq(freq) != 0) {
760 					warn("error setting CPU freq %d",
761 					    freq);
762 					continue;
763 				}
764 			}
765 			continue;
766 		}
767 
768 		/* Adaptive mode; get the current CPU usage times. */
769 		if (read_usage_times(&load)) {
770 			if (vflag)
771 				warn("read_usage_times() failed");
772 			continue;
773 		}
774 
775 		if (mode == MODE_ADAPTIVE) {
776 			if (load > cpu_running_mark) {
777 				if (load > 95 || load > cpu_running_mark * 2)
778 					freq *= 2;
779 				else
780 					freq = freq * load / cpu_running_mark;
781 				if (freq > freqs[0])
782 					freq = freqs[0];
783 			} else if (load < cpu_idle_mark &&
784 			    curfreq * load < freqs[get_freq_id(
785 			    freq * 7 / 8, freqs, numfreqs)] *
786 			    cpu_running_mark) {
787 				freq = freq * 7 / 8;
788 				if (freq < freqs[numfreqs - 1])
789 					freq = freqs[numfreqs - 1];
790 			}
791 		} else { /* MODE_HIADAPTIVE */
792 			if (load > cpu_running_mark / 2) {
793 				if (load > 95 || load > cpu_running_mark)
794 					freq *= 4;
795 				else
796 					freq = freq * load * 2 / cpu_running_mark;
797 				if (freq > freqs[0] * 2)
798 					freq = freqs[0] * 2;
799 			} else if (load < cpu_idle_mark / 2 &&
800 			    curfreq * load < freqs[get_freq_id(
801 			    freq * 31 / 32, freqs, numfreqs)] *
802 			    cpu_running_mark / 2) {
803 				freq = freq * 31 / 32;
804 				if (freq < freqs[numfreqs - 1])
805 					freq = freqs[numfreqs - 1];
806 			}
807 		}
808 		if (vflag) {
809 		    printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
810 			load, curfreq, i, freq);
811 		}
812 		j = get_freq_id(freq, freqs, numfreqs);
813 		if (i != j) {
814 			if (vflag) {
815 				printf("changing clock"
816 				    " speed from %d MHz to %d MHz\n",
817 				    freqs[i], freqs[j]);
818 			}
819 			idle = 0;
820 			if (set_freq(freqs[j]))
821 				warn("error setting CPU frequency %d",
822 				    freqs[j]);
823 		}
824 	}
825 	if (set_freq(initfreq))
826 		warn("error setting CPU frequency %d", initfreq);
827 	free(freqs);
828 	free(mwatts);
829 	devd_close();
830 	if (!vflag)
831 		pidfile_remove(pfh);
832 
833 	exit(0);
834 }
835