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