]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - usr.sbin/powerd/powerd.c
MFC r289577:
[FreeBSD/stable/9.git] / usr.sbin / powerd / powerd.c
1 /*-
2  * Copyright (c) 2004 Colin Percival
3  * Copyright (c) 2005 Nate Lawson
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted providing that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
23  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
24  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25  * POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30
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 <unistd.h>
48
49 #ifdef __i386__
50 #define USE_APM
51 #endif
52
53 #ifdef USE_APM
54 #include <machine/apm_bios.h>
55 #endif
56
57 #define DEFAULT_ACTIVE_PERCENT  75
58 #define DEFAULT_IDLE_PERCENT    50
59 #define DEFAULT_POLL_INTERVAL   250     /* Poll interval in milliseconds */
60
61 typedef enum {
62         MODE_MIN,
63         MODE_ADAPTIVE,
64         MODE_HIADAPTIVE,
65         MODE_MAX,
66 } modes_t;
67
68 typedef enum {
69         SRC_AC,
70         SRC_BATTERY,
71         SRC_UNKNOWN,
72 } power_src_t;
73
74 const char *modes[] = {
75         "AC",
76         "battery",
77         "unknown"
78 };
79
80 #define ACPIAC          "hw.acpi.acline"
81 #define PMUAC           "dev.pmu.0.acline"
82 #define APMDEV          "/dev/apm"
83 #define DEVDPIPE        "/var/run/devd.pipe"
84 #define DEVCTL_MAXBUF   1024
85
86 static int      read_usage_times(int *load);
87 static int      read_freqs(int *numfreqs, int **freqs, int **power,
88                     int minfreq, int maxfreq);
89 static int      set_freq(int freq);
90 static void     acline_init(void);
91 static void     acline_read(void);
92 static int      devd_init(void);
93 static void     devd_close(void);
94 static void     handle_sigs(int sig);
95 static void     parse_mode(char *arg, int *mode, int ch);
96 static void     usage(void);
97
98 /* Sysctl data structures. */
99 static int      cp_times_mib[2];
100 static int      freq_mib[4];
101 static int      levels_mib[4];
102 static int      acline_mib[4];
103 static size_t   acline_mib_len;
104
105 /* Configuration */
106 static int      cpu_running_mark;
107 static int      cpu_idle_mark;
108 static int      poll_ival;
109 static int      vflag;
110
111 static volatile sig_atomic_t exit_requested;
112 static power_src_t acline_status;
113 static enum {
114         ac_none,
115         ac_sysctl,
116         ac_acpi_devd,
117 #ifdef USE_APM
118         ac_apm,
119 #endif
120 } acline_mode;
121 #ifdef USE_APM
122 static int      apm_fd = -1;
123 #endif
124 static int      devd_pipe = -1;
125
126 #define DEVD_RETRY_INTERVAL 60 /* seconds */
127 static struct timeval tried_devd;
128
129 /*
130  * This function returns summary load of all CPUs.  It was made so
131  * intentionally to not reduce performance in scenarios when several
132  * threads are processing requests as a pipeline -- running one at
133  * a time on different CPUs and waiting for each other.
134  */
135 static int
136 read_usage_times(int *load)
137 {
138         static long *cp_times = NULL, *cp_times_old = NULL;
139         static int ncpus = 0;
140         size_t cp_times_len;
141         int error, cpu, i, total;
142
143         if (cp_times == NULL) {
144                 cp_times_len = 0;
145                 error = sysctl(cp_times_mib, 2, NULL, &cp_times_len, NULL, 0);
146                 if (error)
147                         return (error);
148                 if ((cp_times = malloc(cp_times_len)) == NULL)
149                         return (errno);
150                 if ((cp_times_old = malloc(cp_times_len)) == NULL) {
151                         free(cp_times);
152                         cp_times = NULL;
153                         return (errno);
154                 }
155                 ncpus = cp_times_len / (sizeof(long) * CPUSTATES);
156         }
157
158         cp_times_len = sizeof(long) * CPUSTATES * ncpus;
159         error = sysctl(cp_times_mib, 2, cp_times, &cp_times_len, NULL, 0);
160         if (error)
161                 return (error);
162
163         if (load) {
164                 *load = 0;
165                 for (cpu = 0; cpu < ncpus; cpu++) {
166                         total = 0;
167                         for (i = 0; i < CPUSTATES; i++) {
168                             total += cp_times[cpu * CPUSTATES + i] -
169                                 cp_times_old[cpu * CPUSTATES + i];
170                         }
171                         if (total == 0)
172                                 continue;
173                         *load += 100 - (cp_times[cpu * CPUSTATES + CP_IDLE] -
174                             cp_times_old[cpu * CPUSTATES + CP_IDLE]) * 100 / total;
175                 }
176         }
177
178         memcpy(cp_times_old, cp_times, cp_times_len);
179
180         return (0);
181 }
182
183 static int
184 read_freqs(int *numfreqs, int **freqs, int **power, int minfreq, int maxfreq)
185 {
186         char *freqstr, *p, *q;
187         int i, j;
188         size_t len = 0;
189
190         if (sysctl(levels_mib, 4, NULL, &len, NULL, 0))
191                 return (-1);
192         if ((freqstr = malloc(len)) == NULL)
193                 return (-1);
194         if (sysctl(levels_mib, 4, freqstr, &len, NULL, 0))
195                 return (-1);
196
197         *numfreqs = 1;
198         for (p = freqstr; *p != '\0'; p++)
199                 if (*p == ' ')
200                         (*numfreqs)++;
201
202         if ((*freqs = malloc(*numfreqs * sizeof(int))) == NULL) {
203                 free(freqstr);
204                 return (-1);
205         }
206         if ((*power = malloc(*numfreqs * sizeof(int))) == NULL) {
207                 free(freqstr);
208                 free(*freqs);
209                 return (-1);
210         }
211         for (i = 0, j = 0, p = freqstr; i < *numfreqs; i++) {
212                 q = strchr(p, ' ');
213                 if (q != NULL)
214                         *q = '\0';
215                 if (sscanf(p, "%d/%d", &(*freqs)[j], &(*power)[i]) != 2) {
216                         free(freqstr);
217                         free(*freqs);
218                         free(*power);
219                         return (-1);
220                 }
221                 if (((*freqs)[j] >= minfreq || minfreq == -1) &&
222                     ((*freqs)[j] <= maxfreq || maxfreq == -1))
223                         j++;
224                 p = q + 1;
225         }
226
227         *numfreqs = j;
228         if ((*freqs = realloc(*freqs, *numfreqs * sizeof(int))) == NULL) {
229                 free(freqstr);
230                 free(*freqs);
231                 free(*power);
232                 return (-1);
233         }
234
235         free(freqstr);
236         return (0);
237 }
238
239 static int
240 get_freq(void)
241 {
242         size_t len;
243         int curfreq;
244
245         len = sizeof(curfreq);
246         if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
247                 if (vflag)
248                         warn("error reading current CPU frequency");
249                 curfreq = 0;
250         }
251         return (curfreq);
252 }
253
254 static int
255 set_freq(int freq)
256 {
257
258         if (sysctl(freq_mib, 4, NULL, NULL, &freq, sizeof(freq))) {
259                 if (errno != EPERM)
260                         return (-1);
261         }
262
263         return (0);
264 }
265
266 static int
267 get_freq_id(int freq, int *freqs, int numfreqs)
268 {
269         int i = 1;
270
271         while (i < numfreqs) {
272                 if (freqs[i] < freq)
273                         break;
274                 i++;
275         }
276         return (i - 1);
277 }
278
279 /*
280  * Try to use ACPI to find the AC line status.  If this fails, fall back
281  * to APM.  If nothing succeeds, we'll just run in default mode.
282  */
283 static void
284 acline_init(void)
285 {
286         acline_mib_len = 4;
287         acline_status = SRC_UNKNOWN;
288
289         if (sysctlnametomib(ACPIAC, acline_mib, &acline_mib_len) == 0) {
290                 acline_mode = ac_sysctl;
291                 if (vflag)
292                         warnx("using sysctl for AC line status");
293 #if __powerpc__
294         } else if (sysctlnametomib(PMUAC, acline_mib, &acline_mib_len) == 0) {
295                 acline_mode = ac_sysctl;
296                 if (vflag)
297                         warnx("using sysctl for AC line status");
298 #endif
299 #ifdef USE_APM
300         } else if ((apm_fd = open(APMDEV, O_RDONLY)) >= 0) {
301                 if (vflag)
302                         warnx("using APM for AC line status");
303                 acline_mode = ac_apm;
304 #endif
305         } else {
306                 warnx("unable to determine AC line status");
307                 acline_mode = ac_none;
308         }
309 }
310
311 static void
312 acline_read(void)
313 {
314         if (acline_mode == ac_acpi_devd) {
315                 char buf[DEVCTL_MAXBUF], *ptr;
316                 ssize_t rlen;
317                 int notify;
318
319                 rlen = read(devd_pipe, buf, sizeof(buf));
320                 if (rlen == 0 || (rlen < 0 && errno != EWOULDBLOCK)) {
321                         if (vflag)
322                                 warnx("lost devd connection, switching to sysctl");
323                         devd_close();
324                         acline_mode = ac_sysctl;
325                         /* FALLTHROUGH */
326                 }
327                 if (rlen > 0 &&
328                     (ptr = strstr(buf, "system=ACPI")) != NULL &&
329                     (ptr = strstr(ptr, "subsystem=ACAD")) != NULL &&
330                     (ptr = strstr(ptr, "notify=")) != NULL &&
331                     sscanf(ptr, "notify=%x", &notify) == 1)
332                         acline_status = (notify ? SRC_AC : SRC_BATTERY);
333         }
334         if (acline_mode == ac_sysctl) {
335                 int acline;
336                 size_t len;
337
338                 len = sizeof(acline);
339                 if (sysctl(acline_mib, acline_mib_len, &acline, &len,
340                     NULL, 0) == 0)
341                         acline_status = (acline ? SRC_AC : SRC_BATTERY);
342                 else
343                         acline_status = SRC_UNKNOWN;
344         }
345 #ifdef USE_APM
346         if (acline_mode == ac_apm) {
347                 struct apm_info info;
348
349                 if (ioctl(apm_fd, APMIO_GETINFO, &info) == 0) {
350                         acline_status = (info.ai_acline ? SRC_AC : SRC_BATTERY);
351                 } else {
352                         close(apm_fd);
353                         apm_fd = -1;
354                         acline_mode = ac_none;
355                         acline_status = SRC_UNKNOWN;
356                 }
357         }
358 #endif
359         /* try to (re)connect to devd */
360         if (acline_mode == ac_sysctl) {
361                 struct timeval now;
362
363                 gettimeofday(&now, NULL);
364                 if (now.tv_sec > tried_devd.tv_sec + DEVD_RETRY_INTERVAL) {
365                         if (devd_init() >= 0) {
366                                 if (vflag)
367                                         warnx("using devd for AC line status");
368                                 acline_mode = ac_acpi_devd;
369                         }
370                         tried_devd = now;
371                 }
372         }
373 }
374
375 static int
376 devd_init(void)
377 {
378         struct sockaddr_un devd_addr;
379
380         bzero(&devd_addr, sizeof(devd_addr));
381         if ((devd_pipe = socket(PF_LOCAL, SOCK_STREAM, 0)) < 0) {
382                 if (vflag)
383                         warn("%s(): socket()", __func__);
384                 return (-1);
385         }
386
387         devd_addr.sun_family = PF_LOCAL;
388         strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
389         if (connect(devd_pipe, (struct sockaddr *)&devd_addr,
390             sizeof(devd_addr)) == -1) {
391                 if (vflag)
392                         warn("%s(): connect()", __func__);
393                 close(devd_pipe);
394                 devd_pipe = -1;
395                 return (-1);
396         }
397
398         if (fcntl(devd_pipe, F_SETFL, O_NONBLOCK) == -1) {
399                 if (vflag)
400                         warn("%s(): fcntl()", __func__);
401                 close(devd_pipe);
402                 return (-1);
403         }
404
405         return (devd_pipe);
406 }
407
408 static void
409 devd_close(void)
410 {
411
412         close(devd_pipe);
413         devd_pipe = -1;
414 }
415
416 static void
417 parse_mode(char *arg, int *mode, int ch)
418 {
419
420         if (strcmp(arg, "minimum") == 0 || strcmp(arg, "min") == 0)
421                 *mode = MODE_MIN;
422         else if (strcmp(arg, "maximum") == 0 || strcmp(arg, "max") == 0)
423                 *mode = MODE_MAX;
424         else if (strcmp(arg, "adaptive") == 0 || strcmp(arg, "adp") == 0)
425                 *mode = MODE_ADAPTIVE;
426         else if (strcmp(arg, "hiadaptive") == 0 || strcmp(arg, "hadp") == 0)
427                 *mode = MODE_HIADAPTIVE;
428         else
429                 errx(1, "bad option: -%c %s", (char)ch, optarg);
430 }
431
432 static void
433 handle_sigs(int __unused sig)
434 {
435
436         exit_requested = 1;
437 }
438
439 static void
440 usage(void)
441 {
442
443         fprintf(stderr,
444 "usage: powerd [-v] [-a mode] [-b mode] [-i %%] [-m freq] [-M freq] [-n mode] [-p ival] [-r %%] [-P pidfile]\n");
445         exit(1);
446 }
447
448 int
449 main(int argc, char * argv[])
450 {
451         struct timeval timeout;
452         fd_set fdset;
453         int nfds;
454         struct pidfh *pfh = NULL;
455         const char *pidfile = NULL;
456         int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
457         int minfreq = -1, maxfreq = -1;
458         int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
459         uint64_t mjoules_used;
460         size_t len;
461
462         /* Default mode for all AC states is adaptive. */
463         mode_ac = mode_none = MODE_HIADAPTIVE;
464         mode_battery = MODE_ADAPTIVE;
465         cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
466         cpu_idle_mark = DEFAULT_IDLE_PERCENT;
467         poll_ival = DEFAULT_POLL_INTERVAL;
468         mjoules_used = 0;
469         vflag = 0;
470
471         /* User must be root to control frequencies. */
472         if (geteuid() != 0)
473                 errx(1, "must be root to run");
474
475         while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
476                 switch (ch) {
477                 case 'a':
478                         parse_mode(optarg, &mode_ac, ch);
479                         break;
480                 case 'b':
481                         parse_mode(optarg, &mode_battery, ch);
482                         break;
483                 case 'i':
484                         cpu_idle_mark = atoi(optarg);
485                         if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
486                                 warnx("%d is not a valid percent",
487                                     cpu_idle_mark);
488                                 usage();
489                         }
490                         break;
491                 case 'm':
492                         minfreq = atoi(optarg);
493                         if (minfreq < 0) {
494                                 warnx("%d is not a valid CPU frequency",
495                                     minfreq);
496                                 usage();
497                         }
498                         break;
499                 case 'M':
500                         maxfreq = atoi(optarg);
501                         if (maxfreq < 0) {
502                                 warnx("%d is not a valid CPU frequency",
503                                     maxfreq);
504                                 usage();
505                         }
506                         break;
507                 case 'n':
508                         parse_mode(optarg, &mode_none, ch);
509                         break;
510                 case 'p':
511                         poll_ival = atoi(optarg);
512                         if (poll_ival < 5) {
513                                 warnx("poll interval is in units of ms");
514                                 usage();
515                         }
516                         break;
517                 case 'P':
518                         pidfile = optarg;
519                         break;
520                 case 'r':
521                         cpu_running_mark = atoi(optarg);
522                         if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
523                                 warnx("%d is not a valid percent",
524                                     cpu_running_mark);
525                                 usage();
526                         }
527                         break;
528                 case 'v':
529                         vflag = 1;
530                         break;
531                 default:
532                         usage();
533                 }
534
535         mode = mode_none;
536
537         /* Poll interval is in units of ms. */
538         poll_ival *= 1000;
539
540         /* Look up various sysctl MIBs. */
541         len = 2;
542         if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
543                 err(1, "lookup kern.cp_times");
544         len = 4;
545         if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
546                 err(1, "lookup freq");
547         len = 4;
548         if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
549                 err(1, "lookup freq_levels");
550
551         /* Check if we can read the load and supported freqs. */
552         if (read_usage_times(NULL))
553                 err(1, "read_usage_times");
554         if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
555                 err(1, "error reading supported CPU frequencies");
556         if (numfreqs == 0)
557                 errx(1, "no CPU frequencies in user-specified range");
558
559         /* Run in the background unless in verbose mode. */
560         if (!vflag) {
561                 pid_t otherpid;
562
563                 pfh = pidfile_open(pidfile, 0600, &otherpid);
564                 if (pfh == NULL) {
565                         if (errno == EEXIST) {
566                                 errx(1, "powerd already running, pid: %d",
567                                     otherpid);
568                         }
569                         warn("cannot open pid file");
570                 }
571                 if (daemon(0, 0) != 0) {
572                         warn("cannot enter daemon mode, exiting");
573                         pidfile_remove(pfh);
574                         exit(EXIT_FAILURE);
575
576                 }
577                 pidfile_write(pfh);
578         }
579
580         /* Decide whether to use ACPI or APM to read the AC line status. */
581         acline_init();
582
583         /*
584          * Exit cleanly on signals.
585          */
586         signal(SIGINT, handle_sigs);
587         signal(SIGTERM, handle_sigs);
588
589         freq = initfreq = curfreq = get_freq();
590         i = get_freq_id(curfreq, freqs, numfreqs);
591         if (freq < 1)
592                 freq = 1;
593
594         /*
595          * If we are in adaptive mode and the current frequency is outside the
596          * user-defined range, adjust it to be within the user-defined range.
597          */
598         acline_read();
599         if (acline_status > SRC_UNKNOWN)
600                 errx(1, "invalid AC line status %d", acline_status);
601         if ((acline_status == SRC_AC &&
602             (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
603             (acline_status == SRC_BATTERY &&
604             (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
605             (acline_status == SRC_UNKNOWN &&
606             (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
607                 /* Read the current frequency. */
608                 len = sizeof(curfreq);
609                 if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
610                         if (vflag)
611                                 warn("error reading current CPU frequency");
612                 }
613                 if (curfreq < freqs[numfreqs - 1]) {
614                         if (vflag) {
615                                 printf("CPU frequency is below user-defined "
616                                     "minimum; changing frequency to %d "
617                                     "MHz\n", freqs[numfreqs - 1]);
618                         }
619                         if (set_freq(freqs[numfreqs - 1]) != 0) {
620                                 warn("error setting CPU freq %d",
621                                     freqs[numfreqs - 1]);
622                         }
623                 } else if (curfreq > freqs[0]) {
624                         if (vflag) {
625                                 printf("CPU frequency is above user-defined "
626                                     "maximum; changing frequency to %d "
627                                     "MHz\n", freqs[0]);
628                         }
629                         if (set_freq(freqs[0]) != 0) {
630                                 warn("error setting CPU freq %d",
631                                     freqs[0]);
632                         }
633                 }
634         }
635
636         idle = 0;
637         /* Main loop. */
638         for (;;) {
639                 FD_ZERO(&fdset);
640                 if (devd_pipe >= 0) {
641                         FD_SET(devd_pipe, &fdset);
642                         nfds = devd_pipe + 1;
643                 } else {
644                         nfds = 0;
645                 }
646                 if (mode == MODE_HIADAPTIVE || idle < 120)
647                         to = poll_ival;
648                 else if (idle < 360)
649                         to = poll_ival * 2;
650                 else
651                         to = poll_ival * 4;
652                 timeout.tv_sec = to / 1000000;
653                 timeout.tv_usec = to % 1000000;
654                 select(nfds, &fdset, NULL, &fdset, &timeout);
655
656                 /* If the user requested we quit, print some statistics. */
657                 if (exit_requested) {
658                         if (vflag && mjoules_used != 0)
659                                 printf("total joules used: %u.%03u\n",
660                                     (u_int)(mjoules_used / 1000),
661                                     (int)mjoules_used % 1000);
662                         break;
663                 }
664
665                 /* Read the current AC status and record the mode. */
666                 acline_read();
667                 switch (acline_status) {
668                 case SRC_AC:
669                         mode = mode_ac;
670                         break;
671                 case SRC_BATTERY:
672                         mode = mode_battery;
673                         break;
674                 case SRC_UNKNOWN:
675                         mode = mode_none;
676                         break;
677                 default:
678                         errx(1, "invalid AC line status %d", acline_status);
679                 }
680
681                 /* Read the current frequency. */
682                 if (idle % 32 == 0) {
683                         if ((curfreq = get_freq()) == 0)
684                                 continue;
685                         i = get_freq_id(curfreq, freqs, numfreqs);
686                 }
687                 idle++;
688                 if (vflag) {
689                         /* Keep a sum of all power actually used. */
690                         if (mwatts[i] != -1)
691                                 mjoules_used +=
692                                     (mwatts[i] * (poll_ival / 1000)) / 1000;
693                 }
694
695                 /* Always switch to the lowest frequency in min mode. */
696                 if (mode == MODE_MIN) {
697                         freq = freqs[numfreqs - 1];
698                         if (curfreq != freq) {
699                                 if (vflag) {
700                                         printf("now operating on %s power; "
701                                             "changing frequency to %d MHz\n",
702                                             modes[acline_status], freq);
703                                 }
704                                 idle = 0;
705                                 if (set_freq(freq) != 0) {
706                                         warn("error setting CPU freq %d",
707                                             freq);
708                                         continue;
709                                 }
710                         }
711                         continue;
712                 }
713
714                 /* Always switch to the highest frequency in max mode. */
715                 if (mode == MODE_MAX) {
716                         freq = freqs[0];
717                         if (curfreq != freq) {
718                                 if (vflag) {
719                                         printf("now operating on %s power; "
720                                             "changing frequency to %d MHz\n",
721                                             modes[acline_status], freq);
722                                 }
723                                 idle = 0;
724                                 if (set_freq(freq) != 0) {
725                                         warn("error setting CPU freq %d",
726                                             freq);
727                                         continue;
728                                 }
729                         }
730                         continue;
731                 }
732
733                 /* Adaptive mode; get the current CPU usage times. */
734                 if (read_usage_times(&load)) {
735                         if (vflag)
736                                 warn("read_usage_times() failed");
737                         continue;
738                 }
739
740                 if (mode == MODE_ADAPTIVE) {
741                         if (load > cpu_running_mark) {
742                                 if (load > 95 || load > cpu_running_mark * 2)
743                                         freq *= 2;
744                                 else
745                                         freq = freq * load / cpu_running_mark;
746                                 if (freq > freqs[0])
747                                         freq = freqs[0];
748                         } else if (load < cpu_idle_mark &&
749                             curfreq * load < freqs[get_freq_id(
750                             freq * 7 / 8, freqs, numfreqs)] *
751                             cpu_running_mark) {
752                                 freq = freq * 7 / 8;
753                                 if (freq < freqs[numfreqs - 1])
754                                         freq = freqs[numfreqs - 1];
755                         }
756                 } else { /* MODE_HIADAPTIVE */
757                         if (load > cpu_running_mark / 2) {
758                                 if (load > 95 || load > cpu_running_mark)
759                                         freq *= 4;
760                                 else
761                                         freq = freq * load * 2 / cpu_running_mark;
762                                 if (freq > freqs[0] * 2)
763                                         freq = freqs[0] * 2;
764                         } else if (load < cpu_idle_mark / 2 &&
765                             curfreq * load < freqs[get_freq_id(
766                             freq * 31 / 32, freqs, numfreqs)] *
767                             cpu_running_mark / 2) {
768                                 freq = freq * 31 / 32;
769                                 if (freq < freqs[numfreqs - 1])
770                                         freq = freqs[numfreqs - 1];
771                         }
772                 }
773                 if (vflag) {
774                     printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
775                         load, curfreq, i, freq);
776                 }
777                 j = get_freq_id(freq, freqs, numfreqs);
778                 if (i != j) {
779                         if (vflag) {
780                                 printf("changing clock"
781                                     " speed from %d MHz to %d MHz\n",
782                                     freqs[i], freqs[j]);
783                         }
784                         idle = 0;
785                         if (set_freq(freqs[j]))
786                                 warn("error setting CPU frequency %d",
787                                     freqs[j]);
788                 }
789         }
790         if (set_freq(initfreq))
791                 warn("error setting CPU frequency %d", initfreq);
792         free(freqs);
793         free(mwatts);
794         devd_close();
795         if (!vflag)
796                 pidfile_remove(pfh);
797
798         exit(0);
799 }