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