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>
52 static void usage(void);
53 static double getcputime(double);
54 static void acpi_setcpufreq(int nstate);
55 static void setupdominfo(void);
56 static int has_battery(void);
57 static int mon_battery(void);
61 int CpuLimit; /* # of cpus at max frequency */
62 int DomLimit; /* # of domains at max frequency */
67 int CpuCount[256]; /* # of cpus in any given domain */
68 int CpuToDom[256]; /* domain a particular cpu belongs to */
69 int Hysteresis = 10; /* percentage */
70 double TriggerUp = 0.25;/* single-cpu load to force max freq */
71 double TriggerDown; /* load per cpu to force the min freq */
72 static int BatLifeMin = 2; /* shutdown the box, if low on battery life */
73 static struct timespec BatLifePrevT;
74 static struct timespec BatLifeStartT;
75 static int BatLifeLinger = 60; /* unit: sec */
76 static int BatLifePollIntvl = 5; /* unit: sec */
78 static void sigintr(int signo);
81 main(int ac, char **av)
84 double uavg; /* uavg - used for speeding up */
85 double davg; /* davg - used for slowing down */
95 srt = 8.0; /* time for samples - 8 seconds */
96 pollrate = 1.0; /* polling rate in seconds */
98 while ((ch = getopt(ac, av, "dp:r:tu:B:L:P:T:")) != -1) {
104 Hysteresis = (int)strtol(optarg, NULL, 10);
107 pollrate = strtod(optarg, NULL);
113 TriggerUp = (double)strtol(optarg, NULL, 10) / 100;
116 BatLifeMin = strtol(optarg, NULL, 10);
119 BatLifeLinger = strtol(optarg, NULL, 10);
122 BatLifePollIntvl = strtol(optarg, NULL, 10);
125 srt = strtod(optarg, NULL);
135 if (0 > Hysteresis || Hysteresis > 99) {
136 fprintf(stderr, "Invalid hysteresis value\n");
140 if (0 > TriggerUp || TriggerUp > 1) {
141 fprintf(stderr, "Invalid load limit value\n");
145 TriggerDown = TriggerUp - (TriggerUp * (double) Hysteresis / 100);
148 * Make sure powerd is not already running.
150 PowerFd = open("/var/run/powerd.pid", O_CREAT|O_RDWR, 0644);
153 "Cannot create /var/run/powerd.pid, "
154 "continuing anyway\n");
156 if (flock(PowerFd, LOCK_EX|LOCK_NB) < 0) {
157 fprintf(stderr, "powerd is already running\n");
163 * Demonize and set pid
167 openlog("powerd", LOG_CONS | LOG_PID, LOG_DAEMON);
171 ftruncate(PowerFd, 0);
172 snprintf(buf, sizeof(buf), "%d\n", (int)getpid());
173 write(PowerFd, buf, strlen(buf));
176 /* Do we need to monitor battery life? */
177 monbat = has_battery();
180 * Wait hw.acpi.cpu.px_dom* sysctl to be created by kernel
182 * Since hw.acpi.cpu.px_dom* creation is queued into ACPI
183 * taskqueue and ACPI taskqueue is shared across various
184 * ACPI modules, any delay in other modules may cause
185 * hw.acpi.cpu.px_dom* to be created at quite a later time
186 * (e.g. cmbat module's task could take quite a lot of time).
190 * Prime delta cputime calculation, make sure at least
193 getcputime(pollrate);
196 if (DomBeg >= DomEnd) {
197 usleep((int)(pollrate * 1000000.0));
207 * Set to maximum performance if killed.
209 signal(SIGINT, sigintr);
210 signal(SIGTERM, sigintr);
214 srt = srt / pollrate; /* convert to sample count */
217 printf("samples for downgrading: %5.2f\n", srt);
222 * Calculate nstate, the number of cpus we wish to run at max
223 * frequency. All remaining cpus will be set to their lowest
224 * frequency and mapped out of the user process scheduler.
227 qavg = getcputime(pollrate);
228 uavg = (uavg * 2.0 + qavg) / 3.0; /* speeding up */
229 davg = (davg * srt + qavg) / (srt + 1); /* slowing down */
233 ustate = uavg / TriggerUp;
234 if (ustate < CpuLimit)
235 ustate = uavg / TriggerDown;
236 dstate = davg / TriggerUp;
237 if (dstate < CpuLimit)
238 dstate = davg / TriggerDown;
240 nstate = (ustate > dstate) ? ustate : dstate;
245 printf("\rqavg=%5.2f uavg=%5.2f davg=%5.2f "
246 "%2d/%2d ncpus=%d\r",
248 CpuLimit, DomLimit, nstate);
251 if (nstate != CpuLimit)
252 acpi_setcpufreq(nstate);
254 monbat = mon_battery();
255 usleep((int)(pollrate * 1000000.0));
261 sigintr(int signo __unused)
263 syslog(LOG_INFO, "killed, setting max and exiting");
264 acpi_setcpufreq(NCpus);
269 * Figure out the domains and calculate the CpuCount[] and CpuToDom[]
283 for (i = 0; i < 256; ++i) {
284 snprintf(buf, sizeof(buf),
285 "hw.acpi.cpu.px_dom%d.available", i);
286 if (sysctlbyname(buf, NULL, NULL, NULL, 0) >= 0)
291 for (i = 255; i >= DomBeg; --i) {
292 snprintf(buf, sizeof(buf),
293 "hw.acpi.cpu.px_dom%d.available", i);
294 if (sysctlbyname(buf, NULL, NULL, NULL, 0) >= 0) {
301 for (i = DomBeg; i < DomEnd; ++i) {
302 snprintf(buf, sizeof(buf),
303 "hw.acpi.cpu.px_dom%d.members", i);
304 msize = sizeof(members);
305 if (sysctlbyname(buf, members, &msize, NULL, 0) == 0) {
307 for (str = strtok(members, " "); str;
308 str = strtok(NULL, " ")) {
310 sscanf(str, "cpu%d", &n);
322 * Return the one-second cpu load. One cpu at 100% will return a value
323 * of 1.0. On a SMP system N cpus running at 100% will return a value of N.
327 getcputime(double pollrate)
329 static struct kinfo_cputime ocpu_time[64];
330 static struct kinfo_cputime ncpu_time[64];
336 bcopy(ncpu_time, ocpu_time, sizeof(ncpu_time));
337 slen = sizeof(ncpu_time);
338 if (sysctlbyname("kern.cputime", &ncpu_time, &slen, NULL, 0) < 0) {
339 fprintf(stderr, "kern.cputime sysctl not available\n");
342 ncpu = slen / sizeof(ncpu_time[0]);
345 for (cpu = 0; cpu < ncpu; ++cpu) {
346 delta += (ncpu_time[cpu].cp_user + ncpu_time[cpu].cp_sys +
347 ncpu_time[cpu].cp_nice + ncpu_time[cpu].cp_intr) -
348 (ocpu_time[cpu].cp_user + ocpu_time[cpu].cp_sys +
349 ocpu_time[cpu].cp_nice + ocpu_time[cpu].cp_intr);
351 return((double)delta / (pollrate * 1000000.0));
355 * nstate is the requested number of cpus that we wish to run at full
356 * frequency. We calculate how many domains we have to adjust to reach
359 * This function also sets the user scheduler global cpu mask.
363 acpi_setcpufreq(int nstate)
366 int increasing = (nstate > CpuLimit);
378 cpumask_t global_cpumask;
381 * Calculate the ending domain if the number of operating cpus
384 * Calculate the starting domain if the number of operating cpus
387 for (dom = DomBeg; dom < DomEnd; ++dom) {
390 ncpus += CpuCount[dom];
393 syslog(LOG_INFO, "using %d cpus", nstate);
396 * Set the mask of cpus the userland scheduler is allowed to use.
398 CPUMASK_ASSBMASK(global_cpumask, nstate);
399 sysctlbyname("kern.usched_global_cpumask", NULL, 0,
400 &global_cpumask, sizeof(global_cpumask));
413 * Adjust the cpu frequency
417 for (dom = domBeg; dom < domEnd; ++dom) {
419 * Retrieve availability list
421 asprintf(&sysid, "hw.acpi.cpu.px_dom%d.available", dom);
422 buflen = sizeof(buf) - 1;
423 v = sysctlbyname(sysid, buf, &buflen, NULL, 0);
430 * Parse out the highest and lowest cpu frequencies
433 highest = lowest = 0;
434 while (ptr && (v = strtol(ptr, &ptr, 10)) > 0) {
435 if (lowest == 0 || lowest > v)
437 if (highest == 0 || highest < v)
442 if ((highest - v == 1) && ! TurboOpt)
448 * Calculate the desired cpu frequency, test, and set.
450 desired = increasing ? highest : lowest;
452 asprintf(&sysid, "hw.acpi.cpu.px_dom%d.select", dom);
455 sysctlbyname(sysid, &v, &buflen, NULL, 0);
458 printf("dom%d set frequency %d\n",
461 sysctlbyname(sysid, NULL, NULL,
462 &desired, sizeof(desired));
472 fprintf(stderr, "usage: powerd [-dt] [-p hysteresis] "
473 "[-u trigger_up] [-T sample_interval] [-r poll_interval] "
474 "[-B min_battery_life] [-L low_battery_linger] "
475 "[-P battery_poll_interval]\n");
480 #define timespecsub(vvp, uvp) \
482 (vvp)->tv_sec -= (uvp)->tv_sec; \
483 (vvp)->tv_nsec -= (uvp)->tv_nsec; \
484 if ((vvp)->tv_nsec < 0) { \
486 (vvp)->tv_nsec += 1000000000; \
491 #define BAT_SYSCTL_TIME_MAX 50000000 /* unit: nanosecond */
496 struct timespec s, e;
500 clock_gettime(CLOCK_MONOTONIC_FAST, &s);
505 if (sysctlbyname("hw.acpi.acline", &val, &len, NULL, 0) < 0) {
506 /* No AC line information */
509 clock_gettime(CLOCK_MONOTONIC_FAST, &e);
512 if (e.tv_sec > 0 || e.tv_nsec > BAT_SYSCTL_TIME_MAX) {
513 /* hw.acpi.acline takes to long to be useful */
514 syslog(LOG_NOTICE, "hw.acpi.acline takes too long");
518 clock_gettime(CLOCK_MONOTONIC_FAST, &s);
520 if (sysctlbyname("hw.acpi.battery.life", &val, &len, NULL, 0) < 0) {
521 /* No battery life */
524 clock_gettime(CLOCK_MONOTONIC_FAST, &e);
527 if (e.tv_sec > 0 || e.tv_nsec > BAT_SYSCTL_TIME_MAX) {
528 /* hw.acpi.battery.life takes to long to be useful */
529 syslog(LOG_NOTICE, "hw.acpi.battery.life takes too long");
538 struct timespec cur, ts;
542 clock_gettime(CLOCK_MONOTONIC_FAST, &cur);
544 timespecsub(&ts, &BatLifePrevT);
545 if (ts.tv_sec < BatLifePollIntvl)
549 len = sizeof(acline);
550 if (sysctlbyname("hw.acpi.acline", &acline, &len, NULL, 0) < 0)
556 if (sysctlbyname("hw.acpi.battery.life", &life, &len, NULL, 0) < 0)
559 if (BatLifeLinger > 0) {
561 timespecsub(&ts, &BatLifeStartT);
562 if (ts.tv_sec > BatLifeLinger)
566 if (life <= BatLifeMin) {
567 if (BatLifeLinger <= 0) {
568 syslog(LOG_ALERT, "low battery life %d%%, "
569 "shutting down", life);
571 execlp("poweroff", "poweroff", NULL);
578 syslog(LOG_ALERT, "low battery life %d%%, "
579 "please plugin AC line", life);