2 * Copyright (c) 2010 The DragonFly Project. All rights reserved.
4 * This code is derived from software contributed to The DragonFly Project
5 * by Matthew Dillon <dillon@backplane.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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
15 * the documentation and/or other materials provided with the
17 * 3. Neither the name of The DragonFly Project nor the names of its
18 * contributors may be used to endorse or promote products derived
19 * from this software without specific, prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * The powerd daemon monitors the cpu load and adjusts cpu frequencies
37 * via hw.acpi.cpu.px_dom*.
40 #define _KERNEL_STRUCTURES
41 #include <sys/types.h>
42 #include <sys/sysctl.h>
43 #include <sys/kinfo.h>
45 #include <sys/soundcard.h>
55 static void usage(void);
56 static double getcputime(double);
57 static void acpi_setcpufreq(int nstate);
58 static void setupdominfo(void);
59 static int has_battery(void);
60 static int mon_battery(void);
64 int CpuLimit; /* # of cpus at max frequency */
65 int DomLimit; /* # of domains at max frequency */
70 int CpuCount[256]; /* # of cpus in any given domain */
71 int CpuToDom[256]; /* domain a particular cpu belongs to */
72 int Hysteresis = 10; /* percentage */
73 double TriggerUp = 0.25;/* single-cpu load to force max freq */
74 double TriggerDown; /* load per cpu to force the min freq */
75 static int BatLifeMin = 2; /* shutdown the box, if low on battery life */
76 static struct timespec BatLifePrevT;
77 static int BatLifePollIntvl = 5; /* unit: sec */
79 static struct timespec BatShutdownStartT;
80 static int BatShutdownLinger = -1;
81 static int BatShutdownLingerSet = 60; /* unit: sec */
82 static int BatShutdownLingerCnt;
83 static int BatShutdownAudioAlert = 1;
85 static void sigintr(int signo);
88 main(int ac, char **av)
91 double uavg; /* uavg - used for speeding up */
92 double davg; /* davg - used for slowing down */
102 srt = 8.0; /* time for samples - 8 seconds */
103 pollrate = 1.0; /* polling rate in seconds */
105 while ((ch = getopt(ac, av, "dp:r:tu:B:L:P:QT:")) != -1) {
111 Hysteresis = (int)strtol(optarg, NULL, 10);
114 pollrate = strtod(optarg, NULL);
120 TriggerUp = (double)strtol(optarg, NULL, 10) / 100;
123 BatLifeMin = strtol(optarg, NULL, 10);
126 BatShutdownLingerSet = strtol(optarg, NULL, 10);
127 if (BatShutdownLingerSet < 0)
128 BatShutdownLingerSet = 0;
131 BatLifePollIntvl = strtol(optarg, NULL, 10);
134 BatShutdownAudioAlert = 0;
137 srt = strtod(optarg, NULL);
147 if (0 > Hysteresis || Hysteresis > 99) {
148 fprintf(stderr, "Invalid hysteresis value\n");
152 if (0 > TriggerUp || TriggerUp > 1) {
153 fprintf(stderr, "Invalid load limit value\n");
157 TriggerDown = TriggerUp - (TriggerUp * (double) Hysteresis / 100);
160 * Make sure powerd is not already running.
162 PowerFd = open("/var/run/powerd.pid", O_CREAT|O_RDWR, 0644);
165 "Cannot create /var/run/powerd.pid, "
166 "continuing anyway\n");
168 if (flock(PowerFd, LOCK_EX|LOCK_NB) < 0) {
169 fprintf(stderr, "powerd is already running\n");
175 * Demonize and set pid
179 openlog("powerd", LOG_CONS | LOG_PID, LOG_DAEMON);
183 ftruncate(PowerFd, 0);
184 snprintf(buf, sizeof(buf), "%d\n", (int)getpid());
185 write(PowerFd, buf, strlen(buf));
188 /* Do we need to monitor battery life? */
189 if (BatLifePollIntvl <= 0)
192 monbat = has_battery();
195 * Wait hw.acpi.cpu.px_dom* sysctl to be created by kernel
197 * Since hw.acpi.cpu.px_dom* creation is queued into ACPI
198 * taskqueue and ACPI taskqueue is shared across various
199 * ACPI modules, any delay in other modules may cause
200 * hw.acpi.cpu.px_dom* to be created at quite a later time
201 * (e.g. cmbat module's task could take quite a lot of time).
205 * Prime delta cputime calculation, make sure at least
208 getcputime(pollrate);
211 if (DomBeg >= DomEnd) {
212 usleep((int)(pollrate * 1000000.0));
222 * Set to maximum performance if killed.
224 signal(SIGINT, sigintr);
225 signal(SIGTERM, sigintr);
229 srt = srt / pollrate; /* convert to sample count */
232 printf("samples for downgrading: %5.2f\n", srt);
237 * Calculate nstate, the number of cpus we wish to run at max
238 * frequency. All remaining cpus will be set to their lowest
239 * frequency and mapped out of the user process scheduler.
242 qavg = getcputime(pollrate);
243 uavg = (uavg * 2.0 + qavg) / 3.0; /* speeding up */
244 davg = (davg * srt + qavg) / (srt + 1); /* slowing down */
248 ustate = uavg / TriggerUp;
249 if (ustate < CpuLimit)
250 ustate = uavg / TriggerDown;
251 dstate = davg / TriggerUp;
252 if (dstate < CpuLimit)
253 dstate = davg / TriggerDown;
255 nstate = (ustate > dstate) ? ustate : dstate;
260 printf("\rqavg=%5.2f uavg=%5.2f davg=%5.2f "
261 "%2d/%2d ncpus=%d\r",
263 CpuLimit, DomLimit, nstate);
266 if (nstate != CpuLimit)
267 acpi_setcpufreq(nstate);
269 monbat = mon_battery();
270 usleep((int)(pollrate * 1000000.0));
276 sigintr(int signo __unused)
278 syslog(LOG_INFO, "killed, setting max and exiting");
279 acpi_setcpufreq(NCpus);
284 * Figure out the domains and calculate the CpuCount[] and CpuToDom[]
298 for (i = 0; i < 256; ++i) {
299 snprintf(buf, sizeof(buf),
300 "hw.acpi.cpu.px_dom%d.available", i);
301 if (sysctlbyname(buf, NULL, NULL, NULL, 0) >= 0)
306 for (i = 255; i >= DomBeg; --i) {
307 snprintf(buf, sizeof(buf),
308 "hw.acpi.cpu.px_dom%d.available", i);
309 if (sysctlbyname(buf, NULL, NULL, NULL, 0) >= 0) {
316 for (i = DomBeg; i < DomEnd; ++i) {
317 snprintf(buf, sizeof(buf),
318 "hw.acpi.cpu.px_dom%d.members", i);
319 msize = sizeof(members);
320 if (sysctlbyname(buf, members, &msize, NULL, 0) == 0) {
322 for (str = strtok(members, " "); str;
323 str = strtok(NULL, " ")) {
325 sscanf(str, "cpu%d", &n);
337 * Return the one-second cpu load. One cpu at 100% will return a value
338 * of 1.0. On a SMP system N cpus running at 100% will return a value of N.
342 getcputime(double pollrate)
344 static struct kinfo_cputime ocpu_time[64];
345 static struct kinfo_cputime ncpu_time[64];
351 bcopy(ncpu_time, ocpu_time, sizeof(ncpu_time));
352 slen = sizeof(ncpu_time);
353 if (sysctlbyname("kern.cputime", &ncpu_time, &slen, NULL, 0) < 0) {
354 fprintf(stderr, "kern.cputime sysctl not available\n");
357 ncpu = slen / sizeof(ncpu_time[0]);
360 for (cpu = 0; cpu < ncpu; ++cpu) {
361 delta += (ncpu_time[cpu].cp_user + ncpu_time[cpu].cp_sys +
362 ncpu_time[cpu].cp_nice + ncpu_time[cpu].cp_intr) -
363 (ocpu_time[cpu].cp_user + ocpu_time[cpu].cp_sys +
364 ocpu_time[cpu].cp_nice + ocpu_time[cpu].cp_intr);
366 return((double)delta / (pollrate * 1000000.0));
370 * nstate is the requested number of cpus that we wish to run at full
371 * frequency. We calculate how many domains we have to adjust to reach
374 * This function also sets the user scheduler global cpu mask.
378 acpi_setcpufreq(int nstate)
381 int increasing = (nstate > CpuLimit);
393 cpumask_t global_cpumask;
396 * Calculate the ending domain if the number of operating cpus
399 * Calculate the starting domain if the number of operating cpus
402 for (dom = DomBeg; dom < DomEnd; ++dom) {
405 ncpus += CpuCount[dom];
408 syslog(LOG_INFO, "using %d cpus", nstate);
411 * Set the mask of cpus the userland scheduler is allowed to use.
413 CPUMASK_ASSBMASK(global_cpumask, nstate);
414 sysctlbyname("kern.usched_global_cpumask", NULL, 0,
415 &global_cpumask, sizeof(global_cpumask));
428 * Adjust the cpu frequency
432 for (dom = domBeg; dom < domEnd; ++dom) {
434 * Retrieve availability list
436 asprintf(&sysid, "hw.acpi.cpu.px_dom%d.available", dom);
437 buflen = sizeof(buf) - 1;
438 v = sysctlbyname(sysid, buf, &buflen, NULL, 0);
445 * Parse out the highest and lowest cpu frequencies
448 highest = lowest = 0;
449 while (ptr && (v = strtol(ptr, &ptr, 10)) > 0) {
450 if (lowest == 0 || lowest > v)
452 if (highest == 0 || highest < v)
457 if ((highest - v == 1) && ! TurboOpt)
463 * Calculate the desired cpu frequency, test, and set.
465 desired = increasing ? highest : lowest;
467 asprintf(&sysid, "hw.acpi.cpu.px_dom%d.select", dom);
470 sysctlbyname(sysid, &v, &buflen, NULL, 0);
473 printf("dom%d set frequency %d\n",
476 sysctlbyname(sysid, NULL, NULL,
477 &desired, sizeof(desired));
487 fprintf(stderr, "usage: powerd [-dt] [-p hysteresis] "
488 "[-u trigger_up] [-T sample_interval] [-r poll_interval] "
489 "[-B min_battery_life] [-L low_battery_linger] "
490 "[-P battery_poll_interval] [-Q]\n");
495 #define timespecsub(vvp, uvp) \
497 (vvp)->tv_sec -= (uvp)->tv_sec; \
498 (vvp)->tv_nsec -= (uvp)->tv_nsec; \
499 if ((vvp)->tv_nsec < 0) { \
501 (vvp)->tv_nsec += 1000000000; \
506 #define BAT_SYSCTL_TIME_MAX 50000000 /* unit: nanosecond */
511 struct timespec s, e;
515 clock_gettime(CLOCK_MONOTONIC_FAST, &s);
519 if (sysctlbyname("hw.acpi.acline", &val, &len, NULL, 0) < 0) {
520 /* No AC line information */
523 clock_gettime(CLOCK_MONOTONIC_FAST, &e);
526 if (e.tv_sec > 0 || e.tv_nsec > BAT_SYSCTL_TIME_MAX) {
527 /* hw.acpi.acline takes to long to be useful */
528 syslog(LOG_NOTICE, "hw.acpi.acline takes too long");
532 clock_gettime(CLOCK_MONOTONIC_FAST, &s);
534 if (sysctlbyname("hw.acpi.battery.life", &val, &len, NULL, 0) < 0) {
535 /* No battery life */
538 clock_gettime(CLOCK_MONOTONIC_FAST, &e);
541 if (e.tv_sec > 0 || e.tv_nsec > BAT_SYSCTL_TIME_MAX) {
542 /* hw.acpi.battery.life takes to long to be useful */
543 syslog(LOG_NOTICE, "hw.acpi.battery.life takes too long");
550 low_battery_alert(int life)
552 int fmt, stereo, freq;
555 syslog(LOG_ALERT, "low battery life %d%%, please plugin AC line, #%d",
556 life, BatShutdownLingerCnt);
557 ++BatShutdownLingerCnt;
559 if (!BatShutdownAudioAlert)
562 fd = open("/dev/dsp", O_WRONLY);
567 if (ioctl(fd, SNDCTL_DSP_SETFMT, &fmt, sizeof(fmt)) < 0)
571 if (ioctl(fd, SNDCTL_DSP_STEREO, &stereo, sizeof(stereo)) < 0)
575 if (ioctl(fd, SNDCTL_DSP_SPEED, &freq, sizeof(freq)) < 0)
578 write(fd, alert1, sizeof(alert1));
579 write(fd, alert1, sizeof(alert1));
588 struct timespec cur, ts;
592 clock_gettime(CLOCK_MONOTONIC_FAST, &cur);
594 timespecsub(&ts, &BatLifePrevT);
595 if (ts.tv_sec < BatLifePollIntvl)
599 len = sizeof(acline);
600 if (sysctlbyname("hw.acpi.acline", &acline, &len, NULL, 0) < 0)
603 BatShutdownLinger = -1;
604 BatShutdownLingerCnt = 0;
609 if (sysctlbyname("hw.acpi.battery.life", &life, &len, NULL, 0) < 0)
612 if (BatShutdownLinger > 0) {
614 timespecsub(&ts, &BatShutdownStartT);
615 if (ts.tv_sec > BatShutdownLinger)
616 BatShutdownLinger = 0;
619 if (life <= BatLifeMin) {
620 if (BatShutdownLinger == 0 || BatShutdownLingerSet == 0) {
621 syslog(LOG_ALERT, "low battery life %d%%, "
622 "shutting down", life);
624 execlp("poweroff", "poweroff", NULL);
626 } else if (BatShutdownLinger < 0) {
627 BatShutdownLinger = BatShutdownLingerSet;
628 BatShutdownStartT = cur;
630 low_battery_alert(life);