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