powerstat-0.01.30/0000775000175000017500000000000012312556535012356 5ustar kingkingpowerstat-0.01.30/powerstat.c0000664000175000017500000011431212312556517014554 0ustar kingking/* * Copyright (C) 2011-2014 Canonical * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define APP_NAME "powerstat" #define MIN_RUN_DURATION (5*60) /* We recommend a run of 5 minutes */ #define SAMPLE_DELAY (10) /* Delay between samples in seconds */ #define ROLLING_AVERAGE_SECS (120) /* 2 minute rolling average for power usage calculation */ #define STANDARD_AVERAGE_SECS (120) #define MAX_MEASUREMENTS (ROLLING_AVERAGE_SECS + 10) #define START_DELAY (3*60) /* Delay to wait before sampling */ #define MAX_PIDS (32769) /* Hash Max PIDs */ #define RATE_ZERO_LIMIT (0.001) /* Less than this we call the power rate zero */ #define IDLE_THRESHOLD (98) /* Less than this and we assume the machine is not idle */ #define CPU_USER 0 #define CPU_NICE 1 #define CPU_SYS 2 #define CPU_IDLE 3 #define CPU_IOWAIT 4 #define CPU_IRQ 5 #define CPU_SOFTIRQ 6 #define CPU_INTR 7 #define CPU_CTXT 8 #define CPU_PROCS_RUN 9 #define CPU_PROCS_BLK 10 #define POWER_RATE 11 #define PROC_FORK 12 #define PROC_EXEC 13 #define PROC_EXIT 14 #define MAX_VALUES 15 /* Arg opt flags */ #define OPTS_SHOW_PROC_ACTIVITY (0x0001) /* dump out process activity */ #define OPTS_REDO_NETLINK_BUSY (0x0002) /* tasks fork/exec/exit */ #define OPTS_REDO_WHEN_NOT_IDLE (0x0004) /* when idle below idle_threshold */ #define OPTS_ZERO_RATE_ALLOW (0x0008) /* force allow zero rates */ #define OPTS_ROOT_PRIV (0x0010) /* has root privilege */ #define OPTS_STANDARD_AVERAGE (0x0020) /* calc standard average */ #define OPTS_USE_NETLINK (OPTS_SHOW_PROC_ACTIVITY | \ OPTS_REDO_NETLINK_BUSY | \ OPTS_ROOT_PRIV) #define SYS_CLASS_POWER_SUPPLY "/sys/class/power_supply" #define PROC_ACPI_BATTERY "/proc/acpi/battery" #define SYS_FIELD_VOLTAGE "POWER_SUPPLY_VOLTAGE_NOW=" #define SYS_FIELD_WATTS_RATE "POWER_SUPPLY_POWER_NOW=" #define SYS_FIELD_WATTS_LEFT "POWER_SUPPLY_ENERGY_NOW=" #define SYS_FIELD_AMPS_RATE "POWER_SUPPLY_CURRENT_NOW=" #define SYS_FIELD_AMPS_LEFT "POWER_SUPPLY_CHARGE_NOW=" #define SYS_FIELD_STATUS_DISCHARGING "POWER_SUPPLY_STATUS=Discharging" /* Measurement entry */ typedef struct { double value; /* Measurment value */ time_t when; /* When it was measured */ } measurement_t; /* Statistics entry */ typedef struct { double value[MAX_VALUES]; bool inaccurate[MAX_VALUES]; } stats_t; /* /proc info cache */ typedef struct { pid_t pid; /* Process ID */ char *cmdline; /* /proc/pid/cmdline text */ } proc_info_t; /* Log item link list */ typedef struct log_item_t { struct log_item_t *next; char *text; } log_item_t; /* Log list header */ typedef struct { log_item_t *head; log_item_t *tail; } log_t; static proc_info_t *proc_info[MAX_PIDS]; /* Proc hash table */ static int max_readings; /* number of samples to gather */ static int sample_delay = SAMPLE_DELAY; /* time between each sample in secs */ static int start_delay = START_DELAY; /* seconds before we start displaying stats */ static double idle_threshold = IDLE_THRESHOLD; /* lower than this and the CPU is busy */ static log_t infolog; /* log */ static int opts; /* opt arg opt flags */ static volatile int stop_recv; /* sighandler stop flag */ static bool power_calc_from_capacity = false; /* true of power is calculated via capacity change */ /* * file_get() * read a line from a /sys file */ static char *file_get(const char *const file) { FILE *fp; char buffer[4096]; if ((fp = fopen(file, "r")) == NULL) return NULL; if (fgets(buffer, sizeof(buffer), fp) == NULL) { fclose(fp); return NULL; } (void)fclose(fp); return strdup(buffer); } /* * tty_height() * try and find height of tty */ static int tty_height(void) { #ifdef TIOCGWINSZ int fd = 0; struct winsize ws; /* if tty and we can get a sane width, return it */ if (isatty(fd) && (ioctl(fd, TIOCGWINSZ, &ws) != -1) && (0 < ws.ws_row) && (ws.ws_row == (size_t)ws.ws_row)) return ws.ws_row; #endif return 25; /* else standard tty 80x25 */ } /* * time_now() * Gather current time in buffer */ static void time_now(char *const buffer, const size_t buflen) { struct tm tm; time_t now; (void)time(&now); (void)localtime_r(&now, &tm); snprintf(buffer, buflen, "%2.2d:%2.2d:%2.2d ", tm.tm_hour, tm.tm_min, tm.tm_sec); } /* * log_init() * Initialise log head */ static inline void log_init(void) { infolog.head = NULL; infolog.tail = NULL; } /* * log_printf() * append log messages in log list */ static int log_printf(const char *const fmt, ...) { char buffer[4096]; char tmbuffer[10]; va_list ap; log_item_t *log_item; size_t len; va_start(ap, fmt); time_now(tmbuffer, sizeof(tmbuffer)); vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); if ((log_item = calloc(1, sizeof(log_t))) == NULL) { fprintf(stderr, "Out of memory allocating log item\n"); return -1; } len = strlen(buffer) + strlen(tmbuffer) + 1; log_item->text = calloc(1, len); snprintf(log_item->text, len, "%s%s", tmbuffer, buffer); if (infolog.head == NULL) infolog.head = log_item; else infolog.tail->next = log_item; infolog.tail = log_item; return 0; } /* * log_dump() * dump out any saved log messages */ static void log_dump(void) { log_item_t *log_item; if (infolog.head != NULL) printf("\nLog of fork()/exec()/exit() calls:\n"); for (log_item = infolog.head; log_item != NULL; log_item = log_item->next) printf("%s", log_item->text); } /* * log_free() * free log messages */ static void log_free(void) { log_item_t *log_item = infolog.head; while (log_item != NULL) { log_item_t *log_next = log_item->next; free(log_item->text); free(log_item); log_item = log_next; } infolog.head = NULL; infolog.tail = NULL; } /* * handle_sigint() * catch SIGINT and flag a stop */ static void handle_sigint(int dummy) { (void)dummy; stop_recv = 1; } /* * netlink_connect() * connect to netlink socket */ static int netlink_connect(void) { int sock; struct sockaddr_nl addr; if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR)) < 0) { if (errno == EPROTONOSUPPORT) return -EPROTONOSUPPORT; fprintf(stderr, "Socket failed: %s\n", strerror(errno)); return -1; } memset(&addr, 0, sizeof(addr)); addr.nl_pid = getpid(); addr.nl_family = AF_NETLINK; addr.nl_groups = CN_IDX_PROC; if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { fprintf(stderr, "Bind failed: %s\n", strerror(errno)); (void)close(sock); return -1; } return sock; } /* * netlink_listen() * proc connector listen */ static int netlink_listen(const int sock) { struct iovec iov[3]; struct nlmsghdr nlmsghdr; struct cn_msg cn_msg; enum proc_cn_mcast_op op; memset(&nlmsghdr, 0, sizeof(nlmsghdr)); nlmsghdr.nlmsg_len = NLMSG_LENGTH(sizeof(cn_msg) + sizeof(op)); nlmsghdr.nlmsg_pid = getpid(); nlmsghdr.nlmsg_type = NLMSG_DONE; iov[0].iov_base = &nlmsghdr; iov[0].iov_len = sizeof(nlmsghdr); memset(&cn_msg, 0, sizeof(cn_msg)); cn_msg.id.idx = CN_IDX_PROC; cn_msg.id.val = CN_VAL_PROC; cn_msg.len = sizeof(enum proc_cn_mcast_op); iov[1].iov_base = &cn_msg; iov[1].iov_len = sizeof(cn_msg); op = PROC_CN_MCAST_LISTEN; iov[2].iov_base = &op; iov[2].iov_len = sizeof(op); return writev(sock, iov, 3); } /* * stats_clear() * clear stats */ static void stats_clear(stats_t *const stats) { int i; for (i = 0; i < MAX_VALUES; i++) { stats->value[i] = 0.0; stats->inaccurate[i] = false; } } /* * stats_clear_all() * zero stats data */ static void stats_clear_all(stats_t *const stats, const int n) { int i; for (i = 0; i < n; i++) stats_clear(&stats[i]); } /* * stats_read() * gather pertinent /proc/stat data */ static int stats_read(stats_t *const info) { FILE *fp; char buf[4096]; if ((fp = fopen("/proc/stat", "r")) == NULL) return -1; while (fgets(buf, sizeof(buf), fp) != NULL) { if (strncmp(buf, "cpu ", 4) == 0) sscanf(buf, "%*s %15lf %15lf %15lf %15lf %15lf %15lf %15lf", &(info->value[CPU_USER]), &(info->value[CPU_NICE]), &(info->value[CPU_SYS]), &(info->value[CPU_IDLE]), &(info->value[CPU_IOWAIT]), &(info->value[CPU_IRQ]), &(info->value[CPU_SOFTIRQ])); if (strncmp(buf, "ctxt ", 5) == 0) sscanf(buf, "%*s %15lf", &(info->value[CPU_CTXT])); if (strncmp(buf, "intr ", 5) == 0) sscanf(buf, "%*s %15lf", &(info->value[CPU_INTR])); if (strncmp(buf, "procs_running ", 14) == 0) sscanf(buf, "%*s %15lf", &(info->value[CPU_PROCS_RUN])); if (strncmp(buf, "procs_blocked ", 14) == 0) sscanf(buf, "%*s %15lf", &(info->value[CPU_PROCS_BLK])); } (void)fclose(fp); return 0; } /* * On Nexus 4 we occasionally get idle time going backwards so * work around this by ensuring we don't get -ve deltas. */ #define SANE_STATS(s1, s2) ((s2) - (s1)) < 0.0 ? 0.0 : ((s2) - (s1)) /* * stats_gather() * gather up delta between last stats and current to get * some form of per sample accounting calculated. */ static bool stats_gather( const stats_t *const s1, const stats_t *const s2, stats_t *const res) { double total; res->value[CPU_USER] = SANE_STATS(s1->value[CPU_USER] , s2->value[CPU_USER]); res->value[CPU_NICE] = SANE_STATS(s1->value[CPU_NICE] , s2->value[CPU_NICE]); res->value[CPU_SYS] = SANE_STATS(s1->value[CPU_SYS] , s2->value[CPU_SYS]); res->value[CPU_IDLE] = SANE_STATS(s1->value[CPU_IDLE] , s2->value[CPU_IDLE]); res->value[CPU_IOWAIT] = SANE_STATS(s1->value[CPU_IOWAIT] , s2->value[CPU_IOWAIT]); res->value[CPU_IRQ] = SANE_STATS(s1->value[CPU_IRQ] , s2->value[CPU_IRQ]); res->value[CPU_SOFTIRQ] = SANE_STATS(s1->value[CPU_SOFTIRQ], s2->value[CPU_SOFTIRQ]); res->value[CPU_CTXT] = SANE_STATS(s1->value[CPU_CTXT] , s2->value[CPU_CTXT]); res->value[CPU_INTR] = SANE_STATS(s1->value[CPU_INTR] , s2->value[CPU_INTR]); total = res->value[CPU_USER] + res->value[CPU_NICE] + res->value[CPU_SYS] + res->value[CPU_IDLE] + res->value[CPU_IOWAIT]; /* * This should not happen, but we need to avoid division * by zero or weird results */ if (total <= 0.0) return false; res->value[CPU_USER] = (100.0 * res->value[CPU_USER]) / total; res->value[CPU_NICE] = (100.0 * res->value[CPU_NICE]) / total; res->value[CPU_SYS] = (100.0 * res->value[CPU_SYS]) / total; res->value[CPU_IDLE] = (100.0 * res->value[CPU_IDLE]) / total; res->value[CPU_IOWAIT] = (100.0 * res->value[CPU_IOWAIT]) / total; res->value[CPU_CTXT] = res->value[CPU_CTXT] / sample_delay; res->value[CPU_INTR] = res->value[CPU_INTR] / sample_delay; res->value[CPU_PROCS_RUN] = s2->value[CPU_PROCS_RUN]; res->value[CPU_PROCS_BLK] = s2->value[CPU_PROCS_BLK]; return true; } /* * stats_headings() * dump heading columns */ static void stats_headings(void) { if (opts & OPTS_USE_NETLINK) printf(" Time User Nice Sys Idle IO Run Ctxt/s IRQ/s Fork Exec Exit Watts\n"); else printf(" Time User Nice Sys Idle IO Run Ctxt/s IRQ/s Watts\n"); } /* * stats_ruler() * pretty print ruler between rows */ static void stats_ruler(void) { if (opts & OPTS_USE_NETLINK) printf("-------- ----- ----- ----- ----- ----- ---- ------ ------ ---- ---- ---- ------\n"); else printf("-------- ----- ----- ----- ----- ----- ---- ------ ------ ------\n"); } /* * * */ static void row_increment(int *const row) { int tty_rows = tty_height(); (*row)++; if ((tty_rows >2) && (*row >= tty_rows)) { stats_headings(); *row = 2; } } /* * stats_print() * print out statistics with accuracy depending if it's a summary or not */ static void stats_print( const char *const prefix, const bool summary, const stats_t *const s) { char buf[10]; if (summary) { if (s->inaccurate[POWER_RATE]) snprintf(buf, sizeof(buf), "-N/A-"); else snprintf(buf, sizeof(buf), "%6.2f", s->value[POWER_RATE]); } else { snprintf(buf, sizeof(buf), "%6.2f%s", s->value[POWER_RATE], s->inaccurate[POWER_RATE] ? "E" : ""); } if (opts & OPTS_USE_NETLINK) { char *fmt = summary ? "%8.8s %5.1f %5.1f %5.1f %5.1f %5.1f %4.1f %6.1f %6.1f %4.1f %4.1f %4.1f %s\n" : "%8.8s %5.1f %5.1f %5.1f %5.1f %5.1f %4.0f %6.0f %6.0f %4.0f %4.0f %4.0f %s\n"; printf(fmt, prefix, s->value[CPU_USER], s->value[CPU_NICE], s->value[CPU_SYS], s->value[CPU_IDLE], s->value[CPU_IOWAIT], s->value[CPU_PROCS_RUN], s->value[CPU_CTXT], s->value[CPU_INTR], s->value[PROC_FORK], s->value[PROC_EXEC], s->value[PROC_EXIT], buf); } else { char *fmt = summary ? "%8.8s %5.1f %5.1f %5.1f %5.1f %5.1f %4.1f %6.1f %6.1f %s\n" : "%8.8s %5.1f %5.1f %5.1f %5.1f %5.1f %4.0f %6.0f %6.0f %s\n"; printf(fmt, prefix, s->value[CPU_USER], s->value[CPU_NICE], s->value[CPU_SYS], s->value[CPU_IDLE], s->value[CPU_IOWAIT], s->value[CPU_PROCS_RUN], s->value[CPU_CTXT], s->value[CPU_INTR], buf); } } /* * stats_average_stddev_min_max() * calculate average, std deviation, min and max */ static void stats_average_stddev_min_max( const stats_t *const stats, const int num, stats_t *const average, stats_t *const stddev, stats_t *const min, stats_t *const max) { int i, j, valid; for (j = 0; j < MAX_VALUES; j++) { double total = 0.0; max->value[j] = -1E6; min->value[j] = 1E6; for (valid = 0, i = 0; i < num; i++) { if (!stats[i].inaccurate[j]) { if (stats[i].value[j] > max->value[j]) max->value[j] = stats[i].value[j]; if (stats[i].value[j] < min->value[j]) min->value[j] = stats[i].value[j]; total += stats[i].value[j]; valid++; } } if (valid) { average->value[j] = total / (double)valid; total = 0.0; for (i = 0; i < num; i++) { if (!stats[i].inaccurate[j]) { double diff = (double)stats[i].value[j] - average->value[j]; diff = diff * diff; total += diff; } } stddev->value[j] = total / (double)num; stddev->value[j] = sqrt(stddev->value[j]); } else { average->inaccurate[j] = true; max->inaccurate[j] = true; min->inaccurate[j] = true; stddev->inaccurate[j] = true; average->value[j] = 0.0; max->value[j] = 0.0; min->value[j] = 0.0; stddev->value[j] = 0.0; } } } /* * calc_standard_average() * calculate a standard average based on first sample * and the current sample */ static void calc_standard_average( double total_capacity, double *const rate, bool *const inaccurate) { static time_t time_start = 0; static double total_capacity_start = 0.0; static bool first = true; time_t time_now, dt; double dw; time_now = time(NULL); if (first) { time_start = time_now; total_capacity_start = total_capacity; first = false; *rate = 0.0; *inaccurate = true; return; } dt = time_now - time_start; dw = total_capacity_start - total_capacity; if (dt <= 0 || dw <= 0.0) { /* Something is wrong, can't be a good sample */ *rate = 0.0; *inaccurate = true; return; } *rate = 3600.0 * dw / dt; /* Only after a fairly long duration can we be sure it is reasonable */ *inaccurate = dt < STANDARD_AVERAGE_SECS; } /* * calc_rolling_average() * calculate power by using rolling average * * Battery is less helpful, we need to figure the power rate by looking * back in time, measuring capacity drop and figuring out the rate from * this. We keep track of the rate over a sliding window of * ROLLING_AVERAGE_SECS seconds. */ static void calc_rolling_average( double total_capacity, double *const rate, bool *const inaccurate) { static int index = 0; time_t time_now, dt; static measurement_t measurements[MAX_MEASUREMENTS]; int i, j; time_now = time(NULL); measurements[index].value = total_capacity; measurements[index].when = time_now; index = (index + 1) % MAX_MEASUREMENTS; *rate = 0.0; /* * Scan back in time for a sample that's > ROLLING_AVERAGE_SECS * seconds away and calculate power consumption based on this * value and interval */ for (j = index, i = 0; i < MAX_MEASUREMENTS; i++) { j--; if (j < 0) j += MAX_MEASUREMENTS; if (measurements[j].when) { double dw = measurements[j].value - total_capacity; dt = time_now - measurements[j].when; *rate = 3600.0 * dw / dt; if (time_now - measurements[j].when > ROLLING_AVERAGE_SECS) { *inaccurate = false; break; } } } /* * We either have found a good measurement, or an estimate at this point, but * is it valid? */ if (*rate < 0.0) { *rate = 0.0; *inaccurate = true; } } static void calc_from_capacity( double total_capacity, double *const rate, bool *const inaccurate) { power_calc_from_capacity = true; if (opts & OPTS_STANDARD_AVERAGE) calc_standard_average(total_capacity, rate, inaccurate); else calc_rolling_average(total_capacity, rate, inaccurate); } /* * power_rate_get_sys_fs() * get power discharge rate from battery via /sys interface */ static int power_rate_get_sys_fs( double *const rate, bool *const discharging, bool *const inaccurate) { DIR *dir; struct dirent *dirent; double total_watts = 0.0, total_capacity = 0.0; *rate = 0.0; *discharging = false; *inaccurate = true; if ((dir = opendir(SYS_CLASS_POWER_SUPPLY)) == NULL) { fprintf(stderr, "Machine does not have %s, cannot run the test.\n", SYS_CLASS_POWER_SUPPLY); return -1; } do { dirent = readdir(dir); if (dirent && strlen(dirent->d_name) > 2) { char path[PATH_MAX]; char *data; int val; FILE *fp; /* Check that type field matches the expected type */ snprintf(path, sizeof(path), "%s/%s/type", SYS_CLASS_POWER_SUPPLY, dirent->d_name); if ((data = file_get(path)) != NULL) { bool mismatch = (strstr(data, "Battery") == NULL); free(data); if (mismatch) continue; /* type don't match, skip this entry */ } else continue; /* can't check type, skip this entry */ snprintf(path, sizeof(path), "%s/%s/uevent", SYS_CLASS_POWER_SUPPLY, dirent->d_name); if ((fp = fopen(path, "r")) == NULL) { fprintf(stderr, "Battery %s present but under supported - no state present.", dirent->d_name); closedir(dir); return -1; } else { char buffer[4096]; double voltage = 0.0; double amps_rate = 0.0; double amps_left = 0.0; double watts_rate = 0.0; double watts_left = 0.0; while (fgets(buffer, sizeof(buffer)-1, fp) != NULL) { if (strstr(buffer, SYS_FIELD_STATUS_DISCHARGING)) *discharging = true; if (strstr(buffer, SYS_FIELD_AMPS_LEFT) && strlen(buffer) > sizeof(SYS_FIELD_AMPS_LEFT) - 1) { sscanf(buffer + sizeof(SYS_FIELD_AMPS_LEFT) - 1, "%12d", &val); amps_left = (double)val / 1000000.0; } if (strstr(buffer, SYS_FIELD_WATTS_LEFT) && strlen(buffer) > sizeof(SYS_FIELD_WATTS_LEFT) - 1) { sscanf(buffer + sizeof(SYS_FIELD_WATTS_LEFT) - 1, "%12d", &val); watts_left = (double)val / 1000000.0; } if (strstr(buffer, SYS_FIELD_AMPS_RATE) && strlen(buffer) > sizeof(SYS_FIELD_AMPS_RATE) - 1) { sscanf(buffer + sizeof(SYS_FIELD_AMPS_RATE) - 1, "%12d", &val); amps_rate = (double)val / 1000000.0; } if (strstr(buffer, SYS_FIELD_WATTS_RATE) && strlen(buffer) > sizeof(SYS_FIELD_WATTS_RATE) - 1) { sscanf(buffer + sizeof(SYS_FIELD_WATTS_RATE) - 1, "%12d", &val); watts_rate = (double)val / 1000000.0; } if (strstr(buffer, SYS_FIELD_VOLTAGE) && strlen(buffer) > sizeof(SYS_FIELD_VOLTAGE) - 1) { sscanf(buffer + sizeof(SYS_FIELD_VOLTAGE) - 1, "%12d", &val); voltage = (double)val / 1000000.0; } } total_watts += watts_rate + voltage * amps_rate; total_capacity += watts_left + voltage * amps_left; fclose(fp); } } } while (dirent); (void)closedir(dir); if (! *discharging) { printf("Machine is not discharging, cannot measure power usage.\n"); return -1; } /* * If the battery is helpful it supplies the rate already, in which case * we know the results from the battery are as good as we can and we don't * have to figure out anything from capacity change over time. */ if (total_watts > RATE_ZERO_LIMIT) { *rate = total_watts; *inaccurate = (total_watts < 0.0); return 0; } /* Rate not known, so calculate it from historical data, sigh */ calc_from_capacity(total_capacity, rate, inaccurate); return 0; } /* * power_rate_get_proc_acpi() * get power discharge rate from battery via /proc/acpi interface */ static int power_rate_get_proc_acpi( double *const rate, bool *const discharging, bool *const inaccurate) { DIR *dir; FILE *file; struct dirent *dirent; char filename[PATH_MAX]; double total_watts = 0.0, total_capacity = 0.0; *rate = 0.0; *discharging = false; *inaccurate = true; if ((dir = opendir(PROC_ACPI_BATTERY)) == NULL) { fprintf(stderr, "Machine does not have %s, cannot run the test.\n", PROC_ACPI_BATTERY); return -1; } while ((dirent = readdir(dir))) { double voltage = 0.0; double amps_rate = 0.0; double amps_left = 0.0; double watts_rate = 0.0; double watts_left = 0.0; char buffer[4096]; char *ptr; if (strlen(dirent->d_name) < 3) continue; sprintf(filename, "/proc/acpi/battery/%s/state", dirent->d_name); if ((file = fopen(filename, "r")) == NULL) continue; memset(buffer, 0, sizeof(buffer)); while (fgets(buffer, sizeof(buffer), file) != NULL) { if (strstr(buffer, "present:") && strstr(buffer, "no")) break; if (strstr(buffer, "charging state:") && (strstr(buffer, "discharging") || strstr(buffer, "critical"))) *discharging = true; ptr = strchr(buffer, ':'); if (ptr) { ptr++; if (strstr(buffer, "present voltage")) voltage = strtoull(ptr, NULL, 10) / 1000.0; if (strstr(buffer, "present rate")) { if (strstr(ptr, "mW")) watts_rate = strtoull(ptr, NULL, 10) / 1000.0 ; if (strstr(ptr, "mA")) amps_rate = strtoull(ptr, NULL, 10) / 1000.0; } if (strstr(buffer, "remaining capacity")) { if (strstr(ptr, "mW")) watts_left = strtoull(ptr, NULL, 10) / 1000.0 ; if (strstr(ptr, "mA")) amps_left = strtoull(ptr, NULL, 10) / 1000.0; } } } (void)fclose(file); /* * Some HP firmware is broken and has an undefined * 'present voltage' field and instead returns this in * the design_voltage field, so work around this. */ if (voltage == 0.0) { sprintf(filename, "/proc/acpi/battery/%s/info", dirent->d_name); if ((file = fopen(filename, "r")) != NULL) { while (fgets(buffer, sizeof(buffer), file) != NULL) { ptr = strchr(buffer, ':'); if (ptr) { ptr++; if (strstr(buffer, "design voltage:")) { voltage = strtoull(ptr, NULL, 10) / 1000.0; break; } } } fclose(file); } } total_watts += watts_rate + voltage * amps_rate; total_capacity += watts_left + voltage * amps_left; } (void)closedir(dir); if (! *discharging) { printf("Machine is indicating it is not discharging and hence " "we cannot measure power usage.\n"); return -1; } /* * If the battery is helpful it supplies the rate already, in which * case we know the results from the battery are as good as we can * and we don't have to figure out anything from capacity change over * time. */ if (total_watts > RATE_ZERO_LIMIT) { *rate = total_watts; *inaccurate = (total_watts < 0.0); return 0; } /* Rate not known, so calculate it from historical data, sigh */ calc_from_capacity(total_capacity, rate, inaccurate); return 0; } static int power_rate_get( double *const rate, bool *const discharging, bool *const inaccurate) { struct stat buf; if ((stat(SYS_CLASS_POWER_SUPPLY, &buf) != -1) && S_ISDIR(buf.st_mode)) return power_rate_get_sys_fs(rate, discharging, inaccurate); if ((stat(PROC_ACPI_BATTERY, &buf) != -1) && S_ISDIR(buf.st_mode)) return power_rate_get_proc_acpi(rate, discharging, inaccurate); fprintf(stderr, "Machine does not seem to have a battery, cannot measure power.\n"); return -1; } /* * proc_info_hash() * hash on PID */ static inline int proc_info_hash(const pid_t pid) { return pid % MAX_PIDS; } /* * proc_cmdline() * get a processes cmdline text */ static int proc_cmdline( const pid_t pid, char *const cmdline, const size_t size) { FILE *fp; char path[PATH_MAX]; int n = 0; *cmdline = '\0'; snprintf(path, sizeof(path), "/proc/%d/cmdline", pid); if ((fp = fopen(path, "r")) != NULL) { n = fread(cmdline, size, 1, fp); (void)fclose(fp); } return n; } /* * proc_info_get() * get proc info on a given pid */ static char *proc_info_get(const pid_t pid) { int i = proc_info_hash(pid), j; for (j = 0; j < MAX_PIDS; j++, i = (i + 1) % MAX_PIDS) { if ((proc_info[i] != NULL) && (proc_info[i]->pid == pid)) return proc_info[i]->cmdline; } return ""; } /* * proc_info_free() * free cached process info and remove from hash table */ static void proc_info_free(const pid_t pid) { int i = proc_info_hash(pid), j; for (j = 0; j < MAX_PIDS; j++, i = (i + 1) % MAX_PIDS) { if ((proc_info[i] != NULL) && (proc_info[i]->pid == pid)) { free(proc_info[i]->cmdline); free(proc_info[i]); proc_info[i] = NULL; return; } } } /* * proc_info_unload() * free all hashed proc info entries */ static void proc_info_unload(void) { int i; for (i = 0; i < MAX_PIDS; i++) { if (proc_info[i] != NULL) { free(proc_info[i]->cmdline); free(proc_info[i]); proc_info[i] = NULL; } } } /* * proc_info_add() * add processes info of a given pid to the hash table */ static int proc_info_add(const pid_t pid) { int i, j; proc_info_t *info; char path[PATH_MAX]; char cmdline[1024]; bool free_slot = false; i = proc_info_hash(pid); for (j = 0; j < MAX_PIDS; j++, i = (i + 1) % MAX_PIDS) { if (proc_info[i] == NULL) { free_slot = true; break; } } if (!free_slot) return -1; memset(cmdline, 0, sizeof(cmdline)); /* keep valgrind happy */ if ((info = calloc(1, sizeof(proc_info_t))) == NULL) { fprintf(stderr, "Cannot allocate all proc info\n"); return -1; } info->pid = pid; snprintf(path, sizeof(path), "/proc/%d/cmdline", info->pid); (void)proc_cmdline(pid, cmdline, sizeof(cmdline)); if ((info->cmdline = malloc(strlen(cmdline)+1)) == NULL) { fprintf(stderr, "Cannot allocate all proc info\n"); free(info); return -1; } strcpy(info->cmdline, cmdline); proc_info[i] = info; return -1; } /* * proc_info_load() * load up all current processes info into hash table */ static int proc_info_load(void) { DIR *dir; struct dirent *dirent; if ((dir = opendir("/proc")) == NULL) return -1; while ((dirent = readdir(dir))) { if (isdigit(dirent->d_name[0])) proc_info_add(atoi(dirent->d_name)); } (void)closedir(dir); return 0; } /* * monitor() * monitor system activity and power consumption */ static int monitor(const int sock) { ssize_t len; int readings = 0, redone = 0, row = 0; stats_t *stats, s1, s2, average, stddev, min, max; struct nlmsghdr *nlmsghdr; struct timeval t1, t2; if ((stats = calloc(max_readings, sizeof(stats_t))) == NULL) { fprintf(stderr, "Cannot allocate statistics table.\n"); return -1; } stats_clear_all(stats, max_readings); stats_clear(&average); stats_clear(&stddev); stats_clear(&min); stats_clear(&max); stats_headings(); row++; gettimeofday(&t1, NULL); stats_read(&s1); while (!stop_recv && (readings < max_readings)) { bool redo = false; int ret; suseconds_t usec; struct timeval tv; char __attribute__ ((aligned(NLMSG_ALIGNTO)))buf[4096]; (void)gettimeofday(&t2, NULL); usec = ((t1.tv_sec + sample_delay - t2.tv_sec) * 1000000) + (t1.tv_usec - t2.tv_usec); if (usec < 0) goto sample_now; tv.tv_sec = usec / 1000000; tv.tv_usec = usec % 1000000; if (opts & OPTS_USE_NETLINK) { fd_set readfds; FD_ZERO(&readfds); FD_SET(sock, &readfds); ret = select(sock+1, &readfds, NULL, NULL, &tv); } else { ret = select(0, NULL, NULL, NULL, &tv); } if (ret < 0) { if (errno == EINTR) break; fprintf(stderr,"select: %s\n", strerror(errno)); free(stats); return -1; } /* Time out, so measure some more samples */ if (ret == 0) { char tmbuffer[10]; bool discharging; sample_now: if (redone) { char buffer[80]; int indent; snprintf(buffer, sizeof(buffer), "--- Skipped samples(s) because of %s%s%s ---", redone & OPTS_REDO_WHEN_NOT_IDLE ? "low CPU idle" : "", (redone & (OPTS_REDO_WHEN_NOT_IDLE | OPTS_REDO_NETLINK_BUSY)) == (OPTS_REDO_WHEN_NOT_IDLE | OPTS_REDO_NETLINK_BUSY) ? " and " : "", redone & OPTS_REDO_NETLINK_BUSY ? "fork/exec/exit activity" : ""); indent = (80 - strlen(buffer)) / 2; row_increment(&row); printf("%*.*s%s\n", indent, indent, "", buffer); redone = 0; } time_now(tmbuffer, sizeof(tmbuffer)); (void)gettimeofday(&t1, NULL); stats_read(&s2); /* * Total ticks was zero, something is broken, so re-sample */ if (!stats_gather(&s1, &s2, &stats[readings])) { stats_clear(&stats[readings]); stats_read(&s1); gettimeofday(&t1, NULL); redone |= OPTS_REDO_WHEN_NOT_IDLE; continue; } if ((opts & OPTS_REDO_WHEN_NOT_IDLE) && (stats[readings].value[CPU_IDLE] < idle_threshold)) { stats_clear(&stats[readings]); stats_read(&s1); gettimeofday(&t1, NULL); redone |= OPTS_REDO_WHEN_NOT_IDLE; continue; } if (power_rate_get(&stats[readings].value[POWER_RATE], &discharging, &stats[readings].inaccurate[POWER_RATE]) < 0) { free(stats); return -1; /* Failure to read */ } if (!discharging) { free(stats); return -1; /* No longer discharging! */ } row_increment(&row); stats_print(tmbuffer, false, &stats[readings]); readings++; s1 = s2; continue; } if (opts & OPTS_USE_NETLINK) { if ((len = recv(sock, buf, sizeof(buf), 0)) == 0) { free(stats); return 0; } if (len == -1) { if (errno == EINTR) { continue; } else { fprintf(stderr,"recv: %s\n", strerror(errno)); free(stats); return -1; } } for (nlmsghdr = (struct nlmsghdr *)buf; NLMSG_OK (nlmsghdr, len); nlmsghdr = NLMSG_NEXT (nlmsghdr, len)) { struct cn_msg *cn_msg; struct proc_event *proc_ev; if ((nlmsghdr->nlmsg_type == NLMSG_ERROR) || (nlmsghdr->nlmsg_type == NLMSG_NOOP)) continue; cn_msg = NLMSG_DATA(nlmsghdr); if ((cn_msg->id.idx != CN_IDX_PROC) || (cn_msg->id.val != CN_VAL_PROC)) continue; proc_ev = (struct proc_event *)cn_msg->data; switch (proc_ev->what) { case PROC_EVENT_FORK: stats[readings].value[PROC_FORK] += 1.0; proc_info_add(proc_ev->event_data.fork.child_pid); if (opts & OPTS_SHOW_PROC_ACTIVITY) { log_printf("fork: parent tid=%d pid=%d -> child tid=%d pid=%d (%s)\n", proc_ev->event_data.fork.parent_pid, proc_ev->event_data.fork.parent_tgid, proc_ev->event_data.fork.child_pid, proc_ev->event_data.fork.child_tgid, proc_info_get(proc_ev->event_data.fork.child_pid)); } redo = true; break; case PROC_EVENT_EXEC: stats[readings].value[PROC_EXEC] += 1.0; if (opts & OPTS_SHOW_PROC_ACTIVITY) { log_printf("exec: tid=%d pid=%d (%s)\n", proc_ev->event_data.exec.process_pid, proc_ev->event_data.exec.process_tgid, proc_info_get(proc_ev->event_data.exec.process_pid)); } redo = true; break; case PROC_EVENT_EXIT: stats[readings].value[PROC_EXIT] += 1.0; if (opts & OPTS_SHOW_PROC_ACTIVITY) { log_printf("exit: tid=%d pid=%d exit_code=%d (%s)\n", proc_ev->event_data.exit.process_pid, proc_ev->event_data.exit.process_tgid, proc_ev->event_data.exit.exit_code, proc_info_get(proc_ev->event_data.exit.process_pid)); } if (proc_ev->event_data.exit.process_pid == proc_ev->event_data.exit.process_tgid) proc_info_free(proc_ev->event_data.exit.process_pid); redo = true; break; default: break; } } /* Have we been asked to redo a sample on fork/exec/exit? */ if (opts & OPTS_REDO_NETLINK_BUSY && redo) { stats_clear(&stats[readings]); stats_read(&s1); gettimeofday(&t1, NULL); redone |= OPTS_REDO_NETLINK_BUSY; } } } /* Stats now gathered, calculate averages, stddev, min and max and display */ stats_average_stddev_min_max(stats, readings, &average, &stddev, &min, &max); if (readings > 0) { stats_ruler(); stats_print("Average", true, &average); stats_print("StdDev", true, &stddev); stats_ruler(); stats_print("Minimum", true, &min); stats_print("Maximum", true, &max); stats_ruler(); } printf("Summary:\n"); printf("%6.2f Watts on Average with Standard Deviation %-6.2f\n", average.value[POWER_RATE], stddev.value[POWER_RATE]); if (power_calc_from_capacity) { printf("Note: Power calculated from battery capacity drain, may not be accurate.\n"); } else { if (opts & OPTS_STANDARD_AVERAGE) printf("Note: The battery supplied suitable power data, -S option not required.\n"); } free(stats); return 0; } /* * show_help() * simple help */ void show_help(char *const argv[]) { printf("%s, version %s\n\n", APP_NAME, VERSION); printf("usage: %s [-d secs] [-i idle] [-b|-h|-p|-r|-s|-z] [delay [count]]\n", argv[0]); printf("\t-b redo a sample if a system is busy, considered less than %d%% CPU idle\n", IDLE_THRESHOLD); printf("\t-d specify delay before starting, default is %d seconds\n", start_delay); printf("\t-h show help\n"); printf("\t-i specify CPU idle threshold, used in conjunction with -b\n"); printf("\t-p redo a sample if we see process fork/exec/exit activity\n"); printf("\t-r redo a sample if busy and we see process activity (same as -b -p)\n"); printf("\t-s show process fork/exec/exit activity log\n"); printf("\t-S calculate power from capacity drain using standard average\n"); printf("\t-z forcibly ignore zero power rate stats from the battery\n"); printf("\tdelay: delay between each sample, default is %d seconds\n", SAMPLE_DELAY); printf("\tcount: number of samples to take\n"); } int main(int argc, char * const argv[]) { double dummy_rate; int sock = -1, ret = EXIT_FAILURE, i, run_duration; bool discharging, dummy_inaccurate; signal(SIGINT, &handle_sigint); siginterrupt(SIGINT, 1); for (;;) { int c = getopt(argc, argv, "bd:hi:prszS"); if (c == -1) break; switch (c) { case 'b': opts |= OPTS_REDO_WHEN_NOT_IDLE; break; case 'd': start_delay = atoi(optarg); if (start_delay < 0) { fprintf(stderr, "Start delay must be 0 or more seconds\n"); exit(EXIT_FAILURE); } break; case 'h': show_help(argv); exit(EXIT_SUCCESS); case 'i': opts |= OPTS_REDO_WHEN_NOT_IDLE; idle_threshold = atof(optarg); if ((idle_threshold < 0.0) || (idle_threshold > 99.99)) { fprintf(stderr, "Idle threshold must be between 0..99.99\n"); exit(EXIT_FAILURE); } break; case 'p': opts |= OPTS_REDO_NETLINK_BUSY; break; case 'r': opts |= (OPTS_REDO_NETLINK_BUSY | OPTS_REDO_WHEN_NOT_IDLE); break; case 's': opts |= OPTS_SHOW_PROC_ACTIVITY; break; case 'S': opts |= OPTS_STANDARD_AVERAGE; break; case 'z': opts |= OPTS_ZERO_RATE_ALLOW; break; } } if (optind < argc) { sample_delay = atoi(argv[optind++]); if (sample_delay < 1) { fprintf(stderr, "Sample delay must be >= 1\n"); exit(ret); } } run_duration = MIN_RUN_DURATION + START_DELAY - start_delay; if (optind < argc) { max_readings = atoi(argv[optind++]); if ((max_readings * sample_delay) < run_duration) { fprintf(stderr, "Number of readings should be at least %d\n", run_duration / sample_delay); exit(ret); } } else { max_readings = run_duration / sample_delay; } if (geteuid() == 0) opts |= OPTS_ROOT_PRIV; else if (opts & OPTS_USE_NETLINK) { fprintf(stderr, "%s needs to be run with root privilege when using -p, -r, -s options\n", argv[0]); exit(ret); } if (power_rate_get(&dummy_rate, &discharging, &dummy_inaccurate) < 0) exit(ret); printf("Running for %d seconds (%d samples at %d second intervals).\n", sample_delay * max_readings, max_readings, sample_delay); printf("ACPI battery power measurements will start in %d seconds time\n", start_delay); printf("\n"); if (start_delay > 0) { /* Gather up initial data */ for (i = 0; i < start_delay; i++) { printf("Waiting %d seconds before starting (gathering samples) \r", start_delay - i); fflush(stdout); if (power_rate_get(&dummy_rate, &discharging, &dummy_inaccurate) < 0) exit(ret); if (sleep(1) || stop_recv) exit(ret); if (!discharging) exit(ret); } printf("%79.79s\r", ""); } log_init(); if (opts & OPTS_USE_NETLINK) { sock = netlink_connect(); if (sock == -EPROTONOSUPPORT) { if (opts & OPTS_SHOW_PROC_ACTIVITY) printf("Cannot show process activity with this kernel.\n"); opts &= ~OPTS_USE_NETLINK; } else if (sock < 0) { goto abort; } else { proc_info_load(); if (netlink_listen(sock) < 0) goto abort_sock; } } if (power_rate_get(&dummy_rate, &discharging, &dummy_inaccurate) < 0) goto abort_sock; if (monitor(sock) == 0) ret = EXIT_SUCCESS; abort_sock: if (opts & OPTS_USE_NETLINK) proc_info_unload(); abort: if (opts & OPTS_USE_NETLINK) { log_dump(); log_free(); if (sock != -1) close(sock); } exit(ret); } powerstat-0.01.30/powerstat.80000664000175000017500000000662212312556517014505 0ustar kingking.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH POWERSTAT 8 "23 January, 2014" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME powerstat \- a tool to measure laptop power consumption. .br .SH SYNOPSIS .B powerstat .RI [ \-b ] .RI [ \-d " secs] .RI [ \-h ] .RI [ \-i " idle] .RI [ \-p ] .RI [ \-r ] .RI [ \-s ] .RI [ \-z ] .RI [ delay " [count]] .br .SH DESCRIPTION powerstat is a program that measures the power consumption of a mobile PC that has a battery power souce. The output is like vmstat but also shows power consumption statistics. At the end of a run, powerstat will calculate the average, standard deviation and min/max of the gathered data. Note that running powerstat as root will provide extra information about processes that have fork'd, exec'd and exited. .SH OPTIONS powerstat options are as follow: .TP .B \-b redo a sample measurement if a system is busy, the default for busy is considered less than 98% CPU idle. The CPU idle threshold can be altered using the \-i option. .TP .B \-d specify delay before starting, default is 15 seconds. This gives the machine time to settle down and to dim the laptop display when in idle mode. .TP .B \-h show help. .TP .B \-i specify the idle threshold (in % CPU idle) to force a re-sample measurement if the CPU is less idle than this level. This option implicitly enables the \-b option. .TP .B \-p redo a sample measurement if any processes fork(), exec() or exit(). .TP .B \-r redo if system is not idle and any processes fork(), exec() or exit(), an alias for \-p \-b .TP .B \-s this dumps a log of the process fork(), exec() and exit() activity on completion. .TP .B \-S use standard averaging to calculate power consumption instead of using a 120 second rolling average of capacity samples. This is only useful if the battery reports just capacity values and is an alternative method of calculating the power consumption based on the start and current battery capacity. .TP .B \-z forcibly ignore zero power rate readings from the battery, don't use this unless you know what you are doing. .SH EXAMPLES .LP Measure power with the default of 10 samples with an interval of 10 seconds .RS 8 powerstat .RE .LP Measure power with 60 samples with an interval of 1 second .RS 8 powerstat 1 60 .RE .LP Measure power and redo sampling if we are not idle and we detect fork()/exec()/exit() activity .RS 8 sudo powerstat \-r .RE .LP Measure power and redo sampling if less that 95% idle .RS 8 powerstat \-i 95 .RE .LP Wait to settle for 1 minute then measure power every 20 seconds and show any fork()/exec()/exit() activity at end of the measuring .RS 8 powerstat \-d 60 \-s 20 .RE .SH SEE ALSO .BR vmstat (8), .BR powertop (8) .SH AUTHOR powerstat was written by Colin King .PP This manual page was written by Colin King , for the Ubuntu project (but may be used by others). powerstat-0.01.30/Makefile0000664000175000017500000000127212312556517014020 0ustar kingkingVERSION=0.01.30 CFLAGS += -Wall -Wextra -DVERSION='"$(VERSION)"' BINDIR=/usr/bin MANDIR=/usr/share/man/man8 powerstat: powerstat.o $(CC) $(CFLAGS) $< -lm -o $@ $(LDFLAGS) powerstat.8.gz: powerstat.8 gzip -c $< > $@ dist: rm -rf powerstat-$(VERSION) mkdir powerstat-$(VERSION) cp -rp Makefile powerstat.c powerstat.8 COPYING powerstat-$(VERSION) tar -zcf powerstat-$(VERSION).tar.gz powerstat-$(VERSION) rm -rf powerstat-$(VERSION) clean: rm -f powerstat powerstat.o powerstat.8.gz rm -f powerstat-$(VERSION).tar.gz install: powerstat powerstat.8.gz mkdir -p ${DESTDIR}${BINDIR} cp powerstat ${DESTDIR}${BINDIR} mkdir -p ${DESTDIR}${MANDIR} cp powerstat.8.gz ${DESTDIR}${MANDIR} powerstat-0.01.30/COPYING0000664000175000017500000004325412312556517013421 0ustar kingking GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.