From 391c572f0d73824a507ab1c512794d2897a7bbea Mon Sep 17 00:00:00 2001 From: Brenden Matthews Date: Tue, 7 Aug 2018 11:26:57 -0400 Subject: [PATCH] Reformat, add empty comment. --- src/dragonfly.cc | 2948 +++++++++++++++++++++++---- src/haiku.cc | 2942 +++++++++++++++++++++++++-- src/linux.cc | 5082 +++++++++++++++++++++++----------------------- src/netbsd.cc | 2957 +++++++++++++++++++++++++-- src/openbsd.cc | 2286 ++++++++++++++++++++- 5 files changed, 13004 insertions(+), 3211 deletions(-) diff --git a/src/dragonfly.cc b/src/dragonfly.cc index 7a2fb2d899..8067f88c47 100644 --- a/src/dragonfly.cc +++ b/src/dragonfly.cc @@ -8,7 +8,9 @@ * * Please see COPYING for details * - * Copyright (c) 2011 Andrea Magliano + * Copyright (c) 2007 Toni Spets + * Copyright (c) 2005-2018 Brenden Matthews, Philip Kovacs, et. al. + * (see AUTHORS) * All rights reserved. * * This program is free software: you can redistribute it and/or modify @@ -25,151 +27,166 @@ * */ -#include "config.h" - -#include +#include +#include #include +#include #include #include +#include #include -#include +#include #include #include #include #include +#include #include #include -#include -#include +#include -#include +#include +#include +#include #include #include -#include +#include #include -#include +#include +#include #include "conky.h" #include "diskio.h" -#include "dragonfly.h" #include "logging.h" #include "net_stat.h" +#include "openbsd.h" #include "top.h" -#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var)) -#define KELVTOC(x) ((x - 2732) / 10.0) #define MAXSHOWDEVS 16 +#define LOG1024 10 +#define pagetok(size) ((size) << pageshift) + +inline void proc_find_top(struct process **cpu, struct process **mem); + static short cpu_setup = 0; +static kvm_t *kd = 0; -static int getsysctl(const char *name, void *ptr, size_t len) { - size_t nlen = len; +struct ifmibdata *data = nullptr; +size_t len = 0; - if (sysctlbyname(name, ptr, &nlen, nullptr, 0) == -1) { - fprintf(stderr, "getsysctl(): %s failed '%s'\n", name, strerror(errno)); - return -1; - } +int init_kvm = 0; +int init_sensors = 0; - if (nlen != len && errno == ENOMEM) { - fprintf(stderr, "getsysctl(): %s failed %zu != %zu\n", name, nlen, len); - return -1; +static int kvm_init() { + if (init_kvm) { return 1; } + + kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL); + if (kd == nullptr) { + NORM_ERR("error opening kvm"); + } else { + init_kvm = 1; } - return 0; + return 1; } -static int swapmode(unsigned long *retavail, unsigned long *retfree) { - int total, used; - size_t len = sizeof(int); +/* note: swapmode taken from 'top' source */ +/* swapmode is rewritten by Tobias Weingartner + * to be based on the new swapctl(2) system call. */ +static int swapmode(int *used, int *total) { + struct swapent *swdev; + int nswap, rnswap, i; + + nswap = swapctl(SWAP_NSWAP, 0, 0); + if (nswap == 0) { return 0; } - if (sysctlbyname("vm.swap_size", &total, &len, nullptr, 0) == -1) - perror("vm_swap_usage(): vm.swap_size"); - else if (sysctlbyname("vm.swap_anon_use", &used, &len, nullptr, 0) == -1) - perror("vm_swap_usage(): vm.swap_anon_use"); - else { - int size = getpagesize(); + swdev = malloc(nswap * sizeof(*swdev)); + if (swdev == nullptr) { return 0; } -#define CONVERT(v) ((quad_t)(v) * (size / 1024)) + rnswap = swapctl(SWAP_STATS, swdev, nswap); + if (rnswap == -1) { + free(swdev); + return 0; + } - *retavail = CONVERT(total); - *retfree = CONVERT(total - used); + /* if rnswap != nswap, then what? */ - return (int)((double)used * 100.0 / (double)total); + /* Total things up */ + *total = *used = 0; + for (i = 0; i < nswap; i++) { + if (swdev[i].se_flags & SWF_ENABLE) { + *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE)); + *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE)); + } } - return 0; + free(swdev); + return 1; } -void prepare_update(void) {} +int check_mount(struct text_object *obj) { + /* stub */ + (void)obj; + return 0; +} -int update_uptime(void) { +void update_uptime() { int mib[2] = {CTL_KERN, KERN_BOOTTIME}; struct timeval boottime; time_t now; size_t size = sizeof(boottime); - if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && boottime.tv_sec) { + if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && + (boottime.tv_sec != 0)) { time(&now); info.uptime = now - boottime.tv_sec; } else { - fprintf(stderr, "Could not get uptime\n"); + NORM_ERR("Could not get uptime"); info.uptime = 0; } - - return 0; } -int check_mount(char *s) { - struct statfs *mntbuf; - int i, mntsize; - - mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); - for (i = mntsize - 1; i >= 0; i--) { - if (strcmp(mntbuf[i].f_mntonname, s) == 0) { - return 1; - } +void update_meminfo() { + static int mib[2] = {CTL_VM, VM_METER}; + struct vmtotal vmtotal; + size_t size; + int pagesize, pageshift, swap_avail, swap_used; + + pagesize = getpagesize(); + pageshift = 0; + while (pagesize > 1) { + pageshift++; + pagesize >>= 1; } - return 0; -} - -int update_meminfo(void) { - u_int total_pages, inactive_pages, free_pages; - unsigned long swap_avail, swap_free; - - int pagesize = getpagesize(); - - if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages)) { - fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_page_count\"\n"); - } + /* we only need the amount of log(2)1024 for our conversion */ + pageshift -= LOG1024; - if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages)) { - fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_free_count\"\n"); + /* get total -- systemwide main memory usage structure */ + size = sizeof(vmtotal); + if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) { + warn("sysctl failed"); + bzero(&vmtotal, sizeof(vmtotal)); } - if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages)) { - fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"\n"); - } - - info.memmax = total_pages * (pagesize >> 10); - info.mem = (total_pages - free_pages - inactive_pages) * (pagesize >> 10); + info.memmax = pagetok(vmtotal.t_rm) + pagetok(vmtotal.t_free); + info.mem = info.memwithbuffers = pagetok(vmtotal.t_rm); info.memeasyfree = info.memfree = info.memmax - info.mem; - if ((swapmode(&swap_avail, &swap_free)) >= 0) { + if ((swapmode(&swap_used, &swap_avail)) >= 0) { info.swapmax = swap_avail; - info.swap = (swap_avail - swap_free); - info.swapfree = swap_free; + info.swap = swap_used; + info.swapfree = swap_avail - swap_used; } else { info.swapmax = 0; info.swap = 0; info.swapfree = 0; } - - return 0; } -int update_net_stats(void) { +void update_net_stats() { struct net_stat *ns; double delta; long long r, t, last_recv, last_trans; @@ -178,13 +195,9 @@ int update_net_stats(void) { /* get delta */ delta = current_update_time - last_update_time; - if (delta <= 0.0001) { - return 0; - } + if (delta <= 0.0001) { return; } - if (getifaddrs(&ifap) < 0) { - return 0; - } + if (getifaddrs(&ifap) < 0) { return; } for (ifa = ifap; ifa; ifa = ifa->ifa_next) { ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL); @@ -196,9 +209,7 @@ int update_net_stats(void) { last_recv = ns->recv; last_trans = ns->trans; - if (ifa->ifa_addr->sa_family != AF_LINK) { - continue; - } + if (ifa->ifa_addr->sa_family != AF_LINK) { continue; } for (iftmp = ifa->ifa_next; iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0; @@ -221,7 +232,7 @@ int update_net_stats(void) { ns->last_read_recv = r; if (t < ns->last_read_trans) { - ns->trans += ((long long)4294967295U - ns->last_read_trans) + t; + ns->trans += (long long)4294967295U - ns->last_read_trans + t; } else { ns->trans += (t - ns->last_read_trans); } @@ -237,84 +248,86 @@ int update_net_stats(void) { } freeifaddrs(ifap); - return 0; } -static int kern_proc_all_n() { - size_t len = 0; +int update_total_processes() { + int n_processes; - if (sysctlbyname("kern.proc.all_lwp", nullptr, &len, NULL, 0) == -1) { - perror("kern.proc.all_lwp"); - return -1; - } + kvm_init(); + kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes); - if (len % sizeof(struct kinfo_proc)) { - fprintf(stderr, - "kern_proc(): " - "len %% sizeof(struct kinfo_proc) != 0"); - return -1; - } - - return len / sizeof(struct kinfo_proc); + info.procs = n_processes; } -static struct kinfo_proc *kern_proc_all(size_t proc_n) { - if (proc_n > 0) { - size_t len = proc_n * sizeof(struct kinfo_proc); - struct kinfo_proc *kp = (struct kinfo_proc *)malloc(len); - - if (kp) { - if (sysctlbyname("kern.proc.all_lwp", kp, &len, nullptr, 0) == -1) - perror("kern_proc(): kern.proc.all_lwp"); - else - return kp; - free(kp); - } else - perror("malloc"); - } - return nullptr; -} +void update_running_processes() { + struct kinfo_proc2 *p; + int n_processes; + int i, cnt = 0; -void get_cpu_count(void) { - int cpu_count = 0; + kvm_init(); + int max_size = sizeof(struct kinfo_proc2); - if (GETSYSCTL("hw.ncpu", cpu_count) == 0) { - info.cpu_count = cpu_count; - } else { - fprintf(stderr, "Cannot get hw.ncpu\n"); - info.cpu_count = 0; + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, max_size, &n_processes); + for (i = 0; i < n_processes; i++) { + if (p[i].p_stat == SRUN) { cnt++; } } - info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); - if (info.cpu_usage == nullptr) { - CRIT_ERR(nullptr, NULL, "malloc"); - } + info.run_procs = cnt; } -struct cpu_info { - long oldtotal; - long oldused; +/* new SMP code can be enabled by commenting the following line */ +#define OLDCPU + +#ifdef OLDCPU +struct cpu_load_struct { + unsigned long load[5]; }; -PCPU_STATISTICS_FUNC(cputime, struct kinfo_cputime, uint64_t); +struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}}; +long cpu_used, oldtotal, oldused; +#else +#include +int64_t *fresh = nullptr; + +/* XXX is 8 enough? - What's the constant for MAXCPU? */ +/* allocate this with malloc would be better */ +int64_t oldtotal[8], oldused[8]; +#endif + +void get_cpu_count() { + int cpu_count = 1; /* default to 1 cpu */ +#ifndef OLDCPU + int mib[2] = {CTL_HW, HW_NCPU}; + size_t len = sizeof(cpu_count); -static void stat_cpu(struct cpu_info *cpu, struct kinfo_cputime *percpu, - float *usage) { - long int used = (percpu->cp_user + percpu->cp_nice + percpu->cp_sys + - percpu->cp_intr), - total = used + percpu->cp_idle; + if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) { + NORM_ERR("error getting cpu count, defaulting to 1"); + } +#endif + info.cpu_count = cpu_count; - *usage = (total - cpu->oldtotal) && cpu->oldtotal - ? ((float)(used - cpu->oldused)) / (total - cpu->oldtotal) - : 0; + info.cpu_usage = malloc(info.cpu_count * sizeof(float)); + if (info.cpu_usage == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } - cpu->oldused = used; - cpu->oldtotal = total; +#ifndef OLDCPU + assert(fresh == nullptr); /* XXX Is this leaking memory? */ + /* XXX Where shall I free this? */ + if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) { + CRIT_ERR(nullptr, NULL, "calloc"); + } +#endif } -int update_cpu_usage(void) { - static struct cpu_info *cpu = nullptr; - extern void *global_cpu; +void update_cpu_usage() { +#ifdef OLDCPU + int mib[2] = {CTL_KERN, KERN_CPTIME}; + long used, total; + long cp_time[CPUSTATES]; + size_t len = sizeof(cp_time); +#else + size_t size; + unsigned int i; +#endif /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ if ((cpu_setup == 0) || (!info.cpu_usage)) { @@ -322,225 +335,252 @@ int update_cpu_usage(void) { cpu_setup = 1; } - if (!global_cpu) { - if (!cpu) - cpu = (struct cpu_info *)calloc(sizeof(struct cpu_info), - info.cpu_count + 1); - global_cpu = cpu; +#ifdef OLDCPU + if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) { + NORM_ERR("Cannot get kern.cp_time"); } - { - size_t percpu_n = info.cpu_count * sizeof(struct kinfo_cputime); - struct kinfo_cputime *percpu = (struct kinfo_cputime *)malloc( - info.cpu_count * sizeof(struct kinfo_cputime)); + fresh.load[0] = cp_time[CP_USER]; + fresh.load[1] = cp_time[CP_NICE]; + fresh.load[2] = cp_time[CP_SYS]; + fresh.load[3] = cp_time[CP_IDLE]; + fresh.load[4] = cp_time[CP_IDLE]; - if (percpu) { - if (sysctlbyname("kern.cputime", percpu, &percpu_n, nullptr, 0) == -1 && - errno != ENOMEM) { - printf("update_cpu_usage(): with %d cpu(s) ", info.cpu_count); - perror("kern.cputime"); - } else { - struct kinfo_cputime total; - cputime_pcpu_statistics(&percpu[0], &total, info.cpu_count); + used = fresh.load[0] + fresh.load[1] + fresh.load[2]; + total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3]; - { - int i; - for (i = 0; i < info.cpu_count; i++) - stat_cpu(&cpu[i + 1], &percpu[i], &info.cpu_usage[i + 1]); - } - stat_cpu(&cpu[0], &total, &info.cpu_usage[0]); + if ((total - oldtotal) != 0) { + info.cpu_usage[0] = ((double)(used - oldused)) / (double)(total - oldtotal); + } else { + info.cpu_usage[0] = 0; + } + + oldused = used; + oldtotal = total; +#else + if (info.cpu_count > 1) { + size = CPUSTATES * sizeof(int64_t); + for (i = 0; i < info.cpu_count; i++) { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i}; + if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) < + 0) { + NORM_ERR("sysctl kern.cp_time2 failed"); } - free(percpu); } + } else { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME}; + long cp_time_tmp[CPUSTATES]; + + size = sizeof(cp_time_tmp); + if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) { + NORM_ERR("sysctl kern.cp_time failed"); + } + + for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t)cp_time_tmp[i]; } } - return 0; -} + /* XXX Do sg with this int64_t => long => double ? float hell. */ + for (i = 0; i < info.cpu_count; i++) { + int64_t used, total; + int at = i * CPUSTATES; + + used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; + total = used + fresh[at + CP_IDLE]; + + if ((total - oldtotal[i]) != 0) { + info.cpu_usage[i] = + ((double)(used - oldused[i])) / (double)(total - oldtotal[i]); + } else { + info.cpu_usage[i] = 0; + } -void free_cpu(struct text_object *) { + oldused[i] = used; + oldtotal[i] = total; + } +#endif } -int update_load_average(void) { +void free_cpu(struct text_object *) { /* not used */ } + +void update_load_average() { double v[3]; getloadavg(v, 3); - info.loadavg[0] = (double)v[0]; - info.loadavg[1] = (double)v[1]; - info.loadavg[2] = (double)v[2]; - - return 0; + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; } -double get_acpi_temperature(int fd) { - int temp; - (void)fd; - - if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n"); - return 0.0; - } +#define OBSD_MAX_SENSORS 256 +static struct obsd_sensors_struct { + int device; + float temp[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + unsigned int fan[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + float volt[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; +} obsd_sensors; - return KELVTOC(temp); -} +static conky::simple_config_setting sensor_device("sensor_device", 0, + false); -static void get_battery_stats(int *battime, int *batcapacity, int *batstate, - int *ac) { - if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.time\"\n"); - } - if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.life\"\n"); - } - if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.state\"\n"); - } - if (ac && GETSYSCTL("hw.acpi.acline", *ac)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n"); - } -} +/* read sensors from sysctl */ +void update_obsd_sensors() { + int sensor_cnt, dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0}; + struct sensor sensor; + struct sensordev sensordev; + size_t slen, sdlen; + enum sensor_type type; -void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) { - int battime, batcapacity, batstate, ac; - (void)bat; + slen = sizeof(sensor); + sdlen = sizeof(sensordev); - get_battery_stats(&battime, &batcapacity, &batstate, &ac); + sensor_cnt = 0; - if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7) - fprintf(stderr, "Unknown battery state %d!\n", batstate); - else if (batstate != 1 && ac == 0) - fprintf(stderr, "Battery charging while not on AC!\n"); - else if (batstate == 1 && ac == 1) - fprintf(stderr, "Battery discharing while on AC!\n"); + dev = obsd_sensors.device; // FIXME: read more than one device - switch (item) { - case BATTERY_TIME: - if (batstate == 1 && battime != -1) - snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60); - break; - case BATTERY_STATUS: - if (batstate == 1) // Discharging - snprintf(buf, n, "remaining %d%%", batcapacity); - else - snprintf(buf, n, - batstate == 2 - ? "charging (%d%%)" - : (batstate == 7 ? "absent/on AC" : "charged (%d%%)"), - batcapacity); - break; - default: - fprintf(stderr, "Unknown requested battery stat %d\n", item); + /* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */ + mib[2] = dev; + if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + return; + // continue; } -} + for (type = 0; type < SENSOR_MAX_TYPES; type++) { + mib[3] = type; + for (numt = 0; numt < sensordev.maxnumt[type]; numt++) { + mib[4] = numt; + if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + continue; + } + if (sensor.flags & SENSOR_FINVALID) { continue; } -static int check_bat(const char *bat) { - int batnum, numbatts; - char *endptr; - if (GETSYSCTL("hw.acpi.battery.units", numbatts)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n"); - return -1; - } - if (numbatts <= 0) { - fprintf(stderr, "No battery unit detected\n"); - return -1; - } - if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 || bat == endptr || - batnum > numbatts) { - fprintf(stderr, "Wrong battery unit %s requested\n", bat ? bat : ""); - return -1; + switch (type) { + case SENSOR_TEMP: + obsd_sensors.temp[dev][sensor.numt] = + (sensor.value - 273150000) / 1000000.0; + break; + case SENSOR_FANRPM: + obsd_sensors.fan[dev][sensor.numt] = sensor.value; + break; + case SENSOR_VOLTS_DC: + obsd_sensors.volt[dev][sensor.numt] = sensor.value / 1000000.0; + break; + default: + break; + } + + sensor_cnt++; + } } - return batnum; -} + /* } */ -int get_battery_perct(const char *bat) { - union acpi_battery_ioctl_arg battio; - int batnum, acpifd; - int designcap, lastfulcap, batperct; + init_sensors = 1; +} - if ((battio.unit = batnum = check_bat(bat)) < 0) return 0; - if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) { - fprintf(stderr, "Can't open ACPI device\n"); - return 0; - } - if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) { - fprintf(stderr, "Unable to get info for battery unit %d\n", batnum); - return 0; - } - close(acpifd); - designcap = battio.bif.dcap; - lastfulcap = battio.bif.lfcap; - batperct = (designcap > 0 && lastfulcap > 0) - ? (((float)lastfulcap / designcap) * 100) - : 0; - return batperct > 100 ? 100 : batperct; +void parse_obsd_sensor(struct text_object *obj, const char *arg) { + if (!isdigit((unsigned char)arg[0]) || atoi(&arg[0]) < 0 || + atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) { + obj->data.l = 0; + NORM_ERR("Invalid sensor number!"); + } else + obj->data.l = atoi(&arg[0]); } -double get_battery_perct_bar(struct text_object *obj) { - int batperct = get_battery_perct(obj->data.s); - return batperct * 2.56 - 1; +void print_obsd_sensors_temp(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + temp_print(p, p_max_size, obsd_sensors.temp[obsd_sensors.device][obj->data.l], + TEMP_CELSIUS, 1); } -int open_acpi_temperature(const char *name) { - (void)name; - /* Not applicable for FreeBSD. */ - return 0; +void print_obsd_sensors_fan(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%d", + obsd_sensors.fan[obsd_sensors.device][obj->data.l]); } -void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, - const char *adapter) { - int state; +void print_obsd_sensors_volt(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%.2f", + obsd_sensors.volt[obsd_sensors.device][obj->data.l]); +} - (void)adapter; // only linux uses this +/* chipset vendor */ +void get_obsd_vendor(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char vendor[64]; + size_t size = sizeof(vendor); - if (!p_client_buffer || client_buffer_size <= 0) { - return; - } + (void)obj; - if (GETSYSCTL("hw.acpi.acline", state)) { - fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n"); - return; - } + mib[0] = CTL_HW; + mib[1] = HW_VENDOR; - if (state) { - strncpy(p_client_buffer, "Running on AC Power", client_buffer_size); + if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) { + NORM_ERR("error reading vendor"); + snprintf(buf, client_buffer_size, "%s", "unknown"); } else { - strncpy(p_client_buffer, "Running on battery", client_buffer_size); + snprintf(buf, client_buffer_size, "%s", vendor); } } -void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { - /* not implemented */ - if (p_client_buffer && client_buffer_size > 0) { - memset(p_client_buffer, 0, client_buffer_size); +/* chipset name */ +void get_obsd_product(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char product[64]; + size_t size = sizeof(product); + + (void)obj; + + mib[0] = CTL_HW; + mib[1] = HW_PRODUCT; + + if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) { + NORM_ERR("error reading product"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", product); } } /* void */ char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format, int divisor, unsigned int cpu) { - int64_t freq; + int freq = cpu; + int mib[2] = {CTL_HW, HW_CPUSPEED}; - if (p_client_buffer && client_buffer_size > 0 && p_format && divisor > 0) { - if (GETSYSCTL("hw.tsc_frequency", freq) == 0) { - snprintf(p_client_buffer, client_buffer_size, p_format, - (float)freq / (divisor * 1000000)); - } else { - snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f); - } - return 1; + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; } - return 0; + + size_t size = sizeof(freq); + + if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) { + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + } else { + snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f); + } + + return 1; } #if 0 -void update_wifi_stats(void) +/* deprecated, will rewrite this soon in update_net_stats() -hifi */ +void update_wifi_stats() { - struct ifreq ifr; /* interface stats */ - struct wi_req wireq; struct net_stat *ns; struct ifaddrs *ifap, *ifa; struct ifmediareq ifmr; - int s; + struct ieee80211_nodereq nr; + struct ieee80211_bssid bssid; + int s, ibssid; /* Get iface table */ if (getifaddrs(&ifap) < 0) { @@ -548,7 +588,7 @@ void update_wifi_stats(void) } for (ifa = ifap; ifa; ifa = ifa->ifa_next) { - ns = get_net_stat((const char *) ifa->ifa_name, nullptr, NULL); + ns = get_net_stat((const char *) ifa->ifa_name); s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); @@ -565,21 +605,18 @@ void update_wifi_stats(void) if ((ifmr.ifm_active & IFM_IEEE80211) && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) { /* Get wi status */ - bzero(&ifr, sizeof(ifr)); - strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ); - wireq.wi_type = WI_RID_COMMS_QUALITY; - wireq.wi_len = WI_MAX_DATALEN; - ifr.ifr_data = (void *) &wireq; - - if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) { - perror("ioctl (getting wi status)"); - exit(1); - } - /* wi_val[0] = quality - * wi_val[1] = signal - * wi_val[2] = noise */ - ns->linkstatus = (int) wireq.wi_val[1]; + memset(&bssid, 0, sizeof(bssid)); + strlcpy(bssid.i_name, ifa->ifa_name, sizeof(bssid.i_name)); + ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + + bzero(&nr, sizeof(nr)); + bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); + strlcpy(nr.nr_ifname, ifa->ifa_name, sizeof(nr.nr_ifname)); + + if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { + ns->linkstatus = nr.nr_rssi; + } } cleanup: close(s); @@ -587,141 +624,119 @@ void update_wifi_stats(void) } #endif -int update_diskio(void) { - int devs_count, num_selected, num_selections, dn; - struct device_selection *dev_select = nullptr; - long select_generation; - static struct statinfo statinfo_cur; - char device_name[DEFAULT_TEXT_BUFFER_SIZE]; - struct diskio_stat *cur; - unsigned int reads, writes; - unsigned int total_reads = 0, total_writes = 0; - - memset(&statinfo_cur, 0, sizeof(statinfo_cur)); - statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo)); - stats.current = stats.current_read = stats.current_write = 0; - - if (getdevs(&statinfo_cur) < 0) { - free(statinfo_cur.dinfo); - return 0; - } +void clear_diskio_stats() {} - devs_count = statinfo_cur.dinfo->numdevs; - if (selectdevs(&dev_select, &num_selected, &num_selections, - &select_generation, statinfo_cur.dinfo->generation, - statinfo_cur.dinfo->devices, devs_count, nullptr, 0, NULL, 0, - DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) { - for (dn = 0; dn < devs_count; dn++) { - int di; - struct devstat *dev; - - di = dev_select[dn].position; - dev = &statinfo_cur.dinfo->devices[di]; - snprintf(device_name, DEFAULT_TEXT_BUFFER_SIZE, "%s%d", - dev_select[dn].device_name, dev_select[dn].unit_number); - - total_reads += (reads = dev->bytes_read / 512); - total_writes += (writes = dev->bytes_written / 512); - for (cur = stats.next; cur; cur = cur->next) { - if (cur->dev && !strcmp(device_name, cur->dev)) { - update_diskio_values(cur, reads, writes); - break; - } - } - } - update_diskio_values(&stats, total_reads, total_writes); - - free(dev_select); - } +struct diskio_stat *prepare_diskio_stat(const char *s) {} - free(statinfo_cur.dinfo); - return 0; -} +void update_diskio() { return; /* XXX: implement? hifi: not sure how */ } -static int proc_rusage(struct kinfo_proc *p) { - struct kinfo_lwp *lwp = &p->kp_lwp; - struct rusage *cru = &p->kp_cru; +/* While topless is obviously better, top is also not bad. */ - return (lwp->kl_uticks + lwp->kl_sticks + lwp->kl_iticks) + - (cru->ru_stime.tv_sec + cru->ru_utime.tv_sec) * 1000000; -} +void get_top_info(void) { + struct kinfo_proc2 *p; + struct process *proc; + int n_processes; + int i; -static void proc_count(struct kinfo_proc *kp, size_t proc_n) { - size_t i, act = 0, run = 0; + kvm_init(); - for (i = 0; i < proc_n; i++) { - struct kinfo_proc *p = &kp[i]; + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), + &n_processes); - if (!(p->kp_flags & P_SYSTEM)) { - struct kinfo_lwp *lwp = &p->kp_lwp; + for (i = 0; i < n_processes; i++) { + if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) { + proc = find_process(p[i].p_pid); + if (!proc) proc = new_process(p[i].p_pid); - if (!lwp->kl_tid) act++; - if (lwp->kl_stat == LSRUN) run++; + proc->time_stamp = g_time; + proc->name = strndup(p[i].p_comm, text_buffer_size); + proc->amount = 100.0 * p[i].p_pctcpu / FSCALE; + /* TODO: vsize, rss, total_cpu_time */ } } - - info.procs = act; - info.run_procs = run; } -static void proc_fill(struct kinfo_proc *kp, size_t proc_n) { - size_t i, f = getpagesize(); - static long prev_ticks = 0; /* safe as long as in same thread */ - - for (i = 0; i < proc_n; i++) { - struct kinfo_proc *p = &kp[i]; - struct kinfo_lwp *lwp = &p->kp_lwp; +/* empty stubs so conky links */ +void prepare_update() {} - if (!(p->kp_flags & P_SYSTEM) && p->kp_comm && - *p->kp_comm && /* just to be sure */ - !lwp->kl_tid) { /* 'main' lwp, the real process (observed) */ +int get_entropy_avail(unsigned int *val) { return 1; } - struct process *my = get_process(p->kp_pid); - long ticks = proc_rusage(p); - - my->time_stamp = g_time; +int get_entropy_poolsize(unsigned int *val) { return 1; } +WRITE] / 512); +for (cur = stats.next; cur; cur = cur->next) { + if (cur->dev && !strcmp(device_name, cur->dev)) { + update_diskio_values(cur, reads, writes); + break; + } +} +} +update_diskio_values(&stats, total_reads, total_writes); - free_and_zero(my->name); - my->name = strdup(p->kp_comm); +free(dev_select); +} - my->amount = 100.0 * lwp->kl_pctcpu / FSCALE; - my->vsize = p->kp_vm_map_size; - my->rss = p->kp_vm_rssize * f; +if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); } +free(statinfo_cur.dinfo); +return 0; +} - my->total_cpu_time = ticks - prev_ticks; - prev_ticks = ticks; +/* While topless is obviously better, top is also not bad. */ - // printf("\tmy[%p]: %s(%u) %d %d 0x%x 0x%x %f\n", p, - // my->name, my->pid, my->vsize, my->rss, - // p->kp_flags, lwp->kl_stat, my->amount); +void get_top_info(void) { + struct kinfo_proc *p; + struct process *proc; + int n_processes; + int i; + + std::lock_guard guard(kvm_proc_mutex); + p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) { + proc = get_process(p[i].ki_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; + proc->vsize = p[i].ki_size; + proc->rss = (p[i].ki_rssize * getpagesize()); + /* ki_runtime is in microseconds, total_cpu_time in centiseconds. + * Therefore we divide by 10000. */ + proc->total_cpu_time = p[i].ki_runtime / 10000; } } } -void get_top_info(void) { - size_t proc_n = kern_proc_all_n(); - struct kinfo_proc *kp = kern_proc_all(proc_n); - - if (kp) { - proc_count(kp, proc_n); - proc_fill(kp, proc_n); - free(kp); +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("remaining", buffer, 9)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 9, n - 9); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 12, n - 12); } } -#if defined(i386) || defined(__i386__) -#define APMDEV "/dev/apm" -#define APM_UNKNOWN 255 - -int apm_getinfo(int fd, apm_info_t aip) { - if (ioctl(fd, APMIO_GETINFO, aip) == -1) { - return -1; - } - - return 0; +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; } -char *get_apm_adapter(void) { +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} +et_apm_adapter(void) { int fd; struct apm_info a_info; char *out; @@ -861,3 +876,2072 @@ int get_entropy_poolsize(unsigned int *val) { (void)val; return 1; } + stat_fp) == nullptr) { break; } + + // Do some parsing here to handle skipped cpu numbers. For example, + // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports + // "0,3-7". I assume that chip is really an 8-core die with two cores + // disabled... Presumably you could also get "0,3-4,6", and other + // combos too... + for (str1 = buf;; str1 = nullptr) { + token = strtok_r(str1, ",", &saveptr1); + if (token == nullptr) break; + ++info.cpu_count; + + subtoken1 = -1; + subtoken2 = -1; + for (str2 = token;; str2 = nullptr) { + subtoken = strtok_r(str2, "-", &saveptr2); + if (subtoken == nullptr) break; + if (subtoken1 < 0) + subtoken1 = atoi(subtoken); + else + subtoken2 = atoi(subtoken); + } + if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; + } + } + info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + + fclose(stat_fp); + } + +#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" +#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" + + int update_stat(void) { + FILE *stat_fp; + static int rep = 0; + static struct cpu_info *cpu = nullptr; + char buf[256]; + int i; + unsigned int idx; + double curtmp; + const char *stat_template = nullptr; + unsigned int malloc_cpu_size = 0; + extern void *global_cpu; + + static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; + static double last_stat_update = 0.0; + float cur_total = 0.0; + + /* since we use wrappers for this function, the update machinery + * can't eliminate double invocations of this function. Check for + * them here, otherwise cpu_usage counters are freaking out. */ + pthread_mutex_lock(&last_stat_update_mutex); + if (last_stat_update == current_update_time) { + pthread_mutex_unlock(&last_stat_update_mutex); + return 0; + } + last_stat_update = current_update_time; + pthread_mutex_unlock(&last_stat_update_mutex); + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if (!cpu_setup || !info.cpu_usage) { + get_cpu_count(); + cpu_setup = 1; + } + + if (!stat_template) { + stat_template = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + } + + if (!global_cpu) { + malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); + cpu = (struct cpu_info *)malloc(malloc_cpu_size); + memset(cpu, 0, malloc_cpu_size); + global_cpu = cpu; + } + + if (!(stat_fp = open_file("/proc/stat", &rep))) { + info.run_threads = 0; + if (info.cpu_usage) { + memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); + } + return 0; + } + + idx = 0; + while (!feof(stat_fp)) { + if (fgets(buf, 255, stat_fp) == nullptr) { break; } + + if (strncmp(buf, "procs_running ", 14) == 0) { + sscanf(buf, "%*s %hu", &info.run_threads); + } else if (strncmp(buf, "cpu", 3) == 0) { + double delta; + if (isdigit((unsigned char)buf[3])) { + idx++; // just increment here since the CPU index can skip numbers + } else { + idx = 0; + } + if (idx > info.cpu_count) { continue; } + sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), + &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), + &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), + &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); + + cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + + cpu[idx].cpu_system + cpu[idx].cpu_idle + + cpu[idx].cpu_iowait + cpu[idx].cpu_irq + + cpu[idx].cpu_softirq + cpu[idx].cpu_steal; + + cpu[idx].cpu_active_total = + cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); + + delta = current_update_time - last_update_time; + + if (delta <= 0.001) { break; } + + cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); + if (cur_total == 0.0) { + cpu[idx].cpu_val[0] = 1.0; + } else { + cpu[idx].cpu_val[0] = + (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / + cur_total; + } + curtmp = 0; + + int samples = cpu_avg_samples.get(*state); +#ifdef HAVE_OPENMP +#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } + info.cpu_usage[idx] = curtmp / samples; + + cpu[idx].cpu_last_total = cpu[idx].cpu_total; + cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = samples - 1; i > 0; i--) { + cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; + } + } + } + fclose(stat_fp); + return 0; + } + + int update_running_processes(void) { + update_stat(); + return 0; + } + + int update_cpu_usage(void) { + update_stat(); + return 0; + } + + void free_cpu(struct text_object *) { /* not used */ } + + // fscanf() that reads floats with points even if you are using a locale where + // floats are with commas + int fscanf_no_i18n(FILE *stream, const char *format, ...) { + int returncode; + va_list ap; + +#ifdef BUILD_I18N + const char *oldlocale = setlocale(LC_NUMERIC, nullptr); + + setlocale(LC_NUMERIC, "C"); +#endif + va_start(ap, format); + returncode = vfscanf(stream, format, ap); + va_end(ap); +#ifdef BUILD_I18N + setlocale(LC_NUMERIC, oldlocale); +#endif + return returncode; + } + + int update_load_average(void) { +#ifdef HAVE_GETLOADAVG + if (!prefer_proc) { + double v[3]; + + getloadavg(v, 3); + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; + } else +#endif + { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file("/proc/loadavg", &rep))) { + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + return 0; + } + if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], + &info.loadavg[2]) < 0) + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + fclose(fp); + } + return 0; + } + + /***********************************************************/ + /***********************************************************/ + /***********************************************************/ + + static int no_dots(const struct dirent *d) { + if (d->d_name[0] == '.') { return 0; } + return 1; + } + + static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { + struct dirent **namelist; + int i, n; + + n = scandir(dir, &namelist, no_dots, alphasort); + if (n < 0) { + if (!rep || !*rep) { + NORM_ERR("scandir for %s: %s", dir, strerror(errno)); + if (rep) { *rep = 1; } + } + return 0; + } else { + if (n == 0) { return 0; } + + strncpy(s, namelist[0]->d_name, 255); + s[255] = '\0'; + +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < n; i++) { free(namelist[i]); } + free(namelist); + + return 1; + } + } + + static int open_sysfs_sensor(const char *dir, const char *dev, + const char *type, int n, int *divisor, + char *devtype) { + char path[256]; + char buf[256]; + int fd; + int divfd; + + memset(buf, 0, sizeof(buf)); + + /* if device is nullptr or *, get first */ + if (dev == nullptr || strcmp(dev, "*") == 0) { + static int rep = 0; + + if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } + dev = buf; + } + + if (strcmp(dir, "/sys/class/hwmon/") == 0) { + if (*buf) { + /* buf holds result from get_first_file_in_a_directory() above, + * e.g. "hwmon0" -- append "/device" */ + strncat(buf, "/device", 256); + } else { + /* dev holds device number N as a string, + * e.g. "0", -- convert to "hwmon0/device" */ + sprintf(buf, "hwmon%s/device", dev); + dev = buf; + } + } + + /* change vol to in, tempf to temp */ + if (strcmp(type, "vol") == 0) { + type = "in"; + } else if (strcmp(type, "tempf") == 0) { + type = "temp"; + } else if (strcmp(type, "temp2") == 0) { + type = "temp"; + } + + /* construct path */ + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + + /* first, attempt to open file in /device */ + fd = open(path, O_RDONLY); + if (fd < 0) { + /* if it fails, strip the /device from dev and attempt again */ + buf[strlen(buf) - 7] = 0; + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + fd = open(path, O_RDONLY); + if (fd < 0) { + NORM_ERR( + "can't open '%s': %s\nplease check your device or remove this " + "var from " PACKAGE_NAME, + path, strerror(errno)); + } + } + + strncpy(devtype, path, 255); + + if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || + strcmp(type, "tempf") == 0) { + *divisor = 1; + } else { + *divisor = 0; + } + /* fan does not use *_div as a read divisor */ + if (strcmp("fan", type) == 0) { return fd; } + + /* test if *_div file exist, open it and use it as divisor */ + if (strcmp(type, "tempf") == 0) { + snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + } else { + snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + } + + divfd = open(path, O_RDONLY); + if (divfd > 0) { + /* read integer */ + char divbuf[64]; + int divn; + + divn = read(divfd, divbuf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (divn < 0) { + NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); + } else { + divbuf[divn] = '\0'; + *divisor = atoi(divbuf); + } + close(divfd); + } + + return fd; + } + + static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { + int val = 0; + + if (*fd <= 0) { return 0; } + + lseek(*fd, 0, SEEK_SET); + + /* read integer */ + { + char buf[64]; + int n; + n = read(*fd, buf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (n < 0) { + NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); + } else { + buf[n] = '\0'; + val = atoi(buf); + } + } + + close(*fd); + /* open file */ + *fd = open(devtype, O_RDONLY); + if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } + + /* My dirty hack for computing CPU value + * Filedil, from forums.gentoo.org */ + /* if (strstr(devtype, "temp1_input") != nullptr) { + return -15.096 + 1.4893 * (val / 1000.0); + } */ + + /* divide voltage and temperature by 1000 */ + /* or if any other divisor is given, use that */ + if (0 == (strcmp(type, "temp2"))) { + temp2 = "temp2"; + } else { + temp2 = "empty"; + } + if (strcmp(type, "tempf") == 0) { + if (divisor > 1) { + return ((val / divisor + 40) * 9.0 / 5) - 40; + } else if (divisor) { + return ((val / 1000.0 + 40) * 9.0 / 5) - 40; + } else { + return ((val + 40) * 9.0 / 5) - 40; + } + } else { + if (divisor > 1) { + return val / divisor; + } else if (divisor) { + return val / 1000.0; + } else { + return val; + } + } + } + +#define HWMON_RESET() \ + { \ + buf1[0] = 0; \ + factor = 1.0; \ + offset = 0.0; \ + } + + static void parse_sysfs_sensor(struct text_object *obj, const char *arg, + const char *path, const char *type) { + char buf1[64], buf2[64]; + float factor, offset; + int n, found = 0; + struct sysfs *sf; + + if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) + found = 1; + else + HWMON_RESET(); + if (!found && + sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) + found = 1; + else if (!found) + HWMON_RESET(); + + if (!found) { + obj_be_plain_text(obj, "fail"); + return; + } + DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, + offset); + sf = (struct sysfs *)malloc(sizeof(struct sysfs)); + memset(sf, 0, sizeof(struct sysfs)); + sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, + sf->devtype); + strncpy(sf->type, buf2, 63); + sf->factor = factor; + sf->offset = offset; + obj->data.opaque = sf; + } + +#define PARSER_GENERATOR(name, path) \ + void parse_##name##_sensor(struct text_object *obj, const char *arg) { \ + parse_sysfs_sensor(obj, arg, path, #name); \ + } + + PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") + PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") + PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") + + void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { + double r; + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf || sf->fd < 0) return; + + r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); + + r = r * sf->factor + sf->offset; + + if (0 == (strcmp(temp2, "temp2"))) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); + } else if (!strncmp(sf->type, "temp", 4)) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); + } else if (r >= 100.0 || r == 0) { + snprintf(p, p_max_size, "%d", (int)r); + } else { + snprintf(p, p_max_size, "%.1f", r); + } + } + + void free_sysfs_sensor(struct text_object *obj) { + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf) return; + + if (sf->fd >= 0) close(sf->fd); + free_and_zero(obj->data.opaque); + } + +#define CPUFREQ_PREFIX "/sys/devices/system/cpu" +#define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq" + + /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ + char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + static int rep = 0; + char frequency[32]; + char s[256]; + double freq = 0; + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + if (!prefer_proc) { + char current_freq_file[128]; + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, + CPUFREQ_POSTFIX); + f = fopen(current_freq_file, "r"); + if (f) { + /* if there's a cpufreq /sys node, read the current frequency from + * this node and divide by 1000 to get Mhz. */ + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (freq / 1000) / divisor); + return 1; + } + } + + // open the CPU information file + f = open_file("/proc/cpuinfo", &rep); + if (!f) { + perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); + return 0; + } + + // read the file + while (fgets(s, sizeof(s), f) != nullptr) { +#if defined(__i386) || defined(__x86_64) + // and search for the cpu mhz + if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { +#else +#if defined(__alpha) + // different on alpha + if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { +#else + // this is different on ppc for some reason + if (strncmp(s, "clock", 5) == 0 && cpu == 0) { +#endif // defined(__alpha) +#endif // defined(__i386) || defined(__x86_64) + + // copy just the number + strncpy(frequency, strchr(s, ':') + 2, 32); +#if defined(__alpha) + // strip " est.\n" + frequency[strlen(frequency) - 6] = '\0'; + // kernel reports in Hz + freq = strtod(frequency, nullptr) / 1000000; +#else + // strip \n + frequency[strlen(frequency) - 1] = '\0'; + freq = strtod(frequency, nullptr); +#endif + break; + } + if (strncmp(s, "processor", 9) == 0) { + cpu--; + continue; + } + } + + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + return 1; + } + +#define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages" + + /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something + * like this: + # frequency voltage + 1800000 1340 + 1600000 1292 + 1400000 1100 + 1200000 988 + 1000000 1116 + 800000 1004 + 600000 988 + * Peter Tarjan (ptarjan@citromail.hu) */ + + /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ + static char get_voltage(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + char s[256]; + int freq = 0; + int voltage = 0; + char current_freq_file[128]; + int freq_comp = 0; + + /* build the voltage file name */ + cpu--; + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_POSTFIX); + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + /* read the current cpu frequency from the /sys node */ + f = fopen(current_freq_file, "r"); + if (f) { + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_VOLTAGE); + + /* use the current cpu frequency to find the corresponding voltage */ + f = fopen(current_freq_file, "r"); + + if (f) { + while (!feof(f)) { + char line[256]; + + if (fgets(line, 255, f) == nullptr) { break; } + sscanf(line, "%d %d", &freq_comp, &voltage); + if (freq_comp == freq) { break; } + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)voltage / divisor); + return 1; + } + + void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } + } + + void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } + } + +#define ACPI_FAN_DIR "/proc/acpi/fan/" + + void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { + static int rep = 0; + char buf[256]; + char buf2[256]; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "can't open fan's state file"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + +#define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply" +#define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/" + /* Linux 2.6.25 onwards ac adapter info is in + /sys/class/power_supply/AC/ + On my system I get the following. + /sys/class/power_supply/AC/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=ac + POWER_SUPPLY_NAME=AC + POWER_SUPPLY_TYPE=Mains + POWER_SUPPLY_ONLINE=1 + + Update: it seems the folder name is hardware-dependent. We add an aditional + adapter argument, specifying the folder name. + + Update: on some systems it's /sys/class/power_supply/ADP1 instead of + /sys/class/power_supply/AC + */ + + void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, + const char *adapter) { + static int rep = 0; + + char buf[256]; + char buf2[256]; + struct stat sb; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + if (adapter) + snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, + adapter); + else { + snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); + if (stat(buf2, &sb) == -1) + snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); + } + if (stat(buf2, &sb) == 0) + fp = open_file(buf2, &rep); + else + fp = 0; + if (fp) { + /* sysfs processing */ + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { + int online = 0; + sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); + snprintf(p_client_buffer, client_buffer_size, "%s-line", + (online ? "on" : "off")); + break; + } + } + fclose(fp); + } else { + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "No ac adapter found.... where is it?"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + } + + /* + /proc/acpi/thermal_zone/THRM/cooling_mode + cooling mode: active + /proc/acpi/thermal_zone/THRM/polling_frequency + + /proc/acpi/thermal_zone/THRM/state + state: ok + /proc/acpi/thermal_zone/THRM/temperature + temperature: 45 C + /proc/acpi/thermal_zone/THRM/trip_points + critical (S5): 73 C + passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 + */ + +#define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0" +#define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp" + + int open_acpi_temperature(const char *name) { + char path[256]; + int fd; + + if (name == nullptr || strcmp(name, "*") == 0) { + snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); + } else { + snprintf(path, 255, ACPI_THERMAL_FORMAT, name); + } + + fd = open(path, O_RDONLY); + if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } + + return fd; + } + + static double last_acpi_temp; + static double last_acpi_temp_time; + + // the maximum length of the string inside a ACPI_THERMAL_FORMAT file including + // the ending 0 +#define MAXTHERMZONELEN 6 + + double get_acpi_temperature(int fd) { + if (fd <= 0) { return 0; } + + /* don't update acpi temperature too often */ + if (current_update_time - last_acpi_temp_time < 11.32) { + return last_acpi_temp; + } + last_acpi_temp_time = current_update_time; + + /* seek to beginning */ + lseek(fd, 0, SEEK_SET); + + /* read */ + { + char buf[MAXTHERMZONELEN]; + int n; + + n = read(fd, buf, MAXTHERMZONELEN - 1); + if (n < 0) { + NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); + } else { + buf[n] = '\0'; + sscanf(buf, "%lf", &last_acpi_temp); + last_acpi_temp /= 1000; + } + } + + return last_acpi_temp; + } + + /* + hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info + present: yes + design capacity: 4400 mAh + last full capacity: 4064 mAh + battery technology: rechargeable + design voltage: 14800 mV + design capacity warning: 300 mAh + design capacity low: 200 mAh + capacity granularity 1: 32 mAh + capacity granularity 2: 32 mAh + model number: 02KT + serial number: 16922 + battery type: LION + OEM info: SANYO + */ + + /* + hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state + present: yes + capacity state: ok + charging state: unknown + present rate: 0 mA + remaining capacity: 4064 mAh + present voltage: 16608 mV + */ + + /* + 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? + 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) + 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? + + 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman + verkkovirtaa 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? + verkkovirralla + + 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja + monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? + monitori p��ll� mutta ilman verkkovirtaa + */ + + /* Kapil Hari Paranjape + Linux 2.6.24 onwards battery info is in + /sys/class/power_supply/BAT0/ + On my system I get the following. + /sys/class/power_supply/BAT0/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=battery + POWER_SUPPLY_NAME=BAT0 + POWER_SUPPLY_TYPE=Battery + POWER_SUPPLY_STATUS=Discharging + POWER_SUPPLY_PRESENT=1 + POWER_SUPPLY_TECHNOLOGY=Li-ion + POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 + POWER_SUPPLY_VOLTAGE_NOW=10780000 + POWER_SUPPLY_CURRENT_NOW=13970000 + POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 + POWER_SUPPLY_ENERGY_FULL=27370000 + POWER_SUPPLY_ENERGY_NOW=11810000 + POWER_SUPPLY_MODEL_NAME=IBM-92P1060 + POWER_SUPPLY_MANUFACTURER=Panasonic + On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* + */ + + /* Tiago Marques Vale + Regarding the comment above, since kernel 2.6.36.1 I have + POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW + See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 + */ + +#define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply" +#define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" +#define APM_PATH "/proc/apm" +#define MAX_BATTERY_COUNT 4 + + static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + + static int batteries_initialized = 0; + static char batteries[MAX_BATTERY_COUNT][32]; + + static int acpi_last_full[MAX_BATTERY_COUNT]; + static int acpi_design_capacity[MAX_BATTERY_COUNT]; + + /* e.g. "charging 75%" */ + static char last_battery_str[MAX_BATTERY_COUNT][64]; + /* e.g. "3h 15m" */ + static char last_battery_time_str[MAX_BATTERY_COUNT][64]; + + static double last_battery_time[MAX_BATTERY_COUNT]; + + static int last_battery_perct[MAX_BATTERY_COUNT]; + static double last_battery_perct_time[MAX_BATTERY_COUNT]; + + void init_batteries(void) { + int idx; + + if (batteries_initialized) { return; } +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } + batteries_initialized = 1; + } + + int get_battery_idx(const char *bat) { + int idx; + + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } + } + + /* if not found, enter a new entry */ + if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } + + return idx; + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx); + + void get_battery_stuff(char *buffer, unsigned int n, const char *bat, + int item) { + static int idx, rep = 0, rep1 = 0, rep2 = 0; + char acpi_path[128]; + char sysfs_path[128]; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + init_batteries(); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_time[idx] < 29.5) { + set_return_value(buffer, n, item, idx); + return; + } + + last_battery_time[idx] = current_update_time; + + memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); + memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); + + /* first try SYSFS if that fails try ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep1); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[4]; + + strncpy(charging_state, "unknown", 64); + + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + /* let's just hope units are ok */ + if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) + strncpy(present, "yes", 4); + else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) + strncpy(present, "no", 4); + else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) + sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); + /* present_rate is not the same as the current flowing now but it + * is the same value which was used in the past. so we continue the + * tradition! */ + else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) + sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) + acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ + + /* not present */ + if (strcmp(present, "No") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + } + /* charging */ + else if (strcmp(charging_state, "Charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)(acpi_last_full[idx] - remaining_capacity) / + present_rate) * + 3600)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* discharging */ + else if (strncmp(charging_state, "Discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 1h 12m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)remaining_capacity / present_rate) * 3600)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "full"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* charged */ + /* thanks to Lukas Zapletal */ + else if (strncmp(charging_state, "Charged", 64) == 0 || + strncmp(charging_state, "Full", 64) == 0) { + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one + * being charged. */ + if (remaining_capacity == 0) + strncpy(last_battery_str[idx], "empty", 64); + else + strncpy(last_battery_str[idx], "charged", 64); + } + /* unknown, probably full / AC */ + else { + if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) + snprintf( + last_battery_str[idx], 64, "unknown %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + else + strncpy(last_battery_str[idx], "not present", 64); + } + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[5]; + + /* read last full capacity if it's zero */ + if (acpi_last_full[idx] == 0) { + static int rep3 = 0; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep3); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { + break; + } + } + + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + strncpy(charging_state, "unknown", 8); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + /* let's just hope units are ok */ + if (strncmp(buf, "present:", 8) == 0) { + sscanf(buf, "present: %4s", present); + } else if (strncmp(buf, "charging state:", 15) == 0) { + sscanf(buf, "charging state: %63s", charging_state); + } else if (strncmp(buf, "present rate:", 13) == 0) { + sscanf(buf, "present rate: %d", &present_rate); + } else if (strncmp(buf, "remaining capacity:", 19) == 0) { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) { + /* normalize to 100% */ + acpi_last_full[idx] = remaining_capacity; + } + + /* not present */ + if (strcmp(present, "no") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + /* charging */ + } else if (strcmp(charging_state, "charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / + present_rate)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* discharging */ + } else if (strncmp(charging_state, "discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 1h 12m */ + format_seconds(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, + (long)((remaining_capacity * 3600) / present_rate)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charged"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* charged */ + } else if (strncmp(charging_state, "charged", 64) == 0) { + /* thanks to Lukas Zapletal */ + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one being charged. */ + if (remaining_capacity == 0) { + strncpy(last_battery_str[idx], "empty", 6); + } else { + strncpy(last_battery_str[idx], "charged", 8); + } + /* unknown, probably full / AC */ + } else { + if (strncmp(charging_state, "Full", 64) == 0) { + strncpy(last_battery_str[idx], "charged", 64); + } else if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) { + snprintf(last_battery_str[idx], 64, "unknown %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + } else { + strncpy(last_battery_str[idx], "not present", 64); + } + } + fclose(acpi_bat_fp[idx]); + acpi_bat_fp[idx] = nullptr; + } else { + /* APM */ + if (apm_bat_fp[idx] == nullptr) { + apm_bat_fp[idx] = open_file(APM_PATH, &rep2); + } + + if (apm_bat_fp[idx] != nullptr) { + unsigned int ac, status, flag; + int life; + + if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, + &status, &flag, &life) <= 0) + goto read_bat_fp_end; + + if (life == -1) { + /* could check now that there is ac */ + snprintf(last_battery_str[idx], 64, "%s", "not present"); + + /* could check that status == 3 here? */ + } else if (ac && life != 100) { + snprintf(last_battery_str[idx], 64, "charging %d%%", life); + } else { + snprintf(last_battery_str[idx], 64, "%d%%", life); + } + + read_bat_fp_end: + /* it seemed to buffer it so file must be closed (or could use + * syscalls directly but I don't feel like coding it now) */ + fclose(apm_bat_fp[idx]); + apm_bat_fp[idx] = nullptr; + } + } + set_return_value(buffer, n, item, idx); + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx) { + switch (item) { + case BATTERY_STATUS: + snprintf(buffer, n, "%s", last_battery_str[idx]); + break; + case BATTERY_TIME: + snprintf(buffer, n, "%s", last_battery_time_str[idx]); + break; + default: + break; + } + } + + void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("not present", buffer, 11)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("empty", buffer, 5)) { + buffer[0] = 'E'; + memmove(buffer + 1, buffer + 5, n - 5); + } else if (0 == strncmp("unknown", buffer, 7)) { + buffer[0] = 'U'; + memmove(buffer + 1, buffer + 7, n - 7); + } + // Otherwise, don't shorten. + } + + int _get_battery_perct(const char *bat) { + static int rep = 0; + int idx; + char acpi_path[128]; + char sysfs_path[128]; + int remaining_capacity = -1; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_perct_time[idx] < 30) { + return last_battery_perct[idx]; + } + last_battery_perct_time[idx] = current_update_time; + + /* Only check for SYSFS or ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + rep = 0; + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); + } + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + /* read last full capacity if it's zero */ + if (acpi_design_capacity[idx] == 0) { + static int rep2; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep2); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", + &acpi_design_capacity[idx]) != 0) { + break; + } + } + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + if (buf[0] == 'r') { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + } + if (remaining_capacity < 0) { return 0; } + /* compute the battery percentage */ + last_battery_perct[idx] = + (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); + if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; + return last_battery_perct[idx]; + } + + int get_battery_perct(const char *bat) { + int idx, n = 0, total_capacity = 0, remaining_capacity; + ; +#define BATTERY_LEN 8 + char battery[BATTERY_LEN]; + + init_batteries(); + + /* Check if user asked for the mean percentage of all batteries. */ + if (!strcmp(bat, "all")) { + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); +#undef BATTERY_LEN + remaining_capacity = _get_battery_perct(battery); + if (remaining_capacity > 0) { + total_capacity += remaining_capacity; + n++; + } + } + + if (n == 0) + return 0; + else + return total_capacity / n; + } else { + return _get_battery_perct(bat); + } + } + + double get_battery_perct_bar(struct text_object *obj) { + int idx; + + get_battery_perct(obj->data.s); + idx = get_battery_idx(obj->data.s); + return last_battery_perct[idx]; + } + + /* On Apple powerbook and ibook: + $ cat /proc/pmu/battery_0 + flags : 00000013 + charge : 3623 + max_charge : 3720 + current : 388 + voltage : 16787 + time rem. : 900 + $ cat /proc/pmu/info + PMU driver version : 2 + PMU firmware version : 0c + AC Power : 1 + Battery count : 1 + */ + + /* defines as in */ +#define PMU_BATT_PRESENT 0x00000001 +#define PMU_BATT_CHARGING 0x00000002 + + static FILE *pmu_battery_fp; + static FILE *pmu_info_fp; + static char pb_battery_info[3][32]; + static double pb_battery_info_update; + +#define PMU_PATH "/proc/pmu" + void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { + static int rep = 0; + const char *batt_path = PMU_PATH "/battery_0"; + const char *info_path = PMU_PATH "/info"; + unsigned int flags = 0; + int charge = 0; + int max_charge = 1; + int ac = -1; + long timeval = -1; + + /* don't update battery too often */ + if (current_update_time - pb_battery_info_update < 29.5) { + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + return; + } + pb_battery_info_update = current_update_time; + + if (pmu_battery_fp == nullptr) { + pmu_battery_fp = open_file(batt_path, &rep); + if (pmu_battery_fp == nullptr) { return; } + } + + if (pmu_battery_fp != nullptr) { + rewind(pmu_battery_fp); + while (!feof(pmu_battery_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } + + if (buf[0] == 'f') { + sscanf(buf, "flags : %8x", &flags); + } else if (buf[0] == 'c' && buf[1] == 'h') { + sscanf(buf, "charge : %d", &charge); + } else if (buf[0] == 'm') { + sscanf(buf, "max_charge : %d", &max_charge); + } else if (buf[0] == 't') { + sscanf(buf, "time rem. : %ld", &timeval); + } + } + } + if (pmu_info_fp == nullptr) { + pmu_info_fp = open_file(info_path, &rep); + if (pmu_info_fp == nullptr) { return; } + } + + if (pmu_info_fp != nullptr) { + rewind(pmu_info_fp); + while (!feof(pmu_info_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } + if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } + } + } + /* update status string */ + if ((ac && !(flags & PMU_BATT_PRESENT))) { + strncpy(pb_battery_info[PB_BATT_STATUS], "AC", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if (ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charged", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else { + strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } + + /* update percentage string */ + if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); + } else if (timeval == 0) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); + } else { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", + (charge * 100) / max_charge); + } + + /* update time string */ + if (timeval == 0) { /* fully charged or battery not present */ + snprintf(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); + } else if (timeval < 60 * 60) { /* don't show secs */ + format_seconds_short(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } else { + format_seconds(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } + + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + } + +#define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail" + + int get_entropy_avail(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + +#define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize" + + int get_entropy_poolsize(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + + void print_disk_protect_queue(struct text_object *obj, char *p, + int p_max_size) { + FILE *fp; + char path[128]; + int state; + + snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); + if (access(path, F_OK)) { + snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); + } + if ((fp = fopen(path, "r")) == nullptr) { + snprintf(p, p_max_size, "%s", "n/a "); + return; + } + if (fscanf(fp, "%d\n", &state) != 1) { + fclose(fp); + snprintf(p, p_max_size, "%s", "failed"); + return; + } + fclose(fp); + snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); + } + + std::unordered_map dev_list; + + /* Same as sf #2942117 but memoized using a linked list */ + int is_disk(char *dev) { + std::string orig(dev); + std::string syspath("/sys/block/"); + char *slash; + + auto i = dev_list.find(orig); + if (i != dev_list.end()) return i->second; + + while ((slash = strchr(dev, '/'))) *slash = '!'; + syspath += dev; + + return dev_list[orig] = !(access(syspath.c_str(), F_OK)); + } + + int update_diskio(void) { + FILE *fp; + static int rep = 0; + char buf[512], devbuf[64]; + unsigned int major, minor; + int col_count = 0; + struct diskio_stat *cur; + unsigned int reads, writes; + unsigned int total_reads = 0, total_writes = 0; + + stats.current = 0; + stats.current_read = 0; + stats.current_write = 0; + + if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } + + /* read reads and writes from all disks (minor = 0), including cd-roms + * and floppies, and sum them up */ + while (fgets(buf, 512, fp)) { + col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, + &minor, devbuf, &reads, &writes); + /* ignore subdevices (they have only 3 matching entries in their line) + * and virtual devices (LVM, network block devices, RAM disks, Loopback) + * + * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ + if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && + major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { + /* check needed for kernel >= 2.6.31, see sf #2942117 */ + if (is_disk(devbuf)) { + total_reads += reads; + total_writes += writes; + } + } else { + col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, + &reads, &writes); + if (col_count != 5) { continue; } + } + cur = stats.next; + while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; + + if (cur) update_diskio_values(cur, reads, writes); + } + update_diskio_values(&stats, total_reads, total_writes); + fclose(fp); + return 0; + } + + void print_distribution(struct text_object *obj, char *p, int p_max_size) { + (void)obj; + int i, bytes_read; + char *buf; + struct stat sb; + + if (stat("/etc/arch-release", &sb) == 0) { + snprintf(p, p_max_size, "%s", "Arch Linux"); + return; + } + snprintf(p, p_max_size, "Unknown"); + buf = readfile("/proc/version", &bytes_read, 1); + if (buf) { + /* I am assuming the distribution name is the first string in /proc/version + that: + - is preceded by a '(' + - starts with a capital + - is followed by a space and a number + but i am not sure if this is always true... */ + for (i = 1; i < bytes_read; i++) { + if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; + } + if (i < bytes_read) { + snprintf(p, p_max_size, "%s", &buf[i]); + for (i = 1; p[i]; i++) { + if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { + p[i - 1] = 0; + break; + } + } + } + free(buf); + } + } + + /****************************************** + * Calculate cpu total * + ******************************************/ +#define TMPL_SHORTPROC "%*s %llu %llu %llu %llu" +#define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu" + + static unsigned long long calc_cpu_total(void) { + static unsigned long long previous_total = 0; + unsigned long long total = 0; + unsigned long long t = 0; + int rc; + int ps; + char line[BUFFER_LEN] = {0}; + unsigned long long cpu = 0; + unsigned long long niceval = 0; + unsigned long long systemval = 0; + unsigned long long idle = 0; + unsigned long long iowait = 0; + unsigned long long irq = 0; + unsigned long long softirq = 0; + unsigned long long steal = 0; + const char *template_ = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; + + ps = open("/proc/stat", O_RDONLY); + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return 0; } + + sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, + &softirq, &steal); + total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; + + t = total - previous_total; + previous_total = total; + + return t; + } + + /****************************************** + * Calculate each processes cpu * + ******************************************/ + + inline static void calc_cpu_each(unsigned long long total) { + float mul = 100.0; + if (top_cpu_separate.get(*state)) mul *= info.cpu_count; + + for (struct process *p = first_process; p; p = p->next) + p->amount = mul * (p->user_time + p->kernel_time) / (float)total; + } + +#ifdef BUILD_IOSTATS + static void calc_io_each(void) { + struct process *p; + unsigned long long sum = 0; + + for (p = first_process; p; p = p->next) + sum += p->read_bytes + p->write_bytes; + + if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ + for (p = first_process; p; p = p->next) + p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Extract information from /proc * + ******************************************/ + +#define PROCFS_TEMPLATE "/proc/%d/stat" +#define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline" + + /* These are the guts that extract information out of /proc. + * Anyone hoping to port wmtop should look here first. */ + static void process_parse_stat(struct process *process) { + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; + char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], + cmdline_procname[BUFFER_LEN]; + char basename[BUFFER_LEN] = {0}; + char tmpstr[BUFFER_LEN] = {0}; + char state[4]; + int ps, cmdline_ps; + unsigned long user_time = 0; + unsigned long kernel_time = 0; + int rc; + char *r, *q; + int endl; + int nice_val; + char *lparen, *rparen; + struct stat process_stat; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); + snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, + process->pid); + + ps = open(filename, O_RDONLY); + if (ps == -1) { + /* The process must have finished in the last few jiffies! */ + return; + } + + if (fstat(ps, &process_stat) != 0) { + close(ps); + return; + } + process->uid = process_stat.st_uid; + + /* Mark process as up-to-date. */ + process->time_stamp = g_time; + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + /* Read /proc//cmdline */ + cmdline_ps = open(cmdline_filename, O_RDONLY); + if (cmdline_ps < 0) { + /* The process must have finished in the last few jiffies! */ + return; + } + + endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); + close(cmdline_ps); + if (endl < 0) { return; } + + /* Some processes have null-separated arguments (see proc(5)); let's fix it + */ + int i = endl; + while (i && cmdline[i - 1] == 0) { + /* Skip past any trailing null characters */ + --i; + } + while (i--) { + /* Replace null character between arguments with a space */ + if (cmdline[i] == 0) { cmdline[i] = ' '; } + } + + cmdline[endl] = 0; + + /* We want to transform for example "/usr/bin/python program.py" to "python + * program.py" + * 1. search for first space + * 2. search for last / before first space + * 3. copy string from its position + */ + char *space_ptr = strchr(cmdline, ' '); + if (space_ptr == nullptr) { + strncpy(tmpstr, cmdline, BUFFER_LEN); + } else { + long int space_pos = space_ptr - cmdline; + strncpy(tmpstr, cmdline, space_pos); + tmpstr[space_pos] = 0; + } + + char *slash_ptr = strrchr(tmpstr, '/'); + if (slash_ptr == nullptr) { + strncpy(cmdline_procname, cmdline, BUFFER_LEN); + } else { + long int slash_pos = slash_ptr - tmpstr; + strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); + cmdline_procname[BUFFER_LEN - slash_pos] = 0; + } + + /* Extract cpu times from data in /proc filesystem */ + lparen = strchr(line, '('); + rparen = strrchr(line, ')'); + if (!lparen || !rparen || rparen < lparen) return; // this should not happen + + rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); + strncpy(procname, lparen + 1, rc); + procname[rc] = '\0'; + strncpy(basename, procname, strlen(procname) + 1); + + if (strlen(procname) < strlen(cmdline_procname)) + strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); + + rc = sscanf(rparen + 1, + "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " + "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", + state, &process->user_time, &process->kernel_time, &nice_val, + &process->vsize, &process->rss); + if (rc < 6) { + NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); + return; + } + + if (state[0] == 'R') ++info.run_procs; + + free_and_zero(process->name); + free_and_zero(process->basename); + process->name = strndup(procname, text_buffer_size.get(*::state)); + process->basename = strndup(basename, text_buffer_size.get(*::state)); + process->rss *= getpagesize(); + + process->total_cpu_time = process->user_time + process->kernel_time; + if (process->previous_user_time == ULONG_MAX) { + process->previous_user_time = process->user_time; + } + if (process->previous_kernel_time == ULONG_MAX) { + process->previous_kernel_time = process->kernel_time; + } + + /* strangely, the values aren't monotonous */ + if (process->previous_user_time > process->user_time) + process->previous_user_time = process->user_time; + + if (process->previous_kernel_time > process->kernel_time) + process->previous_kernel_time = process->kernel_time; + + /* store the difference of the user_time */ + user_time = process->user_time - process->previous_user_time; + kernel_time = process->kernel_time - process->previous_kernel_time; + + /* backup the process->user_time for next time around */ + process->previous_user_time = process->user_time; + process->previous_kernel_time = process->kernel_time; + + /* store only the difference of the user_time here... */ + process->user_time = user_time; + process->kernel_time = kernel_time; + } + +#ifdef BUILD_IOSTATS +#define PROCFS_TEMPLATE_IO "/proc/%d/io" + static void process_parse_io(struct process *process) { + static const char *read_bytes_str = "read_bytes:"; + static const char *write_bytes_str = "write_bytes:"; + + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; + int ps; + int rc; + char *pos, *endpos; + unsigned long long read_bytes, write_bytes; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); + + ps = open(filename, O_RDONLY); + if (ps < 0) { + /* The process must have finished in the last few jiffies! + * Or, the kernel doesn't support I/O accounting. + */ + return; + } + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + pos = strstr(line, read_bytes_str); + if (pos == nullptr) { + /* these should not happen (unless the format of the file changes) */ + return; + } + pos += strlen(read_bytes_str); + process->read_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + pos = strstr(line, write_bytes_str); + if (pos == nullptr) { return; } + pos += strlen(write_bytes_str); + process->write_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + if (process->previous_read_bytes == ULLONG_MAX) { + process->previous_read_bytes = process->read_bytes; + } + if (process->previous_write_bytes == ULLONG_MAX) { + process->previous_write_bytes = process->write_bytes; + } + + /* store the difference of the byte counts */ + read_bytes = process->read_bytes - process->previous_read_bytes; + write_bytes = process->write_bytes - process->previous_write_bytes; + + /* backup the counts for next time around */ + process->previous_read_bytes = process->read_bytes; + process->previous_write_bytes = process->write_bytes; + + /* store only the difference here... */ + process->read_bytes = read_bytes; + process->write_bytes = write_bytes; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Get process structure for process pid * + ******************************************/ + + /* This function seems to hog all of the CPU time. + * I can't figure out why - it doesn't do much. */ + static void calculate_stats(struct process *process) { + /* compute each process cpu usage by reading /proc//stat */ + process_parse_stat(process); + +#ifdef BUILD_IOSTATS + process_parse_io(process); +#endif /* BUILD_IOSTATS */ + + /* + * Check name against the exclusion list + */ + /* if (process->counted && exclusion_expression && + * !regexec(exclusion_expression, process->name, 0, 0, 0)) + * process->counted = 0; */ + } + + /****************************************** + * Update process table * + ******************************************/ + + static void update_process_table(void) { + DIR *dir; + struct dirent *entry; + + if (!(dir = opendir("/proc"))) { return; } + + info.run_procs = 0; + + /* Get list of processes from /proc directory */ + while ((entry = readdir(dir))) { + pid_t pid; + + if (sscanf(entry->d_name, "%d", &pid) > 0) { + /* compute each process cpu usage */ + calculate_stats(get_process(pid)); + } + } + + closedir(dir); + } + + void get_top_info(void) { + unsigned long long total = 0; + + total = calc_cpu_total(); /* calculate the total of the processor */ + update_process_table(); /* update the table with process list */ + calc_cpu_each(total); /* and then the percentage for each task */ +#ifdef BUILD_IOSTATS + calc_io_each(); /* percentage of I/O for each task */ +#endif /* BUILD_IOSTATS */ + } diff --git a/src/haiku.cc b/src/haiku.cc index 62423f391e..8067f88c47 100644 --- a/src/haiku.cc +++ b/src/haiku.cc @@ -8,7 +8,7 @@ * * Please see COPYING for details * - * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen + * Copyright (c) 2007 Toni Spets * Copyright (c) 2005-2018 Brenden Matthews, Philip Kovacs, et. al. * (see AUTHORS) * All rights reserved. @@ -27,20 +27,103 @@ * */ -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include #include "conky.h" -#include "haiku.h" +#include "diskio.h" +#include "logging.h" #include "net_stat.h" +#include "openbsd.h" #include "top.h" +#define MAXSHOWDEVS 16 + +#define LOG1024 10 +#define pagetok(size) ((size) << pageshift) + +inline void proc_find_top(struct process **cpu, struct process **mem); + static short cpu_setup = 0; +static kvm_t *kd = 0; -void prepare_update() {} +struct ifmibdata *data = nullptr; +size_t len = 0; -int update_uptime() { - info.uptime = (double)system_time() / 1000000.0; - return 0; +int init_kvm = 0; +int init_sensors = 0; + +static int kvm_init() { + if (init_kvm) { return 1; } + + kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL); + if (kd == nullptr) { + NORM_ERR("error opening kvm"); + } else { + init_kvm = 1; + } + + return 1; +} + +/* note: swapmode taken from 'top' source */ +/* swapmode is rewritten by Tobias Weingartner + * to be based on the new swapctl(2) system call. */ +static int swapmode(int *used, int *total) { + struct swapent *swdev; + int nswap, rnswap, i; + + nswap = swapctl(SWAP_NSWAP, 0, 0); + if (nswap == 0) { return 0; } + + swdev = malloc(nswap * sizeof(*swdev)); + if (swdev == nullptr) { return 0; } + + rnswap = swapctl(SWAP_STATS, swdev, nswap); + if (rnswap == -1) { + free(swdev); + return 0; + } + + /* if rnswap != nswap, then what? */ + + /* Total things up */ + *total = *used = 0; + for (i = 0; i < nswap; i++) { + if (swdev[i].se_flags & SWF_ENABLE) { + *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE)); + *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE)); + } + } + free(swdev); + return 1; } int check_mount(struct text_object *obj) { @@ -49,61 +132,202 @@ int check_mount(struct text_object *obj) { return 0; } -int update_meminfo() { - system_info si; +void update_uptime() { + int mib[2] = {CTL_KERN, KERN_BOOTTIME}; + struct timeval boottime; + time_t now; + size_t size = sizeof(boottime); - if (get_system_info(&si) != B_OK) { - fprintf(stderr, "Cannot get_system_info\n"); - return 1; + if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && + (boottime.tv_sec != 0)) { + time(&now); + info.uptime = now - boottime.tv_sec; + } else { + NORM_ERR("Could not get uptime"); + info.uptime = 0; } +} - info.memmax = si.max_pages * (B_PAGE_SIZE >> 10); - info.mem = si.used_pages * (B_PAGE_SIZE >> 10); - // TODO: we have some more info... - info.memwithbuffers = info.mem; - info.memeasyfree = info.memfree = info.memmax - info.mem; +void update_meminfo() { + static int mib[2] = {CTL_VM, VM_METER}; + struct vmtotal vmtotal; + size_t size; + int pagesize, pageshift, swap_avail, swap_used; + + pagesize = getpagesize(); + pageshift = 0; + while (pagesize > 1) { + pageshift++; + pagesize >>= 1; + } - info.swapmax = si.max_swap_pages * (B_PAGE_SIZE >> 10); - info.swapfree = si.free_swap_pages * (B_PAGE_SIZE >> 10); - info.swap = (info.swapmax - info.swapfree); + /* we only need the amount of log(2)1024 for our conversion */ + pageshift -= LOG1024; - return 0; + /* get total -- systemwide main memory usage structure */ + size = sizeof(vmtotal); + if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) { + warn("sysctl failed"); + bzero(&vmtotal, sizeof(vmtotal)); + } + + info.memmax = pagetok(vmtotal.t_rm) + pagetok(vmtotal.t_free); + info.mem = info.memwithbuffers = pagetok(vmtotal.t_rm); + info.memeasyfree = info.memfree = info.memmax - info.mem; + + if ((swapmode(&swap_used, &swap_avail)) >= 0) { + info.swapmax = swap_avail; + info.swap = swap_used; + info.swapfree = swap_avail - swap_used; + } else { + info.swapmax = 0; + info.swap = 0; + info.swapfree = 0; + } } -int update_net_stats() { - // TODO - return 1; +void update_net_stats() { + struct net_stat *ns; + double delta; + long long r, t, last_recv, last_trans; + struct ifaddrs *ifap, *ifa; + struct if_data *ifd; + + /* get delta */ + delta = current_update_time - last_update_time; + if (delta <= 0.0001) { return; } + + if (getifaddrs(&ifap) < 0) { return; } + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL); + + if (ifa->ifa_flags & IFF_UP) { + struct ifaddrs *iftmp; + + ns->up = 1; + last_recv = ns->recv; + last_trans = ns->trans; + + if (ifa->ifa_addr->sa_family != AF_LINK) { continue; } + + for (iftmp = ifa->ifa_next; + iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0; + iftmp = iftmp->ifa_next) { + if (iftmp->ifa_addr->sa_family == AF_INET) { + memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len); + } + } + + ifd = (struct if_data *)ifa->ifa_data; + r = ifd->ifi_ibytes; + t = ifd->ifi_obytes; + + if (r < ns->last_read_recv) { + ns->recv += ((long long)4294967295U - ns->last_read_recv) + r; + } else { + ns->recv += (r - ns->last_read_recv); + } + + ns->last_read_recv = r; + + if (t < ns->last_read_trans) { + ns->trans += (long long)4294967295U - ns->last_read_trans + t; + } else { + ns->trans += (t - ns->last_read_trans); + } + + ns->last_read_trans = t; + + /* calculate speeds */ + ns->recv_speed = (ns->recv - last_recv) / delta; + ns->trans_speed = (ns->trans - last_trans) / delta; + } else { + ns->up = 0; + } + } + + freeifaddrs(ifap); } int update_total_processes() { - // TODO + int n_processes; + + kvm_init(); + kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes); + + info.procs = n_processes; } -int update_running_processes() { - // TODO - return 1; +void update_running_processes() { + struct kinfo_proc2 *p; + int n_processes; + int i, cnt = 0; + + kvm_init(); + int max_size = sizeof(struct kinfo_proc2); + + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, max_size, &n_processes); + for (i = 0; i < n_processes; i++) { + if (p[i].p_stat == SRUN) { cnt++; } + } + + info.run_procs = cnt; } -void get_cpu_count(void) { - system_info si; +/* new SMP code can be enabled by commenting the following line */ +#define OLDCPU - if (get_system_info(&si) != B_OK) { - fprintf(stderr, "Cannot get_system_info\n"); - info.cpu_count = 0; - return; +#ifdef OLDCPU +struct cpu_load_struct { + unsigned long load[5]; +}; + +struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}}; +long cpu_used, oldtotal, oldused; +#else +#include +int64_t *fresh = nullptr; + +/* XXX is 8 enough? - What's the constant for MAXCPU? */ +/* allocate this with malloc would be better */ +int64_t oldtotal[8], oldused[8]; +#endif + +void get_cpu_count() { + int cpu_count = 1; /* default to 1 cpu */ +#ifndef OLDCPU + int mib[2] = {CTL_HW, HW_NCPU}; + size_t len = sizeof(cpu_count); + + if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) { + NORM_ERR("error getting cpu count, defaulting to 1"); } - info.cpu_count = si.cpu_count; +#endif + info.cpu_count = cpu_count; - info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + info.cpu_usage = malloc(info.cpu_count * sizeof(float)); if (info.cpu_usage == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } + +#ifndef OLDCPU + assert(fresh == nullptr); /* XXX Is this leaking memory? */ + /* XXX Where shall I free this? */ + if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) { + CRIT_ERR(nullptr, NULL, "calloc"); + } +#endif } -int update_cpu_usage() { - // TODO - static bigtime_t prev = 0; - static cpu_info *prev_cpuinfo = nullptr; - bigtime_t now; - cpu_info *cpuinfo; +void update_cpu_usage() { +#ifdef OLDCPU + int mib[2] = {CTL_KERN, KERN_CPTIME}; + long used, total; + long cp_time[CPUSTATES]; + size_t len = sizeof(cp_time); +#else + size_t size; + unsigned int i; +#endif /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ if ((cpu_setup == 0) || (!info.cpu_usage)) { @@ -111,133 +335,2613 @@ int update_cpu_usage() { cpu_setup = 1; } - int malloc_cpu_size = sizeof(cpu_info) * (info.cpu_count + 1); +#ifdef OLDCPU + if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) { + NORM_ERR("Cannot get kern.cp_time"); + } + + fresh.load[0] = cp_time[CP_USER]; + fresh.load[1] = cp_time[CP_NICE]; + fresh.load[2] = cp_time[CP_SYS]; + fresh.load[3] = cp_time[CP_IDLE]; + fresh.load[4] = cp_time[CP_IDLE]; + + used = fresh.load[0] + fresh.load[1] + fresh.load[2]; + total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3]; + + if ((total - oldtotal) != 0) { + info.cpu_usage[0] = ((double)(used - oldused)) / (double)(total - oldtotal); + } else { + info.cpu_usage[0] = 0; + } + + oldused = used; + oldtotal = total; +#else + if (info.cpu_count > 1) { + size = CPUSTATES * sizeof(int64_t); + for (i = 0; i < info.cpu_count; i++) { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i}; + if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) < + 0) { + NORM_ERR("sysctl kern.cp_time2 failed"); + } + } + } else { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME}; + long cp_time_tmp[CPUSTATES]; + + size = sizeof(cp_time_tmp); + if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) { + NORM_ERR("sysctl kern.cp_time failed"); + } - if (!prev_cpuinfo) { - prev_cpuinfo = (cpu_info *)malloc(malloc_cpu_size); - if (prev_cpuinfo == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } - memset(prev_cpuinfo, 0, malloc_cpu_size); + for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t)cp_time_tmp[i]; } } - cpuinfo = (cpu_info *)malloc(malloc_cpu_size); - memset(cpuinfo, 0, malloc_cpu_size); + /* XXX Do sg with this int64_t => long => double ? float hell. */ + for (i = 0; i < info.cpu_count; i++) { + int64_t used, total; + int at = i * CPUSTATES; - if (cpuinfo == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } + used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; + total = used + fresh[at + CP_IDLE]; - now = system_time(); - if (get_cpu_info(0, info.cpu_count, &cpuinfo[1]) == B_OK) { - for (int i = 1; i <= info.cpu_count; i++) - cpuinfo[0].active_time += cpuinfo[i].active_time; - cpuinfo[0].active_time /= info.cpu_count; - for (int i = 0; i <= info.cpu_count; i++) { - double period = (double)(now - prev); + if ((total - oldtotal[i]) != 0) { info.cpu_usage[i] = - ((double)(cpuinfo[i].active_time - prev_cpuinfo[i].active_time)) / - period; + ((double)(used - oldused[i])) / (double)(total - oldtotal[i]); + } else { + info.cpu_usage[i] = 0; } - } - memcpy(prev_cpuinfo, cpuinfo, malloc_cpu_size); - prev = now; - free(cpuinfo); - return 1; + oldused[i] = used; + oldtotal[i] = total; + } +#endif } -void free_cpu(struct text_object *) { -} +void free_cpu(struct text_object *) { /* not used */ } -int update_load_average() { - // TODO - return 1; +void update_load_average() { + double v[3]; + + getloadavg(v, 3); + + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; } -double get_acpi_temperature(int fd) { return -1; } +#define OBSD_MAX_SENSORS 256 +static struct obsd_sensors_struct { + int device; + float temp[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + unsigned int fan[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + float volt[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; +} obsd_sensors; + +static conky::simple_config_setting sensor_device("sensor_device", 0, + false); + +/* read sensors from sysctl */ +void update_obsd_sensors() { + int sensor_cnt, dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0}; + struct sensor sensor; + struct sensordev sensordev; + size_t slen, sdlen; + enum sensor_type type; + + slen = sizeof(sensor); + sdlen = sizeof(sensordev); + + sensor_cnt = 0; + + dev = obsd_sensors.device; // FIXME: read more than one device + + /* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */ + mib[2] = dev; + if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + return; + // continue; + } + for (type = 0; type < SENSOR_MAX_TYPES; type++) { + mib[3] = type; + for (numt = 0; numt < sensordev.maxnumt[type]; numt++) { + mib[4] = numt; + if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + continue; + } + if (sensor.flags & SENSOR_FINVALID) { continue; } + + switch (type) { + case SENSOR_TEMP: + obsd_sensors.temp[dev][sensor.numt] = + (sensor.value - 273150000) / 1000000.0; + break; + case SENSOR_FANRPM: + obsd_sensors.fan[dev][sensor.numt] = sensor.value; + break; + case SENSOR_VOLTS_DC: + obsd_sensors.volt[dev][sensor.numt] = sensor.value / 1000000.0; + break; + default: + break; + } + + sensor_cnt++; + } + } + /* } */ -void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) { - // TODO + init_sensors = 1; } -int get_battery_perct(const char *bat) { - /* - int batcapacity; +void parse_obsd_sensor(struct text_object *obj, const char *arg) { + if (!isdigit((unsigned char)arg[0]) || atoi(&arg[0]) < 0 || + atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) { + obj->data.l = 0; + NORM_ERR("Invalid sensor number!"); + } else + obj->data.l = atoi(&arg[0]); +} - get_battery_stats(nullptr, &batcapacity, NULL, NULL); - return batcapacity; - */ - // TODO - return 0; +void print_obsd_sensors_temp(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + temp_print(p, p_max_size, obsd_sensors.temp[obsd_sensors.device][obj->data.l], + TEMP_CELSIUS, 1); } -double get_battery_perct_bar(struct text_object *obj) { - int batperct = get_battery_perct(obj->data.s); - return batperct; +void print_obsd_sensors_fan(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%d", + obsd_sensors.fan[obsd_sensors.device][obj->data.l]); } -int open_acpi_temperature(const char *name) { return -1; } +void print_obsd_sensors_volt(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%.2f", + obsd_sensors.volt[obsd_sensors.device][obj->data.l]); +} + +/* chipset vendor */ +void get_obsd_vendor(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char vendor[64]; + size_t size = sizeof(vendor); -void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, - const char *adapter) { - (void)adapter; // only linux uses this + (void)obj; - if (!p_client_buffer || client_buffer_size <= 0) { return; } + mib[0] = CTL_HW; + mib[1] = HW_VENDOR; - /* not implemented */ - memset(p_client_buffer, 0, client_buffer_size); + if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) { + NORM_ERR("error reading vendor"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", vendor); + } } -/* char *get_acpi_fan() */ -void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { - if (!p_client_buffer || client_buffer_size <= 0) { return; } +/* chipset name */ +void get_obsd_product(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char product[64]; + size_t size = sizeof(product); - /* not implemented */ - memset(p_client_buffer, 0, client_buffer_size); + (void)obj; + + mib[0] = CTL_HW; + mib[1] = HW_PRODUCT; + + if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) { + NORM_ERR("error reading product"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", product); + } } /* void */ char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format, int divisor, unsigned int cpu) { - int freq; - char *freq_sysctl; + int freq = cpu; + int mib[2] = {CTL_HW, HW_CPUSPEED}; if (!p_client_buffer || client_buffer_size <= 0 || !p_format || divisor <= 0) { return 0; } - return 0; - // TODO - // return 1; + + size_t size = sizeof(freq); + + if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) { + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + } else { + snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f); + } + + return 1; } -int update_diskio(void) { return 1; } +#if 0 +/* deprecated, will rewrite this soon in update_net_stats() -hifi */ +void update_wifi_stats() +{ + struct net_stat *ns; + struct ifaddrs *ifap, *ifa; + struct ifmediareq ifmr; + struct ieee80211_nodereq nr; + struct ieee80211_bssid bssid; + int s, ibssid; + + /* Get iface table */ + if (getifaddrs(&ifap) < 0) { + return; + } + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *) ifa->ifa_name); + + s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + /* Get media type */ + bzero(&ifmr, sizeof(ifmr)); + strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ); + if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) { + close(s); + return; + } + + /* We can monitor only wireless interfaces + * which are not in hostap mode */ + if ((ifmr.ifm_active & IFM_IEEE80211) + && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) { + /* Get wi status */ + + memset(&bssid, 0, sizeof(bssid)); + strlcpy(bssid.i_name, ifa->ifa_name, sizeof(bssid.i_name)); + ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + + bzero(&nr, sizeof(nr)); + bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); + strlcpy(nr.nr_ifname, ifa->ifa_name, sizeof(nr.nr_ifname)); + + if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { + ns->linkstatus = nr.nr_rssi; + } + } +cleanup: + close(s); + } +} +#endif + +void clear_diskio_stats() {} + +struct diskio_stat *prepare_diskio_stat(const char *s) {} + +void update_diskio() { return; /* XXX: implement? hifi: not sure how */ } + +/* While topless is obviously better, top is also not bad. */ void get_top_info(void) { - int32 tmcookie = 0; - team_info tm; + struct kinfo_proc2 *p; struct process *proc; + int n_processes; + int i; - while (get_next_team_info(&tmcookie, &tm) == B_NO_ERROR) { - team_usage_info ti; + kvm_init(); - if (get_team_usage_info(tm.team, B_TEAM_USAGE_SELF, &ti) != B_OK) continue; + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), + &n_processes); - proc = get_process(tm.team); + for (i = 0; i < n_processes; i++) { + if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) { + proc = find_process(p[i].p_pid); + if (!proc) proc = new_process(p[i].p_pid); - proc->time_stamp = g_time; - proc->name = strndup(tm.args, sizeof(tm.args)); - proc->basename = strndup(tm.args, sizeof(tm.args)); - // proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; - proc->vsize = 0; - proc->rss = 0; - /* bigtime_t is in microseconds, total_cpu_time in centiseconds. - * Therefore we divide by 10000. */ - proc->total_cpu_time = (ti.user_time + ti.kernel_time) / 10000; + proc->time_stamp = g_time; + proc->name = strndup(p[i].p_comm, text_buffer_size); + proc->amount = 100.0 * p[i].p_pctcpu / FSCALE; + /* TODO: vsize, rss, total_cpu_time */ + } } } -void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { - // TODO -} +/* empty stubs so conky links */ +void prepare_update() {} int get_entropy_avail(unsigned int *val) { return 1; } int get_entropy_poolsize(unsigned int *val) { return 1; } +WRITE] / 512); +for (cur = stats.next; cur; cur = cur->next) { + if (cur->dev && !strcmp(device_name, cur->dev)) { + update_diskio_values(cur, reads, writes); + break; + } +} +} +update_diskio_values(&stats, total_reads, total_writes); + +free(dev_select); +} + +if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); } +free(statinfo_cur.dinfo); +return 0; +} + +/* While topless is obviously better, top is also not bad. */ + +void get_top_info(void) { + struct kinfo_proc *p; + struct process *proc; + int n_processes; + int i; + + std::lock_guard guard(kvm_proc_mutex); + p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) { + proc = get_process(p[i].ki_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; + proc->vsize = p[i].ki_size; + proc->rss = (p[i].ki_rssize * getpagesize()); + /* ki_runtime is in microseconds, total_cpu_time in centiseconds. + * Therefore we divide by 10000. */ + proc->total_cpu_time = p[i].ki_runtime / 10000; + } + } +} + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("remaining", buffer, 9)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 9, n - 9); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} +et_apm_adapter(void) { + int fd; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + switch (a_info.ai_acline) { + case 0: + strncpy(out, "off-line", 16); + return out; + break; + case 1: + if (a_info.ai_batt_stat == 3) { + strncpy(out, "charging", 16); + return out; + } else { + strncpy(out, "on-line", 16); + return out; + } + break; + default: + strncpy(out, "unknown", 16); + return out; + break; + } +} + +char *get_apm_battery_life(void) { + int fd; + u_int batt_life; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_life = a_info.ai_batt_life; + if (batt_life == APM_UNKNOWN) { + strncpy(out, "unknown", 16); + } else if (batt_life <= 100) { + snprintf(out, 16, "%d%%", batt_life); + return out; + } else { + strncpy(out, "ERR", 16); + } + + return out; +} + +char *get_apm_battery_time(void) { + int fd; + int batt_time; + int h, m, s; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_time = a_info.ai_batt_time; + + if (batt_time == -1) { + strncpy(out, "unknown", 16); + } else { + h = batt_time; + s = h % 60; + h /= 60; + m = h % 60; + h /= 60; + snprintf(out, 16, "%2d:%02d:%02d", h, m, s); + } + + return out; +} + +#endif + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'A'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + stat_fp) == nullptr) { break; } + + // Do some parsing here to handle skipped cpu numbers. For example, + // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports + // "0,3-7". I assume that chip is really an 8-core die with two cores + // disabled... Presumably you could also get "0,3-4,6", and other + // combos too... + for (str1 = buf;; str1 = nullptr) { + token = strtok_r(str1, ",", &saveptr1); + if (token == nullptr) break; + ++info.cpu_count; + + subtoken1 = -1; + subtoken2 = -1; + for (str2 = token;; str2 = nullptr) { + subtoken = strtok_r(str2, "-", &saveptr2); + if (subtoken == nullptr) break; + if (subtoken1 < 0) + subtoken1 = atoi(subtoken); + else + subtoken2 = atoi(subtoken); + } + if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; + } + } + info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + + fclose(stat_fp); + } + +#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" +#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" + + int update_stat(void) { + FILE *stat_fp; + static int rep = 0; + static struct cpu_info *cpu = nullptr; + char buf[256]; + int i; + unsigned int idx; + double curtmp; + const char *stat_template = nullptr; + unsigned int malloc_cpu_size = 0; + extern void *global_cpu; + + static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; + static double last_stat_update = 0.0; + float cur_total = 0.0; + + /* since we use wrappers for this function, the update machinery + * can't eliminate double invocations of this function. Check for + * them here, otherwise cpu_usage counters are freaking out. */ + pthread_mutex_lock(&last_stat_update_mutex); + if (last_stat_update == current_update_time) { + pthread_mutex_unlock(&last_stat_update_mutex); + return 0; + } + last_stat_update = current_update_time; + pthread_mutex_unlock(&last_stat_update_mutex); + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if (!cpu_setup || !info.cpu_usage) { + get_cpu_count(); + cpu_setup = 1; + } + + if (!stat_template) { + stat_template = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + } + + if (!global_cpu) { + malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); + cpu = (struct cpu_info *)malloc(malloc_cpu_size); + memset(cpu, 0, malloc_cpu_size); + global_cpu = cpu; + } + + if (!(stat_fp = open_file("/proc/stat", &rep))) { + info.run_threads = 0; + if (info.cpu_usage) { + memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); + } + return 0; + } + + idx = 0; + while (!feof(stat_fp)) { + if (fgets(buf, 255, stat_fp) == nullptr) { break; } + + if (strncmp(buf, "procs_running ", 14) == 0) { + sscanf(buf, "%*s %hu", &info.run_threads); + } else if (strncmp(buf, "cpu", 3) == 0) { + double delta; + if (isdigit((unsigned char)buf[3])) { + idx++; // just increment here since the CPU index can skip numbers + } else { + idx = 0; + } + if (idx > info.cpu_count) { continue; } + sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), + &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), + &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), + &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); + + cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + + cpu[idx].cpu_system + cpu[idx].cpu_idle + + cpu[idx].cpu_iowait + cpu[idx].cpu_irq + + cpu[idx].cpu_softirq + cpu[idx].cpu_steal; + + cpu[idx].cpu_active_total = + cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); + + delta = current_update_time - last_update_time; + + if (delta <= 0.001) { break; } + + cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); + if (cur_total == 0.0) { + cpu[idx].cpu_val[0] = 1.0; + } else { + cpu[idx].cpu_val[0] = + (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / + cur_total; + } + curtmp = 0; + + int samples = cpu_avg_samples.get(*state); +#ifdef HAVE_OPENMP +#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } + info.cpu_usage[idx] = curtmp / samples; + + cpu[idx].cpu_last_total = cpu[idx].cpu_total; + cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = samples - 1; i > 0; i--) { + cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; + } + } + } + fclose(stat_fp); + return 0; + } + + int update_running_processes(void) { + update_stat(); + return 0; + } + + int update_cpu_usage(void) { + update_stat(); + return 0; + } + + void free_cpu(struct text_object *) { /* not used */ } + + // fscanf() that reads floats with points even if you are using a locale where + // floats are with commas + int fscanf_no_i18n(FILE *stream, const char *format, ...) { + int returncode; + va_list ap; + +#ifdef BUILD_I18N + const char *oldlocale = setlocale(LC_NUMERIC, nullptr); + + setlocale(LC_NUMERIC, "C"); +#endif + va_start(ap, format); + returncode = vfscanf(stream, format, ap); + va_end(ap); +#ifdef BUILD_I18N + setlocale(LC_NUMERIC, oldlocale); +#endif + return returncode; + } + + int update_load_average(void) { +#ifdef HAVE_GETLOADAVG + if (!prefer_proc) { + double v[3]; + + getloadavg(v, 3); + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; + } else +#endif + { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file("/proc/loadavg", &rep))) { + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + return 0; + } + if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], + &info.loadavg[2]) < 0) + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + fclose(fp); + } + return 0; + } + + /***********************************************************/ + /***********************************************************/ + /***********************************************************/ + + static int no_dots(const struct dirent *d) { + if (d->d_name[0] == '.') { return 0; } + return 1; + } + + static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { + struct dirent **namelist; + int i, n; + + n = scandir(dir, &namelist, no_dots, alphasort); + if (n < 0) { + if (!rep || !*rep) { + NORM_ERR("scandir for %s: %s", dir, strerror(errno)); + if (rep) { *rep = 1; } + } + return 0; + } else { + if (n == 0) { return 0; } + + strncpy(s, namelist[0]->d_name, 255); + s[255] = '\0'; + +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < n; i++) { free(namelist[i]); } + free(namelist); + + return 1; + } + } + + static int open_sysfs_sensor(const char *dir, const char *dev, + const char *type, int n, int *divisor, + char *devtype) { + char path[256]; + char buf[256]; + int fd; + int divfd; + + memset(buf, 0, sizeof(buf)); + + /* if device is nullptr or *, get first */ + if (dev == nullptr || strcmp(dev, "*") == 0) { + static int rep = 0; + + if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } + dev = buf; + } + + if (strcmp(dir, "/sys/class/hwmon/") == 0) { + if (*buf) { + /* buf holds result from get_first_file_in_a_directory() above, + * e.g. "hwmon0" -- append "/device" */ + strncat(buf, "/device", 256); + } else { + /* dev holds device number N as a string, + * e.g. "0", -- convert to "hwmon0/device" */ + sprintf(buf, "hwmon%s/device", dev); + dev = buf; + } + } + + /* change vol to in, tempf to temp */ + if (strcmp(type, "vol") == 0) { + type = "in"; + } else if (strcmp(type, "tempf") == 0) { + type = "temp"; + } else if (strcmp(type, "temp2") == 0) { + type = "temp"; + } + + /* construct path */ + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + + /* first, attempt to open file in /device */ + fd = open(path, O_RDONLY); + if (fd < 0) { + /* if it fails, strip the /device from dev and attempt again */ + buf[strlen(buf) - 7] = 0; + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + fd = open(path, O_RDONLY); + if (fd < 0) { + NORM_ERR( + "can't open '%s': %s\nplease check your device or remove this " + "var from " PACKAGE_NAME, + path, strerror(errno)); + } + } + + strncpy(devtype, path, 255); + + if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || + strcmp(type, "tempf") == 0) { + *divisor = 1; + } else { + *divisor = 0; + } + /* fan does not use *_div as a read divisor */ + if (strcmp("fan", type) == 0) { return fd; } + + /* test if *_div file exist, open it and use it as divisor */ + if (strcmp(type, "tempf") == 0) { + snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + } else { + snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + } + + divfd = open(path, O_RDONLY); + if (divfd > 0) { + /* read integer */ + char divbuf[64]; + int divn; + + divn = read(divfd, divbuf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (divn < 0) { + NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); + } else { + divbuf[divn] = '\0'; + *divisor = atoi(divbuf); + } + close(divfd); + } + + return fd; + } + + static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { + int val = 0; + + if (*fd <= 0) { return 0; } + + lseek(*fd, 0, SEEK_SET); + + /* read integer */ + { + char buf[64]; + int n; + n = read(*fd, buf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (n < 0) { + NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); + } else { + buf[n] = '\0'; + val = atoi(buf); + } + } + + close(*fd); + /* open file */ + *fd = open(devtype, O_RDONLY); + if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } + + /* My dirty hack for computing CPU value + * Filedil, from forums.gentoo.org */ + /* if (strstr(devtype, "temp1_input") != nullptr) { + return -15.096 + 1.4893 * (val / 1000.0); + } */ + + /* divide voltage and temperature by 1000 */ + /* or if any other divisor is given, use that */ + if (0 == (strcmp(type, "temp2"))) { + temp2 = "temp2"; + } else { + temp2 = "empty"; + } + if (strcmp(type, "tempf") == 0) { + if (divisor > 1) { + return ((val / divisor + 40) * 9.0 / 5) - 40; + } else if (divisor) { + return ((val / 1000.0 + 40) * 9.0 / 5) - 40; + } else { + return ((val + 40) * 9.0 / 5) - 40; + } + } else { + if (divisor > 1) { + return val / divisor; + } else if (divisor) { + return val / 1000.0; + } else { + return val; + } + } + } + +#define HWMON_RESET() \ + { \ + buf1[0] = 0; \ + factor = 1.0; \ + offset = 0.0; \ + } + + static void parse_sysfs_sensor(struct text_object *obj, const char *arg, + const char *path, const char *type) { + char buf1[64], buf2[64]; + float factor, offset; + int n, found = 0; + struct sysfs *sf; + + if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) + found = 1; + else + HWMON_RESET(); + if (!found && + sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) + found = 1; + else if (!found) + HWMON_RESET(); + + if (!found) { + obj_be_plain_text(obj, "fail"); + return; + } + DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, + offset); + sf = (struct sysfs *)malloc(sizeof(struct sysfs)); + memset(sf, 0, sizeof(struct sysfs)); + sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, + sf->devtype); + strncpy(sf->type, buf2, 63); + sf->factor = factor; + sf->offset = offset; + obj->data.opaque = sf; + } + +#define PARSER_GENERATOR(name, path) \ + void parse_##name##_sensor(struct text_object *obj, const char *arg) { \ + parse_sysfs_sensor(obj, arg, path, #name); \ + } + + PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") + PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") + PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") + + void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { + double r; + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf || sf->fd < 0) return; + + r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); + + r = r * sf->factor + sf->offset; + + if (0 == (strcmp(temp2, "temp2"))) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); + } else if (!strncmp(sf->type, "temp", 4)) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); + } else if (r >= 100.0 || r == 0) { + snprintf(p, p_max_size, "%d", (int)r); + } else { + snprintf(p, p_max_size, "%.1f", r); + } + } + + void free_sysfs_sensor(struct text_object *obj) { + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf) return; + + if (sf->fd >= 0) close(sf->fd); + free_and_zero(obj->data.opaque); + } + +#define CPUFREQ_PREFIX "/sys/devices/system/cpu" +#define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq" + + /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ + char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + static int rep = 0; + char frequency[32]; + char s[256]; + double freq = 0; + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + if (!prefer_proc) { + char current_freq_file[128]; + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, + CPUFREQ_POSTFIX); + f = fopen(current_freq_file, "r"); + if (f) { + /* if there's a cpufreq /sys node, read the current frequency from + * this node and divide by 1000 to get Mhz. */ + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (freq / 1000) / divisor); + return 1; + } + } + + // open the CPU information file + f = open_file("/proc/cpuinfo", &rep); + if (!f) { + perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); + return 0; + } + + // read the file + while (fgets(s, sizeof(s), f) != nullptr) { +#if defined(__i386) || defined(__x86_64) + // and search for the cpu mhz + if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { +#else +#if defined(__alpha) + // different on alpha + if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { +#else + // this is different on ppc for some reason + if (strncmp(s, "clock", 5) == 0 && cpu == 0) { +#endif // defined(__alpha) +#endif // defined(__i386) || defined(__x86_64) + + // copy just the number + strncpy(frequency, strchr(s, ':') + 2, 32); +#if defined(__alpha) + // strip " est.\n" + frequency[strlen(frequency) - 6] = '\0'; + // kernel reports in Hz + freq = strtod(frequency, nullptr) / 1000000; +#else + // strip \n + frequency[strlen(frequency) - 1] = '\0'; + freq = strtod(frequency, nullptr); +#endif + break; + } + if (strncmp(s, "processor", 9) == 0) { + cpu--; + continue; + } + } + + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + return 1; + } + +#define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages" + + /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something + * like this: + # frequency voltage + 1800000 1340 + 1600000 1292 + 1400000 1100 + 1200000 988 + 1000000 1116 + 800000 1004 + 600000 988 + * Peter Tarjan (ptarjan@citromail.hu) */ + + /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ + static char get_voltage(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + char s[256]; + int freq = 0; + int voltage = 0; + char current_freq_file[128]; + int freq_comp = 0; + + /* build the voltage file name */ + cpu--; + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_POSTFIX); + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + /* read the current cpu frequency from the /sys node */ + f = fopen(current_freq_file, "r"); + if (f) { + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_VOLTAGE); + + /* use the current cpu frequency to find the corresponding voltage */ + f = fopen(current_freq_file, "r"); + + if (f) { + while (!feof(f)) { + char line[256]; + + if (fgets(line, 255, f) == nullptr) { break; } + sscanf(line, "%d %d", &freq_comp, &voltage); + if (freq_comp == freq) { break; } + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)voltage / divisor); + return 1; + } + + void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } + } + + void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } + } + +#define ACPI_FAN_DIR "/proc/acpi/fan/" + + void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { + static int rep = 0; + char buf[256]; + char buf2[256]; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "can't open fan's state file"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + +#define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply" +#define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/" + /* Linux 2.6.25 onwards ac adapter info is in + /sys/class/power_supply/AC/ + On my system I get the following. + /sys/class/power_supply/AC/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=ac + POWER_SUPPLY_NAME=AC + POWER_SUPPLY_TYPE=Mains + POWER_SUPPLY_ONLINE=1 + + Update: it seems the folder name is hardware-dependent. We add an aditional + adapter argument, specifying the folder name. + + Update: on some systems it's /sys/class/power_supply/ADP1 instead of + /sys/class/power_supply/AC + */ + + void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, + const char *adapter) { + static int rep = 0; + + char buf[256]; + char buf2[256]; + struct stat sb; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + if (adapter) + snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, + adapter); + else { + snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); + if (stat(buf2, &sb) == -1) + snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); + } + if (stat(buf2, &sb) == 0) + fp = open_file(buf2, &rep); + else + fp = 0; + if (fp) { + /* sysfs processing */ + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { + int online = 0; + sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); + snprintf(p_client_buffer, client_buffer_size, "%s-line", + (online ? "on" : "off")); + break; + } + } + fclose(fp); + } else { + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "No ac adapter found.... where is it?"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + } + + /* + /proc/acpi/thermal_zone/THRM/cooling_mode + cooling mode: active + /proc/acpi/thermal_zone/THRM/polling_frequency + + /proc/acpi/thermal_zone/THRM/state + state: ok + /proc/acpi/thermal_zone/THRM/temperature + temperature: 45 C + /proc/acpi/thermal_zone/THRM/trip_points + critical (S5): 73 C + passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 + */ + +#define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0" +#define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp" + + int open_acpi_temperature(const char *name) { + char path[256]; + int fd; + + if (name == nullptr || strcmp(name, "*") == 0) { + snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); + } else { + snprintf(path, 255, ACPI_THERMAL_FORMAT, name); + } + + fd = open(path, O_RDONLY); + if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } + + return fd; + } + + static double last_acpi_temp; + static double last_acpi_temp_time; + + // the maximum length of the string inside a ACPI_THERMAL_FORMAT file including + // the ending 0 +#define MAXTHERMZONELEN 6 + + double get_acpi_temperature(int fd) { + if (fd <= 0) { return 0; } + + /* don't update acpi temperature too often */ + if (current_update_time - last_acpi_temp_time < 11.32) { + return last_acpi_temp; + } + last_acpi_temp_time = current_update_time; + + /* seek to beginning */ + lseek(fd, 0, SEEK_SET); + + /* read */ + { + char buf[MAXTHERMZONELEN]; + int n; + + n = read(fd, buf, MAXTHERMZONELEN - 1); + if (n < 0) { + NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); + } else { + buf[n] = '\0'; + sscanf(buf, "%lf", &last_acpi_temp); + last_acpi_temp /= 1000; + } + } + + return last_acpi_temp; + } + + /* + hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info + present: yes + design capacity: 4400 mAh + last full capacity: 4064 mAh + battery technology: rechargeable + design voltage: 14800 mV + design capacity warning: 300 mAh + design capacity low: 200 mAh + capacity granularity 1: 32 mAh + capacity granularity 2: 32 mAh + model number: 02KT + serial number: 16922 + battery type: LION + OEM info: SANYO + */ + + /* + hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state + present: yes + capacity state: ok + charging state: unknown + present rate: 0 mA + remaining capacity: 4064 mAh + present voltage: 16608 mV + */ + + /* + 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? + 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) + 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? + + 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman + verkkovirtaa 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? + verkkovirralla + + 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja + monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? + monitori p��ll� mutta ilman verkkovirtaa + */ + + /* Kapil Hari Paranjape + Linux 2.6.24 onwards battery info is in + /sys/class/power_supply/BAT0/ + On my system I get the following. + /sys/class/power_supply/BAT0/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=battery + POWER_SUPPLY_NAME=BAT0 + POWER_SUPPLY_TYPE=Battery + POWER_SUPPLY_STATUS=Discharging + POWER_SUPPLY_PRESENT=1 + POWER_SUPPLY_TECHNOLOGY=Li-ion + POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 + POWER_SUPPLY_VOLTAGE_NOW=10780000 + POWER_SUPPLY_CURRENT_NOW=13970000 + POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 + POWER_SUPPLY_ENERGY_FULL=27370000 + POWER_SUPPLY_ENERGY_NOW=11810000 + POWER_SUPPLY_MODEL_NAME=IBM-92P1060 + POWER_SUPPLY_MANUFACTURER=Panasonic + On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* + */ + + /* Tiago Marques Vale + Regarding the comment above, since kernel 2.6.36.1 I have + POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW + See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 + */ + +#define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply" +#define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" +#define APM_PATH "/proc/apm" +#define MAX_BATTERY_COUNT 4 + + static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + + static int batteries_initialized = 0; + static char batteries[MAX_BATTERY_COUNT][32]; + + static int acpi_last_full[MAX_BATTERY_COUNT]; + static int acpi_design_capacity[MAX_BATTERY_COUNT]; + + /* e.g. "charging 75%" */ + static char last_battery_str[MAX_BATTERY_COUNT][64]; + /* e.g. "3h 15m" */ + static char last_battery_time_str[MAX_BATTERY_COUNT][64]; + + static double last_battery_time[MAX_BATTERY_COUNT]; + + static int last_battery_perct[MAX_BATTERY_COUNT]; + static double last_battery_perct_time[MAX_BATTERY_COUNT]; + + void init_batteries(void) { + int idx; + + if (batteries_initialized) { return; } +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } + batteries_initialized = 1; + } + + int get_battery_idx(const char *bat) { + int idx; + + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } + } + + /* if not found, enter a new entry */ + if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } + + return idx; + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx); + + void get_battery_stuff(char *buffer, unsigned int n, const char *bat, + int item) { + static int idx, rep = 0, rep1 = 0, rep2 = 0; + char acpi_path[128]; + char sysfs_path[128]; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + init_batteries(); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_time[idx] < 29.5) { + set_return_value(buffer, n, item, idx); + return; + } + + last_battery_time[idx] = current_update_time; + + memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); + memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); + + /* first try SYSFS if that fails try ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep1); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[4]; + + strncpy(charging_state, "unknown", 64); + + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + /* let's just hope units are ok */ + if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) + strncpy(present, "yes", 4); + else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) + strncpy(present, "no", 4); + else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) + sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); + /* present_rate is not the same as the current flowing now but it + * is the same value which was used in the past. so we continue the + * tradition! */ + else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) + sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) + acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ + + /* not present */ + if (strcmp(present, "No") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + } + /* charging */ + else if (strcmp(charging_state, "Charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)(acpi_last_full[idx] - remaining_capacity) / + present_rate) * + 3600)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* discharging */ + else if (strncmp(charging_state, "Discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 1h 12m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)remaining_capacity / present_rate) * 3600)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "full"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* charged */ + /* thanks to Lukas Zapletal */ + else if (strncmp(charging_state, "Charged", 64) == 0 || + strncmp(charging_state, "Full", 64) == 0) { + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one + * being charged. */ + if (remaining_capacity == 0) + strncpy(last_battery_str[idx], "empty", 64); + else + strncpy(last_battery_str[idx], "charged", 64); + } + /* unknown, probably full / AC */ + else { + if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) + snprintf( + last_battery_str[idx], 64, "unknown %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + else + strncpy(last_battery_str[idx], "not present", 64); + } + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[5]; + + /* read last full capacity if it's zero */ + if (acpi_last_full[idx] == 0) { + static int rep3 = 0; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep3); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { + break; + } + } + + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + strncpy(charging_state, "unknown", 8); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + /* let's just hope units are ok */ + if (strncmp(buf, "present:", 8) == 0) { + sscanf(buf, "present: %4s", present); + } else if (strncmp(buf, "charging state:", 15) == 0) { + sscanf(buf, "charging state: %63s", charging_state); + } else if (strncmp(buf, "present rate:", 13) == 0) { + sscanf(buf, "present rate: %d", &present_rate); + } else if (strncmp(buf, "remaining capacity:", 19) == 0) { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) { + /* normalize to 100% */ + acpi_last_full[idx] = remaining_capacity; + } + + /* not present */ + if (strcmp(present, "no") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + /* charging */ + } else if (strcmp(charging_state, "charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / + present_rate)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* discharging */ + } else if (strncmp(charging_state, "discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 1h 12m */ + format_seconds(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, + (long)((remaining_capacity * 3600) / present_rate)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charged"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* charged */ + } else if (strncmp(charging_state, "charged", 64) == 0) { + /* thanks to Lukas Zapletal */ + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one being charged. */ + if (remaining_capacity == 0) { + strncpy(last_battery_str[idx], "empty", 6); + } else { + strncpy(last_battery_str[idx], "charged", 8); + } + /* unknown, probably full / AC */ + } else { + if (strncmp(charging_state, "Full", 64) == 0) { + strncpy(last_battery_str[idx], "charged", 64); + } else if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) { + snprintf(last_battery_str[idx], 64, "unknown %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + } else { + strncpy(last_battery_str[idx], "not present", 64); + } + } + fclose(acpi_bat_fp[idx]); + acpi_bat_fp[idx] = nullptr; + } else { + /* APM */ + if (apm_bat_fp[idx] == nullptr) { + apm_bat_fp[idx] = open_file(APM_PATH, &rep2); + } + + if (apm_bat_fp[idx] != nullptr) { + unsigned int ac, status, flag; + int life; + + if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, + &status, &flag, &life) <= 0) + goto read_bat_fp_end; + + if (life == -1) { + /* could check now that there is ac */ + snprintf(last_battery_str[idx], 64, "%s", "not present"); + + /* could check that status == 3 here? */ + } else if (ac && life != 100) { + snprintf(last_battery_str[idx], 64, "charging %d%%", life); + } else { + snprintf(last_battery_str[idx], 64, "%d%%", life); + } + + read_bat_fp_end: + /* it seemed to buffer it so file must be closed (or could use + * syscalls directly but I don't feel like coding it now) */ + fclose(apm_bat_fp[idx]); + apm_bat_fp[idx] = nullptr; + } + } + set_return_value(buffer, n, item, idx); + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx) { + switch (item) { + case BATTERY_STATUS: + snprintf(buffer, n, "%s", last_battery_str[idx]); + break; + case BATTERY_TIME: + snprintf(buffer, n, "%s", last_battery_time_str[idx]); + break; + default: + break; + } + } + + void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("not present", buffer, 11)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("empty", buffer, 5)) { + buffer[0] = 'E'; + memmove(buffer + 1, buffer + 5, n - 5); + } else if (0 == strncmp("unknown", buffer, 7)) { + buffer[0] = 'U'; + memmove(buffer + 1, buffer + 7, n - 7); + } + // Otherwise, don't shorten. + } + + int _get_battery_perct(const char *bat) { + static int rep = 0; + int idx; + char acpi_path[128]; + char sysfs_path[128]; + int remaining_capacity = -1; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_perct_time[idx] < 30) { + return last_battery_perct[idx]; + } + last_battery_perct_time[idx] = current_update_time; + + /* Only check for SYSFS or ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + rep = 0; + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); + } + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + /* read last full capacity if it's zero */ + if (acpi_design_capacity[idx] == 0) { + static int rep2; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep2); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", + &acpi_design_capacity[idx]) != 0) { + break; + } + } + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + if (buf[0] == 'r') { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + } + if (remaining_capacity < 0) { return 0; } + /* compute the battery percentage */ + last_battery_perct[idx] = + (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); + if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; + return last_battery_perct[idx]; + } + + int get_battery_perct(const char *bat) { + int idx, n = 0, total_capacity = 0, remaining_capacity; + ; +#define BATTERY_LEN 8 + char battery[BATTERY_LEN]; + + init_batteries(); + + /* Check if user asked for the mean percentage of all batteries. */ + if (!strcmp(bat, "all")) { + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); +#undef BATTERY_LEN + remaining_capacity = _get_battery_perct(battery); + if (remaining_capacity > 0) { + total_capacity += remaining_capacity; + n++; + } + } + + if (n == 0) + return 0; + else + return total_capacity / n; + } else { + return _get_battery_perct(bat); + } + } + + double get_battery_perct_bar(struct text_object *obj) { + int idx; + + get_battery_perct(obj->data.s); + idx = get_battery_idx(obj->data.s); + return last_battery_perct[idx]; + } + + /* On Apple powerbook and ibook: + $ cat /proc/pmu/battery_0 + flags : 00000013 + charge : 3623 + max_charge : 3720 + current : 388 + voltage : 16787 + time rem. : 900 + $ cat /proc/pmu/info + PMU driver version : 2 + PMU firmware version : 0c + AC Power : 1 + Battery count : 1 + */ + + /* defines as in */ +#define PMU_BATT_PRESENT 0x00000001 +#define PMU_BATT_CHARGING 0x00000002 + + static FILE *pmu_battery_fp; + static FILE *pmu_info_fp; + static char pb_battery_info[3][32]; + static double pb_battery_info_update; + +#define PMU_PATH "/proc/pmu" + void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { + static int rep = 0; + const char *batt_path = PMU_PATH "/battery_0"; + const char *info_path = PMU_PATH "/info"; + unsigned int flags = 0; + int charge = 0; + int max_charge = 1; + int ac = -1; + long timeval = -1; + + /* don't update battery too often */ + if (current_update_time - pb_battery_info_update < 29.5) { + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + return; + } + pb_battery_info_update = current_update_time; + + if (pmu_battery_fp == nullptr) { + pmu_battery_fp = open_file(batt_path, &rep); + if (pmu_battery_fp == nullptr) { return; } + } + + if (pmu_battery_fp != nullptr) { + rewind(pmu_battery_fp); + while (!feof(pmu_battery_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } + + if (buf[0] == 'f') { + sscanf(buf, "flags : %8x", &flags); + } else if (buf[0] == 'c' && buf[1] == 'h') { + sscanf(buf, "charge : %d", &charge); + } else if (buf[0] == 'm') { + sscanf(buf, "max_charge : %d", &max_charge); + } else if (buf[0] == 't') { + sscanf(buf, "time rem. : %ld", &timeval); + } + } + } + if (pmu_info_fp == nullptr) { + pmu_info_fp = open_file(info_path, &rep); + if (pmu_info_fp == nullptr) { return; } + } + + if (pmu_info_fp != nullptr) { + rewind(pmu_info_fp); + while (!feof(pmu_info_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } + if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } + } + } + /* update status string */ + if ((ac && !(flags & PMU_BATT_PRESENT))) { + strncpy(pb_battery_info[PB_BATT_STATUS], "AC", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if (ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charged", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else { + strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } + + /* update percentage string */ + if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); + } else if (timeval == 0) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); + } else { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", + (charge * 100) / max_charge); + } + + /* update time string */ + if (timeval == 0) { /* fully charged or battery not present */ + snprintf(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); + } else if (timeval < 60 * 60) { /* don't show secs */ + format_seconds_short(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } else { + format_seconds(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } + + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + } + +#define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail" + + int get_entropy_avail(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + +#define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize" + + int get_entropy_poolsize(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + + void print_disk_protect_queue(struct text_object *obj, char *p, + int p_max_size) { + FILE *fp; + char path[128]; + int state; + + snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); + if (access(path, F_OK)) { + snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); + } + if ((fp = fopen(path, "r")) == nullptr) { + snprintf(p, p_max_size, "%s", "n/a "); + return; + } + if (fscanf(fp, "%d\n", &state) != 1) { + fclose(fp); + snprintf(p, p_max_size, "%s", "failed"); + return; + } + fclose(fp); + snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); + } + + std::unordered_map dev_list; + + /* Same as sf #2942117 but memoized using a linked list */ + int is_disk(char *dev) { + std::string orig(dev); + std::string syspath("/sys/block/"); + char *slash; + + auto i = dev_list.find(orig); + if (i != dev_list.end()) return i->second; + + while ((slash = strchr(dev, '/'))) *slash = '!'; + syspath += dev; + + return dev_list[orig] = !(access(syspath.c_str(), F_OK)); + } + + int update_diskio(void) { + FILE *fp; + static int rep = 0; + char buf[512], devbuf[64]; + unsigned int major, minor; + int col_count = 0; + struct diskio_stat *cur; + unsigned int reads, writes; + unsigned int total_reads = 0, total_writes = 0; + + stats.current = 0; + stats.current_read = 0; + stats.current_write = 0; + + if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } + + /* read reads and writes from all disks (minor = 0), including cd-roms + * and floppies, and sum them up */ + while (fgets(buf, 512, fp)) { + col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, + &minor, devbuf, &reads, &writes); + /* ignore subdevices (they have only 3 matching entries in their line) + * and virtual devices (LVM, network block devices, RAM disks, Loopback) + * + * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ + if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && + major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { + /* check needed for kernel >= 2.6.31, see sf #2942117 */ + if (is_disk(devbuf)) { + total_reads += reads; + total_writes += writes; + } + } else { + col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, + &reads, &writes); + if (col_count != 5) { continue; } + } + cur = stats.next; + while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; + + if (cur) update_diskio_values(cur, reads, writes); + } + update_diskio_values(&stats, total_reads, total_writes); + fclose(fp); + return 0; + } + + void print_distribution(struct text_object *obj, char *p, int p_max_size) { + (void)obj; + int i, bytes_read; + char *buf; + struct stat sb; + + if (stat("/etc/arch-release", &sb) == 0) { + snprintf(p, p_max_size, "%s", "Arch Linux"); + return; + } + snprintf(p, p_max_size, "Unknown"); + buf = readfile("/proc/version", &bytes_read, 1); + if (buf) { + /* I am assuming the distribution name is the first string in /proc/version + that: + - is preceded by a '(' + - starts with a capital + - is followed by a space and a number + but i am not sure if this is always true... */ + for (i = 1; i < bytes_read; i++) { + if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; + } + if (i < bytes_read) { + snprintf(p, p_max_size, "%s", &buf[i]); + for (i = 1; p[i]; i++) { + if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { + p[i - 1] = 0; + break; + } + } + } + free(buf); + } + } + + /****************************************** + * Calculate cpu total * + ******************************************/ +#define TMPL_SHORTPROC "%*s %llu %llu %llu %llu" +#define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu" + + static unsigned long long calc_cpu_total(void) { + static unsigned long long previous_total = 0; + unsigned long long total = 0; + unsigned long long t = 0; + int rc; + int ps; + char line[BUFFER_LEN] = {0}; + unsigned long long cpu = 0; + unsigned long long niceval = 0; + unsigned long long systemval = 0; + unsigned long long idle = 0; + unsigned long long iowait = 0; + unsigned long long irq = 0; + unsigned long long softirq = 0; + unsigned long long steal = 0; + const char *template_ = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; + + ps = open("/proc/stat", O_RDONLY); + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return 0; } + + sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, + &softirq, &steal); + total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; + + t = total - previous_total; + previous_total = total; + + return t; + } + + /****************************************** + * Calculate each processes cpu * + ******************************************/ + + inline static void calc_cpu_each(unsigned long long total) { + float mul = 100.0; + if (top_cpu_separate.get(*state)) mul *= info.cpu_count; + + for (struct process *p = first_process; p; p = p->next) + p->amount = mul * (p->user_time + p->kernel_time) / (float)total; + } + +#ifdef BUILD_IOSTATS + static void calc_io_each(void) { + struct process *p; + unsigned long long sum = 0; + + for (p = first_process; p; p = p->next) + sum += p->read_bytes + p->write_bytes; + + if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ + for (p = first_process; p; p = p->next) + p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Extract information from /proc * + ******************************************/ + +#define PROCFS_TEMPLATE "/proc/%d/stat" +#define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline" + + /* These are the guts that extract information out of /proc. + * Anyone hoping to port wmtop should look here first. */ + static void process_parse_stat(struct process *process) { + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; + char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], + cmdline_procname[BUFFER_LEN]; + char basename[BUFFER_LEN] = {0}; + char tmpstr[BUFFER_LEN] = {0}; + char state[4]; + int ps, cmdline_ps; + unsigned long user_time = 0; + unsigned long kernel_time = 0; + int rc; + char *r, *q; + int endl; + int nice_val; + char *lparen, *rparen; + struct stat process_stat; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); + snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, + process->pid); + + ps = open(filename, O_RDONLY); + if (ps == -1) { + /* The process must have finished in the last few jiffies! */ + return; + } + + if (fstat(ps, &process_stat) != 0) { + close(ps); + return; + } + process->uid = process_stat.st_uid; + + /* Mark process as up-to-date. */ + process->time_stamp = g_time; + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + /* Read /proc//cmdline */ + cmdline_ps = open(cmdline_filename, O_RDONLY); + if (cmdline_ps < 0) { + /* The process must have finished in the last few jiffies! */ + return; + } + + endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); + close(cmdline_ps); + if (endl < 0) { return; } + + /* Some processes have null-separated arguments (see proc(5)); let's fix it + */ + int i = endl; + while (i && cmdline[i - 1] == 0) { + /* Skip past any trailing null characters */ + --i; + } + while (i--) { + /* Replace null character between arguments with a space */ + if (cmdline[i] == 0) { cmdline[i] = ' '; } + } + + cmdline[endl] = 0; + + /* We want to transform for example "/usr/bin/python program.py" to "python + * program.py" + * 1. search for first space + * 2. search for last / before first space + * 3. copy string from its position + */ + char *space_ptr = strchr(cmdline, ' '); + if (space_ptr == nullptr) { + strncpy(tmpstr, cmdline, BUFFER_LEN); + } else { + long int space_pos = space_ptr - cmdline; + strncpy(tmpstr, cmdline, space_pos); + tmpstr[space_pos] = 0; + } + + char *slash_ptr = strrchr(tmpstr, '/'); + if (slash_ptr == nullptr) { + strncpy(cmdline_procname, cmdline, BUFFER_LEN); + } else { + long int slash_pos = slash_ptr - tmpstr; + strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); + cmdline_procname[BUFFER_LEN - slash_pos] = 0; + } + + /* Extract cpu times from data in /proc filesystem */ + lparen = strchr(line, '('); + rparen = strrchr(line, ')'); + if (!lparen || !rparen || rparen < lparen) return; // this should not happen + + rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); + strncpy(procname, lparen + 1, rc); + procname[rc] = '\0'; + strncpy(basename, procname, strlen(procname) + 1); + + if (strlen(procname) < strlen(cmdline_procname)) + strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); + + rc = sscanf(rparen + 1, + "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " + "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", + state, &process->user_time, &process->kernel_time, &nice_val, + &process->vsize, &process->rss); + if (rc < 6) { + NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); + return; + } + + if (state[0] == 'R') ++info.run_procs; + + free_and_zero(process->name); + free_and_zero(process->basename); + process->name = strndup(procname, text_buffer_size.get(*::state)); + process->basename = strndup(basename, text_buffer_size.get(*::state)); + process->rss *= getpagesize(); + + process->total_cpu_time = process->user_time + process->kernel_time; + if (process->previous_user_time == ULONG_MAX) { + process->previous_user_time = process->user_time; + } + if (process->previous_kernel_time == ULONG_MAX) { + process->previous_kernel_time = process->kernel_time; + } + + /* strangely, the values aren't monotonous */ + if (process->previous_user_time > process->user_time) + process->previous_user_time = process->user_time; + + if (process->previous_kernel_time > process->kernel_time) + process->previous_kernel_time = process->kernel_time; + + /* store the difference of the user_time */ + user_time = process->user_time - process->previous_user_time; + kernel_time = process->kernel_time - process->previous_kernel_time; + + /* backup the process->user_time for next time around */ + process->previous_user_time = process->user_time; + process->previous_kernel_time = process->kernel_time; + + /* store only the difference of the user_time here... */ + process->user_time = user_time; + process->kernel_time = kernel_time; + } + +#ifdef BUILD_IOSTATS +#define PROCFS_TEMPLATE_IO "/proc/%d/io" + static void process_parse_io(struct process *process) { + static const char *read_bytes_str = "read_bytes:"; + static const char *write_bytes_str = "write_bytes:"; + + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; + int ps; + int rc; + char *pos, *endpos; + unsigned long long read_bytes, write_bytes; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); + + ps = open(filename, O_RDONLY); + if (ps < 0) { + /* The process must have finished in the last few jiffies! + * Or, the kernel doesn't support I/O accounting. + */ + return; + } + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + pos = strstr(line, read_bytes_str); + if (pos == nullptr) { + /* these should not happen (unless the format of the file changes) */ + return; + } + pos += strlen(read_bytes_str); + process->read_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + pos = strstr(line, write_bytes_str); + if (pos == nullptr) { return; } + pos += strlen(write_bytes_str); + process->write_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + if (process->previous_read_bytes == ULLONG_MAX) { + process->previous_read_bytes = process->read_bytes; + } + if (process->previous_write_bytes == ULLONG_MAX) { + process->previous_write_bytes = process->write_bytes; + } + + /* store the difference of the byte counts */ + read_bytes = process->read_bytes - process->previous_read_bytes; + write_bytes = process->write_bytes - process->previous_write_bytes; + + /* backup the counts for next time around */ + process->previous_read_bytes = process->read_bytes; + process->previous_write_bytes = process->write_bytes; + + /* store only the difference here... */ + process->read_bytes = read_bytes; + process->write_bytes = write_bytes; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Get process structure for process pid * + ******************************************/ + + /* This function seems to hog all of the CPU time. + * I can't figure out why - it doesn't do much. */ + static void calculate_stats(struct process *process) { + /* compute each process cpu usage by reading /proc//stat */ + process_parse_stat(process); + +#ifdef BUILD_IOSTATS + process_parse_io(process); +#endif /* BUILD_IOSTATS */ + + /* + * Check name against the exclusion list + */ + /* if (process->counted && exclusion_expression && + * !regexec(exclusion_expression, process->name, 0, 0, 0)) + * process->counted = 0; */ + } + + /****************************************** + * Update process table * + ******************************************/ + + static void update_process_table(void) { + DIR *dir; + struct dirent *entry; + + if (!(dir = opendir("/proc"))) { return; } + + info.run_procs = 0; + + /* Get list of processes from /proc directory */ + while ((entry = readdir(dir))) { + pid_t pid; + + if (sscanf(entry->d_name, "%d", &pid) > 0) { + /* compute each process cpu usage */ + calculate_stats(get_process(pid)); + } + } + + closedir(dir); + } + + void get_top_info(void) { + unsigned long long total = 0; + + total = calc_cpu_total(); /* calculate the total of the processor */ + update_process_table(); /* update the table with process list */ + calc_cpu_each(total); /* and then the percentage for each task */ +#ifdef BUILD_IOSTATS + calc_io_each(); /* percentage of I/O for each task */ +#endif /* BUILD_IOSTATS */ + } diff --git a/src/linux.cc b/src/linux.cc index a9ebd22dad..8067f88c47 100644 --- a/src/linux.cc +++ b/src/linux.cc @@ -2,9 +2,12 @@ * * Conky, a system monitor, based on torsmo * + * Any original torsmo code is licensed under the BSD license + * + * All code written since the fork of torsmo is licensed under the GPL + * * Please see COPYING for details * - * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen * Copyright (c) 2007 Toni Spets * Copyright (c) 2005-2018 Brenden Matthews, Philip Kovacs, et. al. * (see AUTHORS) @@ -24,1158 +27,1253 @@ * */ -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include #include +#include +#include #include -#include -#include -#include -#include "common.h" +#include +#include + +#include +#include + #include "conky.h" #include "diskio.h" -#include "linux.h" #include "logging.h" #include "net_stat.h" -#include "proc.h" -#include "temphelper.h" -#ifndef HAVE_CLOCK_GETTIME -#include -#endif -#include -#include -// #include -#include -#include -#include "setting.hh" +#include "openbsd.h" #include "top.h" -#include -#include -#include -#include -#include -#include -#ifdef _NET_IF_H -#define _LINUX_IF_H -#endif -#include -#include -#include - -/* The following ifdefs were adapted from gkrellm */ -#include - -#if !defined(MD_MAJOR) -#define MD_MAJOR 9 -#endif +#define MAXSHOWDEVS 16 -#if !defined(LVM_BLK_MAJOR) -#define LVM_BLK_MAJOR 58 -#endif +#define LOG1024 10 +#define pagetok(size) ((size) << pageshift) -#if !defined(NBD_MAJOR) -#define NBD_MAJOR 43 -#endif +inline void proc_find_top(struct process **cpu, struct process **mem); -#if !defined(DM_MAJOR) -#define DM_MAJOR 253 -#endif +static short cpu_setup = 0; +static kvm_t *kd = 0; -#ifdef BUILD_WLAN -#include -#endif +struct ifmibdata *data = nullptr; +size_t len = 0; -struct sysfs { - int fd; - int arg; - char devtype[256]; - char type[64]; - float factor, offset; -}; +int init_kvm = 0; +int init_sensors = 0; -char e_iface[50]; +static int kvm_init() { + if (init_kvm) { return 1; } -#define SHORTSTAT_TEMPL "%*s %llu %llu %llu" -#define LONGSTAT_TEMPL "%*s %llu %llu %llu " + kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL); + if (kd == nullptr) { + NORM_ERR("error opening kvm"); + } else { + init_kvm = 1; + } -static conky::simple_config_setting top_cpu_separate("top_cpu_separate", - false, true); + return 1; +} -/* This flag tells the linux routines to use the /proc system where possible, - * even if other api's are available, e.g. sysinfo() or getloadavg(). - * the reason for this is to allow for /proc-based distributed monitoring. - * using a flag in this manner creates less confusing code. */ -static int prefer_proc = 0; +/* note: swapmode taken from 'top' source */ +/* swapmode is rewritten by Tobias Weingartner + * to be based on the new swapctl(2) system call. */ +static int swapmode(int *used, int *total) { + struct swapent *swdev; + int nswap, rnswap, i; -/* To tell 'print_sysfs_sensor' whether to print the temperature - * in int or float */ -static const char *temp2 = "empty"; + nswap = swapctl(SWAP_NSWAP, 0, 0); + if (nswap == 0) { return 0; } -void prepare_update(void) {} + swdev = malloc(nswap * sizeof(*swdev)); + if (swdev == nullptr) { return 0; } -int update_uptime(void) { -#ifdef HAVE_SYSINFO - if (!prefer_proc) { - struct sysinfo s_info; + rnswap = swapctl(SWAP_STATS, swdev, nswap); + if (rnswap == -1) { + free(swdev); + return 0; + } - sysinfo(&s_info); - info.uptime = (double)s_info.uptime; - } else -#endif - { - static int rep = 0; - FILE *fp; + /* if rnswap != nswap, then what? */ - if (!(fp = open_file("/proc/uptime", &rep))) { - info.uptime = 0.0; - return 0; + /* Total things up */ + *total = *used = 0; + for (i = 0; i < nswap; i++) { + if (swdev[i].se_flags & SWF_ENABLE) { + *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE)); + *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE)); } - if (fscanf(fp, "%lf", &info.uptime) <= 0) info.uptime = 0; - fclose(fp); } - return 0; + free(swdev); + return 1; } int check_mount(struct text_object *obj) { - int ret = 0; - FILE *mtab; - - if (!obj->data.s) return 0; + /* stub */ + (void)obj; + return 0; +} - if ((mtab = fopen("/proc/mounts", "r"))) { - char buf1[256], buf2[129]; +void update_uptime() { + int mib[2] = {CTL_KERN, KERN_BOOTTIME}; + struct timeval boottime; + time_t now; + size_t size = sizeof(boottime); - while (fgets(buf1, 256, mtab)) { - sscanf(buf1, "%*s %128s", buf2); - if (!strcmp(obj->data.s, buf2)) { - ret = 1; - break; - } - } - fclose(mtab); + if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && + (boottime.tv_sec != 0)) { + time(&now); + info.uptime = now - boottime.tv_sec; } else { - NORM_ERR("Could not open mtab"); + NORM_ERR("Could not get uptime"); + info.uptime = 0; } - return ret; } -/* these things are also in sysinfo except Buffers: - * (that's why I'm reading them from proc) */ - -int update_meminfo(void) { - FILE *meminfo_fp; - static int rep = 0; - - /* unsigned int a; */ - char buf[256]; - - unsigned long long shmem = 0, sreclaimable = 0; - - info.mem = info.memwithbuffers = info.memmax = info.memdirty = info.swap = - info.swapfree = info.swapmax = info.bufmem = info.buffers = info.cached = - info.memfree = info.memeasyfree = 0; - - if (!(meminfo_fp = open_file("/proc/meminfo", &rep))) { return 0; } - - while (!feof(meminfo_fp)) { - if (fgets(buf, 255, meminfo_fp) == nullptr) { break; } - - if (strncmp(buf, "MemTotal:", 9) == 0) { - sscanf(buf, "%*s %llu", &info.memmax); - } else if (strncmp(buf, "MemFree:", 8) == 0) { - sscanf(buf, "%*s %llu", &info.memfree); - } else if (strncmp(buf, "SwapTotal:", 10) == 0) { - sscanf(buf, "%*s %llu", &info.swapmax); - } else if (strncmp(buf, "SwapFree:", 9) == 0) { - sscanf(buf, "%*s %llu", &info.swapfree); - } else if (strncmp(buf, "Buffers:", 8) == 0) { - sscanf(buf, "%*s %llu", &info.buffers); - } else if (strncmp(buf, "Cached:", 7) == 0) { - sscanf(buf, "%*s %llu", &info.cached); - } else if (strncmp(buf, "Dirty:", 6) == 0) { - sscanf(buf, "%*s %llu", &info.memdirty); - } else if (strncmp(buf, "Shmem:", 6) == 0) { - sscanf(buf, "%*s %llu", &shmem); - } else if (strncmp(buf, "SReclaimable:", 13) == 0) { - sscanf(buf, "%*s %llu", &sreclaimable); - } +void update_meminfo() { + static int mib[2] = {CTL_VM, VM_METER}; + struct vmtotal vmtotal; + size_t size; + int pagesize, pageshift, swap_avail, swap_used; + + pagesize = getpagesize(); + pageshift = 0; + while (pagesize > 1) { + pageshift++; + pagesize >>= 1; } - info.mem = info.memwithbuffers = info.memmax - info.memfree; - info.memeasyfree = info.memfree; - info.swap = info.swapmax - info.swapfree; + /* we only need the amount of log(2)1024 for our conversion */ + pageshift -= LOG1024; - /* Reclaimable memory: does not include shared memory, which is part of cached - but unreclaimable. Includes the reclaimable part of the Slab cache though. - Note: when shared memory is swapped out, shmem decreases and swapfree - decreases - we want this. - */ - info.bufmem = (info.cached - shmem) + info.buffers + sreclaimable; + /* get total -- systemwide main memory usage structure */ + size = sizeof(vmtotal); + if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) { + warn("sysctl failed"); + bzero(&vmtotal, sizeof(vmtotal)); + } - /* Now (info.mem - info.bufmem) is the *really used* (aka unreclaimable) - memory. When this value reaches the size of the physical RAM, and swap is - full or non-present, OOM happens. Therefore this is the value users want to - monitor, regarding their RAM. - */ + info.memmax = pagetok(vmtotal.t_rm) + pagetok(vmtotal.t_free); + info.mem = info.memwithbuffers = pagetok(vmtotal.t_rm); + info.memeasyfree = info.memfree = info.memmax - info.mem; - fclose(meminfo_fp); - return 0; + if ((swapmode(&swap_used, &swap_avail)) >= 0) { + info.swapmax = swap_avail; + info.swap = swap_used; + info.swapfree = swap_avail - swap_used; + } else { + info.swapmax = 0; + info.swap = 0; + info.swapfree = 0; + } } -void print_laptop_mode(struct text_object *obj, char *p, int p_max_size) { - FILE *fp; - int val = -1; - - (void)obj; +void update_net_stats() { + struct net_stat *ns; + double delta; + long long r, t, last_recv, last_trans; + struct ifaddrs *ifap, *ifa; + struct if_data *ifd; - if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != nullptr) { - if (fscanf(fp, "%d\n", &val) <= 0) val = 0; - fclose(fp); - } - snprintf(p, p_max_size, "%d", val); -} + /* get delta */ + delta = current_update_time - last_update_time; + if (delta <= 0.0001) { return; } -/* my system says: - * # cat /sys/block/sda/queue/scheduler - * noop [anticipatory] cfq - */ -void print_ioscheduler(struct text_object *obj, char *p, int p_max_size) { - FILE *fp; - char buf[128]; + if (getifaddrs(&ifap) < 0) { return; } - if (!obj->data.s) goto out_fail; + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL); - snprintf(buf, 127, "/sys/block/%s/queue/scheduler", obj->data.s); - if ((fp = fopen(buf, "r")) == nullptr) goto out_fail; + if (ifa->ifa_flags & IFF_UP) { + struct ifaddrs *iftmp; - while (fscanf(fp, "%127s", buf) == 1) { - if (buf[0] == '[') { - buf[strlen(buf) - 1] = '\0'; - snprintf(p, p_max_size, "%s", buf + 1); - fclose(fp); - return; - } - } - fclose(fp); -out_fail: - snprintf(p, p_max_size, "%s", "n/a"); - return; -} + ns->up = 1; + last_recv = ns->recv; + last_trans = ns->trans; -static struct { - char *iface; - char *ip; - int count; -} gw_info; - -#define SAVE_SET_STRING(x, y) \ - if (x && strcmp((char *)x, (char *)y)) { \ - free(x); \ - x = strndup("multiple", text_buffer_size.get(*state)); \ - } else if (!x) { \ - x = strndup(y, text_buffer_size.get(*state)); \ - } + if (ifa->ifa_addr->sa_family != AF_LINK) { continue; } -void update_gateway_info_failure(const char *reason) { - if (reason != nullptr) { perror(reason); } - // 2 pointers to 1 location causes a crash when we try to free them both - gw_info.iface = strndup("failed", text_buffer_size.get(*state)); - gw_info.ip = strndup("failed", text_buffer_size.get(*state)); -} + for (iftmp = ifa->ifa_next; + iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0; + iftmp = iftmp->ifa_next) { + if (iftmp->ifa_addr->sa_family == AF_INET) { + memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len); + } + } -/* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT */ -#define RT_ENTRY_FORMAT "%63s %lx %lx %x %*d %*d %*d %lx %*d %*d %*d\n" + ifd = (struct if_data *)ifa->ifa_data; + r = ifd->ifi_ibytes; + t = ifd->ifi_obytes; -int update_gateway_info(void) { - FILE *fp; - struct in_addr ina; - char iface[64]; - unsigned long dest, gate, mask; - unsigned int flags; + if (r < ns->last_read_recv) { + ns->recv += ((long long)4294967295U - ns->last_read_recv) + r; + } else { + ns->recv += (r - ns->last_read_recv); + } - free_and_zero(gw_info.iface); - free_and_zero(gw_info.ip); - gw_info.count = 0; + ns->last_read_recv = r; - if ((fp = fopen("/proc/net/route", "r")) == nullptr) { - update_gateway_info_failure("fopen()"); - return 0; - } + if (t < ns->last_read_trans) { + ns->trans += (long long)4294967295U - ns->last_read_trans + t; + } else { + ns->trans += (t - ns->last_read_trans); + } - /* skip over the table header line, which is always present */ - if (fscanf(fp, "%*[^\n]\n") < 0) { - fclose(fp); - return 0; - } + ns->last_read_trans = t; - while (!feof(fp)) { - if (fscanf(fp, RT_ENTRY_FORMAT, iface, &dest, &gate, &flags, &mask) != 5) { - update_gateway_info_failure("fscanf()"); - break; - } - if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate)) { - gw_info.count++; - snprintf(e_iface, 49, "%s", iface); - SAVE_SET_STRING(gw_info.iface, iface) - ina.s_addr = gate; - SAVE_SET_STRING(gw_info.ip, inet_ntoa(ina)) + /* calculate speeds */ + ns->recv_speed = (ns->recv - last_recv) / delta; + ns->trans_speed = (ns->trans - last_trans) / delta; + } else { + ns->up = 0; } } - fclose(fp); - return 0; + + freeifaddrs(ifap); } -void free_gateway_info(struct text_object *obj) { - (void)obj; +int update_total_processes() { + int n_processes; - free_and_zero(gw_info.iface); - free_and_zero(gw_info.ip); - memset(&gw_info, 0, sizeof(gw_info)); -} + kvm_init(); + kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes); -int gateway_exists(struct text_object *obj) { - (void)obj; - return !!gw_info.count; + info.procs = n_processes; } -void print_gateway_iface(struct text_object *obj, char *p, int p_max_size) { - (void)obj; +void update_running_processes() { + struct kinfo_proc2 *p; + int n_processes; + int i, cnt = 0; - snprintf(p, p_max_size, "%s", gw_info.iface); -} + kvm_init(); + int max_size = sizeof(struct kinfo_proc2); -void print_gateway_ip(struct text_object *obj, char *p, int p_max_size) { - (void)obj; + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, max_size, &n_processes); + for (i = 0; i < n_processes; i++) { + if (p[i].p_stat == SRUN) { cnt++; } + } - snprintf(p, p_max_size, "%s", gw_info.ip); + info.run_procs = cnt; } -/** - * Parses information from /proc/net/dev and stores them in ??? - * - * For the output format of /proc/net/dev @see http://linux.die.net/man/5/proc - * - * @return always returns 0. May change in the future, e.g. returning non zero - * if some error happened - **/ -int update_net_stats(void) { - update_gateway_info(); - FILE *net_dev_fp; - static int rep = 0; - /* variably to notify the parts averaging the download speed, that this - * is the first call ever to this function. This variable can't be used - * to decide if this is the first time an interface was parsed as there - * are many interfaces, which can be activated and deactivated at arbitrary - * times */ - static char first = 1; - - // FIXME: arbitrary size chosen to keep code simple. - int i, i2; - unsigned int curtmp1, curtmp2; - unsigned int k; - struct ifconf conf; - char buf[256]; - double delta; +/* new SMP code can be enabled by commenting the following line */ +#define OLDCPU + +#ifdef OLDCPU +struct cpu_load_struct { + unsigned long load[5]; +}; + +struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}}; +long cpu_used, oldtotal, oldused; +#else +#include +int64_t *fresh = nullptr; -#ifdef BUILD_WLAN - // wireless info variables - int skfd, has_bitrate = 0; - struct wireless_info *winfo; - struct iwreq wrq; +/* XXX is 8 enough? - What's the constant for MAXCPU? */ +/* allocate this with malloc would be better */ +int64_t oldtotal[8], oldused[8]; #endif - /* get delta */ - delta = current_update_time - last_update_time; - if (delta <= 0.0001) { return 0; } +void get_cpu_count() { + int cpu_count = 1; /* default to 1 cpu */ +#ifndef OLDCPU + int mib[2] = {CTL_HW, HW_NCPU}; + size_t len = sizeof(cpu_count); - /* open file /proc/net/dev. If not something went wrong, clear all - * network statistics */ - if (!(net_dev_fp = open_file("/proc/net/dev", &rep))) { - clear_net_stats(); - return 0; + if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) { + NORM_ERR("error getting cpu count, defaulting to 1"); } - /* ignore first two header lines in file /proc/net/dev. If somethings - * goes wrong, e.g. end of file reached, quit. - * (Why isn't clear_net_stats called for this case ??? */ - char *one = fgets(buf, 255, net_dev_fp); - char *two = fgets(buf, 255, net_dev_fp); - if (!one || /* garbage */ - !two) { /* garbage (field names) */ - fclose(net_dev_fp); - return 0; +#endif + info.cpu_count = cpu_count; + + info.cpu_usage = malloc(info.cpu_count * sizeof(float)); + if (info.cpu_usage == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } + +#ifndef OLDCPU + assert(fresh == nullptr); /* XXX Is this leaking memory? */ + /* XXX Where shall I free this? */ + if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) { + CRIT_ERR(nullptr, NULL, "calloc"); } +#endif +} - /* read each interface */ - for (i2 = 0; i2 < MAX_NET_INTERFACES; i2++) { - struct net_stat *ns; - char *s, *p; - char temp_addr[18]; - long long r, t, last_recv, last_trans; - - /* quit only after all non-header lines from /proc/net/dev parsed */ - if (fgets(buf, 255, net_dev_fp) == nullptr) { break; } - p = buf; - /* change char * p to first non-space character, which is the beginning - * of the interface name */ - while (*p != '\0' && isspace((unsigned char)*p)) { p++; } - - s = p; - - /* increment p until the end of the interface name has been reached */ - while (*p != '\0' && *p != ':') { p++; } - if (*p == '\0') { continue; } - /* replace ':' with '\0' in output of /proc/net/dev */ - *p = '\0'; - p++; - - /* get pointer to interface statistics with the interface name in s */ - ns = get_net_stat(s, nullptr, NULL); - ns->up = 1; - memset(&(ns->addr.sa_data), 0, 14); - - memset(ns->addrs, 0, - 17 * MAX_NET_INTERFACES + - 1); /* Up to 17 chars per ip, max MAX_NET_INTERFACES interfaces. - Nasty memory usage... */ - - /* bytes packets errs drop fifo frame compressed multicast|bytes ... */ - sscanf(p, "%lld %*d %*d %*d %*d %*d %*d %*d %lld", - &r, &t); - - /* if the interface is parsed the first time, then set recv and trans - * to currently received, meaning the change in network traffic is 0 */ - if (ns->last_read_recv == -1) { - ns->recv = r; - first = 1; - ns->last_read_recv = r; - } - if (ns->last_read_trans == -1) { - ns->trans = t; - first = 1; - ns->last_read_trans = t; - } - /* move current traffic statistic to last thereby obsoleting the - * current statistic */ - last_recv = ns->recv; - last_trans = ns->trans; - - /* If recv or trans is less than last time, an overflow happened. - * In that case set the last traffic to the current one, don't set - * it to 0, else a spike in the download and upload speed will occur! */ - if (r < ns->last_read_recv) { - last_recv = r; - } else { - ns->recv += (r - ns->last_read_recv); - } - ns->last_read_recv = r; +void update_cpu_usage() { +#ifdef OLDCPU + int mib[2] = {CTL_KERN, KERN_CPTIME}; + long used, total; + long cp_time[CPUSTATES]; + size_t len = sizeof(cp_time); +#else + size_t size; + unsigned int i; +#endif - if (t < ns->last_read_trans) { - last_trans = t; - } else { - ns->trans += (t - ns->last_read_trans); - } - ns->last_read_trans = t; + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if ((cpu_setup == 0) || (!info.cpu_usage)) { + get_cpu_count(); + cpu_setup = 1; + } - /*** ip addr patch ***/ - i = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); +#ifdef OLDCPU + if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) { + NORM_ERR("Cannot get kern.cp_time"); + } - conf.ifc_buf = (char *)malloc(sizeof(struct ifreq) * MAX_NET_INTERFACES); - conf.ifc_len = sizeof(struct ifreq) * MAX_NET_INTERFACES; - memset(conf.ifc_buf, 0, conf.ifc_len); + fresh.load[0] = cp_time[CP_USER]; + fresh.load[1] = cp_time[CP_NICE]; + fresh.load[2] = cp_time[CP_SYS]; + fresh.load[3] = cp_time[CP_IDLE]; + fresh.load[4] = cp_time[CP_IDLE]; - ioctl((long)i, SIOCGIFCONF, &conf); + used = fresh.load[0] + fresh.load[1] + fresh.load[2]; + total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3]; - for (k = 0; k < conf.ifc_len / sizeof(struct ifreq); k++) { - struct net_stat *ns2; + if ((total - oldtotal) != 0) { + info.cpu_usage[0] = ((double)(used - oldused)) / (double)(total - oldtotal); + } else { + info.cpu_usage[0] = 0; + } - if (!(((struct ifreq *)conf.ifc_buf) + k)) break; + oldused = used; + oldtotal = total; +#else + if (info.cpu_count > 1) { + size = CPUSTATES * sizeof(int64_t); + for (i = 0; i < info.cpu_count; i++) { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i}; + if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) < + 0) { + NORM_ERR("sysctl kern.cp_time2 failed"); + } + } + } else { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME}; + long cp_time_tmp[CPUSTATES]; - ns2 = get_net_stat(((struct ifreq *)conf.ifc_buf)[k].ifr_ifrn.ifrn_name, - nullptr, NULL); - ns2->addr = ((struct ifreq *)conf.ifc_buf)[k].ifr_ifru.ifru_addr; - sprintf(temp_addr, "%u.%u.%u.%u, ", ns2->addr.sa_data[2] & 255, - ns2->addr.sa_data[3] & 255, ns2->addr.sa_data[4] & 255, - ns2->addr.sa_data[5] & 255); - if (nullptr == strstr(ns2->addrs, temp_addr)) - strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17); + size = sizeof(cp_time_tmp); + if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) { + NORM_ERR("sysctl kern.cp_time failed"); } - close((long)i); + for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t)cp_time_tmp[i]; } + } - free(conf.ifc_buf); - /*** end ip addr patch ***/ + /* XXX Do sg with this int64_t => long => double ? float hell. */ + for (i = 0; i < info.cpu_count; i++) { + int64_t used, total; + int at = i * CPUSTATES; - if (!first) { - /* calculate instantenous speeds */ - ns->net_rec[0] = (ns->recv - last_recv) / delta; - ns->net_trans[0] = (ns->trans - last_trans) / delta; - } + used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; + total = used + fresh[at + CP_IDLE]; - curtmp1 = 0; - curtmp2 = 0; - /* get an average over the last speed samples */ - int samples = net_avg_samples.get(*state); - /* is OpenMP actually useful here? How large is samples? > 1000 ? */ -#ifdef HAVE_OPENMP -#pragma omp parallel for reduction(+ : curtmp1, curtmp2) schedule(dynamic, 10) -#endif /* HAVE_OPENMP */ - for (i = 0; i < samples; i++) { - curtmp1 = curtmp1 + ns->net_rec[i]; - curtmp2 = curtmp2 + ns->net_trans[i]; - } - ns->recv_speed = curtmp1 / (double)samples; - ns->trans_speed = curtmp2 / (double)samples; - if (samples > 1) { -#ifdef HAVE_OPENMP -#pragma omp parallel for schedule(dynamic, 10) -#endif /* HAVE_OPENMP */ - for (i = samples; i > 1; i--) { - ns->net_rec[i - 1] = ns->net_rec[i - 2]; - ns->net_trans[i - 1] = ns->net_trans[i - 2]; - } + if ((total - oldtotal[i]) != 0) { + info.cpu_usage[i] = + ((double)(used - oldused[i])) / (double)(total - oldtotal[i]); + } else { + info.cpu_usage[i] = 0; } -#ifdef BUILD_WLAN - /* update wireless info */ - winfo = (struct wireless_info *)malloc(sizeof(struct wireless_info)); - memset(winfo, 0, sizeof(struct wireless_info)); + oldused[i] = used; + oldtotal[i] = total; + } +#endif +} - skfd = iw_sockets_open(); - if (iw_get_basic_config(skfd, s, &(winfo->b)) > -1) { - // set present winfo variables - if (iw_get_range_info(skfd, s, &(winfo->range)) >= 0) { - winfo->has_range = 1; - } - if (iw_get_stats(skfd, s, &(winfo->stats), &winfo->range, - winfo->has_range) >= 0) { - winfo->has_stats = 1; - } - if (iw_get_ext(skfd, s, SIOCGIWAP, &wrq) >= 0) { - winfo->has_ap_addr = 1; - memcpy(&(winfo->ap_addr), &(wrq.u.ap_addr), sizeof(sockaddr)); - } +void free_cpu(struct text_object *) { /* not used */ } - // get bitrate - if (iw_get_ext(skfd, s, SIOCGIWRATE, &wrq) >= 0) { - memcpy(&(winfo->bitrate), &(wrq.u.bitrate), sizeof(iwparam)); - iw_print_bitrate(ns->bitrate, 16, winfo->bitrate.value); - has_bitrate = 1; - } +void update_load_average() { + double v[3]; - // get link quality - if (winfo->has_range && winfo->has_stats && - ((winfo->stats.qual.level != 0) || - (winfo->stats.qual.updated & IW_QUAL_DBM))) { - if (!(winfo->stats.qual.updated & IW_QUAL_QUAL_INVALID)) { - ns->link_qual = winfo->stats.qual.qual; - ns->link_qual_max = winfo->range.max_qual.qual; - } - } + getloadavg(v, 3); - // get ap mac - if (winfo->has_ap_addr) { iw_sawap_ntop(&winfo->ap_addr, ns->ap); } + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; +} - // get essid - if (winfo->b.has_essid) { - if (winfo->b.essid_on) { - snprintf(ns->essid, 32, "%s", winfo->b.essid); - } else { - snprintf(ns->essid, 32, "%s", "off/any"); - } - } - // get channel and freq - if (winfo->b.has_freq) { - if (winfo->has_range == 1) { - ns->channel = iw_freq_to_channel(winfo->b.freq, &(winfo->range)); - iw_print_freq_value(ns->freq, 16, winfo->b.freq); - } else { - ns->channel = 0; - ns->freq[0] = 0; - } - } +#define OBSD_MAX_SENSORS 256 +static struct obsd_sensors_struct { + int device; + float temp[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + unsigned int fan[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + float volt[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; +} obsd_sensors; - snprintf(ns->mode, 16, "%s", iw_operation_mode[winfo->b.mode]); - } - iw_sockets_close(skfd); - free(winfo); -#endif - } +static conky::simple_config_setting sensor_device("sensor_device", 0, + false); -#ifdef BUILD_IPV6 - FILE *file; - char v6addr[33]; - char devname[21]; - unsigned int netmask, scope; - struct net_stat *ns; - struct v6addr *lastv6; - // remove the old v6 addresses otherwise they are listed multiple times - for (unsigned int i = 0; i < MAX_NET_INTERFACES; i++) { - ns = &netstats[i]; - while (ns->v6addrs != nullptr) { - lastv6 = ns->v6addrs; - ns->v6addrs = ns->v6addrs->next; - free(lastv6); - } - } - if ((file = fopen(PROCDIR "/net/if_inet6", "r")) != nullptr) { - while (fscanf(file, "%32s %*02x %02x %02x %*02x %20s\n", v6addr, &netmask, - &scope, devname) != EOF) { - ns = get_net_stat(devname, nullptr, NULL); - if (ns->v6addrs == nullptr) { - lastv6 = (struct v6addr *)malloc(sizeof(struct v6addr)); - ns->v6addrs = lastv6; - } else { - lastv6 = ns->v6addrs; - while (lastv6->next) lastv6 = lastv6->next; - lastv6->next = (struct v6addr *)malloc(sizeof(struct v6addr)); - lastv6 = lastv6->next; +/* read sensors from sysctl */ +void update_obsd_sensors() { + int sensor_cnt, dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0}; + struct sensor sensor; + struct sensordev sensordev; + size_t slen, sdlen; + enum sensor_type type; + + slen = sizeof(sensor); + sdlen = sizeof(sensordev); + + sensor_cnt = 0; + + dev = obsd_sensors.device; // FIXME: read more than one device + + /* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */ + mib[2] = dev; + if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + return; + // continue; + } + for (type = 0; type < SENSOR_MAX_TYPES; type++) { + mib[3] = type; + for (numt = 0; numt < sensordev.maxnumt[type]; numt++) { + mib[4] = numt; + if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + continue; } - for (int i = 0; i < 16; i++) - sscanf(v6addr + 2 * i, "%2hhx", &(lastv6->addr.s6_addr[i])); - lastv6->netmask = netmask; - switch (scope) { - case 0: // global - lastv6->scope = 'G'; - break; - case 16: // host-local - lastv6->scope = 'H'; - break; - case 32: // link-local - lastv6->scope = 'L'; + if (sensor.flags & SENSOR_FINVALID) { continue; } + + switch (type) { + case SENSOR_TEMP: + obsd_sensors.temp[dev][sensor.numt] = + (sensor.value - 273150000) / 1000000.0; break; - case 64: // site-local - lastv6->scope = 'S'; + case SENSOR_FANRPM: + obsd_sensors.fan[dev][sensor.numt] = sensor.value; break; - case 128: // compat - lastv6->scope = 'C'; + case SENSOR_VOLTS_DC: + obsd_sensors.volt[dev][sensor.numt] = sensor.value / 1000000.0; break; default: - lastv6->scope = '?'; + break; } - lastv6->next = nullptr; + + sensor_cnt++; } - fclose(file); } -#endif /* BUILD_IPV6 */ + /* } */ - first = 0; - - fclose(net_dev_fp); - return 0; + init_sensors = 1; } -int result; - -int update_total_processes(void) { - DIR *dir; - struct dirent *entry; - int ignore1; - char ignore2; - - info.procs = 0; - dir = opendir("/proc"); - if (dir) { - while ((entry = readdir(dir))) { - if (sscanf(entry->d_name, "%d%c", &ignore1, &ignore2) == 1) { - info.procs++; - } - } - closedir(dir); - } - return 0; +void parse_obsd_sensor(struct text_object *obj, const char *arg) { + if (!isdigit((unsigned char)arg[0]) || atoi(&arg[0]) < 0 || + atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) { + obj->data.l = 0; + NORM_ERR("Invalid sensor number!"); + } else + obj->data.l = atoi(&arg[0]); } -int update_threads(void) { -#ifdef HAVE_SYSINFO - if (!prefer_proc) { - struct sysinfo s_info; +void print_obsd_sensors_temp(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + temp_print(p, p_max_size, obsd_sensors.temp[obsd_sensors.device][obj->data.l], + TEMP_CELSIUS, 1); +} - sysinfo(&s_info); - info.threads = s_info.procs; - } else -#endif - { - static int rep = 0; - FILE *fp; +void print_obsd_sensors_fan(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%d", + obsd_sensors.fan[obsd_sensors.device][obj->data.l]); +} - if (!(fp = open_file("/proc/loadavg", &rep))) { - info.threads = 0; - return 0; - } - if (fscanf(fp, "%*f %*f %*f %*d/%hu", &info.threads) <= 0) info.threads = 0; - fclose(fp); - } - return 0; +void print_obsd_sensors_volt(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%.2f", + obsd_sensors.volt[obsd_sensors.device][obj->data.l]); } -#define CPU_SAMPLE_COUNT 15 -struct cpu_info { - unsigned long long cpu_user; - unsigned long long cpu_system; - unsigned long long cpu_nice; - unsigned long long cpu_idle; - unsigned long long cpu_iowait; - unsigned long long cpu_irq; - unsigned long long cpu_softirq; - unsigned long long cpu_steal; - unsigned long long cpu_total; - unsigned long long cpu_active_total; - unsigned long long cpu_last_total; - unsigned long long cpu_last_active_total; - double cpu_val[CPU_SAMPLE_COUNT]; -}; -static short cpu_setup = 0; +/* chipset vendor */ +void get_obsd_vendor(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char vendor[64]; + size_t size = sizeof(vendor); -/* Determine if this kernel gives us "extended" statistics information in - * /proc/stat. - * Kernels around 2.5 and earlier only reported user, system, nice, and - * idle values in proc stat. - * Kernels around 2.6 and greater report these PLUS iowait, irq, softirq, - * and steal */ -void determine_longstat(char *buf) { - unsigned long long iowait = 0; - - KFLAG_SETOFF(KFLAG_IS_LONGSTAT); - /* scanf will either return -1 or 1 because there is only 1 assignment */ - if (sscanf(buf, "%*s %*d %*d %*d %*d %llu", &iowait) > 0) { - KFLAG_SETON(KFLAG_IS_LONGSTAT); - } -} + (void)obj; -void determine_longstat_file(void) { -#define MAX_PROCSTAT_LINELEN 255 - FILE *stat_fp; - static int rep = 0; - char buf[MAX_PROCSTAT_LINELEN + 1]; - - if (not(stat_fp = open_file("/proc/stat", &rep))) return; - while (not feof(stat_fp)) { - if (fgets(buf, MAX_PROCSTAT_LINELEN, stat_fp) == nullptr) break; - if (strncmp(buf, "cpu", 3) == 0) { - determine_longstat(buf); - break; - } + mib[0] = CTL_HW; + mib[1] = HW_VENDOR; + + if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) { + NORM_ERR("error reading vendor"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", vendor); } - fclose(stat_fp); } -void get_cpu_count(void) { - FILE *stat_fp; - static int rep = 0; - char buf[256]; - char *str1, *str2, *token, *subtoken; - char *saveptr1, *saveptr2; - int subtoken1 = -1; - int subtoken2 = -1; +/* chipset name */ +void get_obsd_product(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char product[64]; + size_t size = sizeof(product); - if (info.cpu_usage) { return; } + (void)obj; - if (!(stat_fp = open_file("/sys/devices/system/cpu/present", &rep))) { - return; - } + mib[0] = CTL_HW; + mib[1] = HW_PRODUCT; - info.cpu_count = 0; - - while (!feof(stat_fp)) { - if (fgets(buf, 255, stat_fp) == nullptr) { break; } - - // Do some parsing here to handle skipped cpu numbers. For example, - // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports - // "0,3-7". I assume that chip is really an 8-core die with two cores - // disabled... Presumably you could also get "0,3-4,6", and other - // combos too... - for (str1 = buf;; str1 = nullptr) { - token = strtok_r(str1, ",", &saveptr1); - if (token == nullptr) break; - ++info.cpu_count; - - subtoken1 = -1; - subtoken2 = -1; - for (str2 = token;; str2 = nullptr) { - subtoken = strtok_r(str2, "-", &saveptr2); - if (subtoken == nullptr) break; - if (subtoken1 < 0) - subtoken1 = atoi(subtoken); - else - subtoken2 = atoi(subtoken); - } - if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; - } + if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) { + NORM_ERR("error reading product"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", product); } - info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); - - fclose(stat_fp); } -#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" -#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" +/* void */ +char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + int freq = cpu; + int mib[2] = {CTL_HW, HW_CPUSPEED}; -int update_stat(void) { - FILE *stat_fp; - static int rep = 0; - static struct cpu_info *cpu = nullptr; - char buf[256]; - int i; - unsigned int idx; - double curtmp; - const char *stat_template = nullptr; - unsigned int malloc_cpu_size = 0; - extern void *global_cpu; - - static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; - static double last_stat_update = 0.0; - float cur_total = 0.0; - - /* since we use wrappers for this function, the update machinery - * can't eliminate double invocations of this function. Check for - * them here, otherwise cpu_usage counters are freaking out. */ - pthread_mutex_lock(&last_stat_update_mutex); - if (last_stat_update == current_update_time) { - pthread_mutex_unlock(&last_stat_update_mutex); + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { return 0; } - last_stat_update = current_update_time; - pthread_mutex_unlock(&last_stat_update_mutex); - /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ - if (!cpu_setup || !info.cpu_usage) { - get_cpu_count(); - cpu_setup = 1; - } + size_t size = sizeof(freq); - if (!stat_template) { - stat_template = - KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) { + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + } else { + snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f); } - if (!global_cpu) { - malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); - cpu = (struct cpu_info *)malloc(malloc_cpu_size); - memset(cpu, 0, malloc_cpu_size); - global_cpu = cpu; - } + return 1; +} - if (!(stat_fp = open_file("/proc/stat", &rep))) { - info.run_threads = 0; - if (info.cpu_usage) { - memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); - } - return 0; - } +#if 0 +/* deprecated, will rewrite this soon in update_net_stats() -hifi */ +void update_wifi_stats() +{ + struct net_stat *ns; + struct ifaddrs *ifap, *ifa; + struct ifmediareq ifmr; + struct ieee80211_nodereq nr; + struct ieee80211_bssid bssid; + int s, ibssid; + + /* Get iface table */ + if (getifaddrs(&ifap) < 0) { + return; + } + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *) ifa->ifa_name); + + s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + /* Get media type */ + bzero(&ifmr, sizeof(ifmr)); + strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ); + if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) { + close(s); + return; + } + + /* We can monitor only wireless interfaces + * which are not in hostap mode */ + if ((ifmr.ifm_active & IFM_IEEE80211) + && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) { + /* Get wi status */ + + memset(&bssid, 0, sizeof(bssid)); + strlcpy(bssid.i_name, ifa->ifa_name, sizeof(bssid.i_name)); + ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + + bzero(&nr, sizeof(nr)); + bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); + strlcpy(nr.nr_ifname, ifa->ifa_name, sizeof(nr.nr_ifname)); + + if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { + ns->linkstatus = nr.nr_rssi; + } + } +cleanup: + close(s); + } +} +#endif - idx = 0; - while (!feof(stat_fp)) { - if (fgets(buf, 255, stat_fp) == nullptr) { break; } +void clear_diskio_stats() {} - if (strncmp(buf, "procs_running ", 14) == 0) { - sscanf(buf, "%*s %hu", &info.run_threads); - } else if (strncmp(buf, "cpu", 3) == 0) { - double delta; - if (isdigit((unsigned char)buf[3])) { - idx++; // just increment here since the CPU index can skip numbers - } else { - idx = 0; - } - if (idx > info.cpu_count) { continue; } - sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), - &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), - &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), - &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); +struct diskio_stat *prepare_diskio_stat(const char *s) {} - cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + - cpu[idx].cpu_system + cpu[idx].cpu_idle + - cpu[idx].cpu_iowait + cpu[idx].cpu_irq + - cpu[idx].cpu_softirq + cpu[idx].cpu_steal; +void update_diskio() { return; /* XXX: implement? hifi: not sure how */ } - cpu[idx].cpu_active_total = - cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); +/* While topless is obviously better, top is also not bad. */ - delta = current_update_time - last_update_time; +void get_top_info(void) { + struct kinfo_proc2 *p; + struct process *proc; + int n_processes; + int i; - if (delta <= 0.001) { break; } + kvm_init(); - cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); - if (cur_total == 0.0) { - cpu[idx].cpu_val[0] = 1.0; - } else { - cpu[idx].cpu_val[0] = - (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / - cur_total; - } - curtmp = 0; + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), + &n_processes); - int samples = cpu_avg_samples.get(*state); -#ifdef HAVE_OPENMP -#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) -#endif /* HAVE_OPENMP */ - for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } - info.cpu_usage[idx] = curtmp / samples; + for (i = 0; i < n_processes; i++) { + if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) { + proc = find_process(p[i].p_pid); + if (!proc) proc = new_process(p[i].p_pid); - cpu[idx].cpu_last_total = cpu[idx].cpu_total; - cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; -#ifdef HAVE_OPENMP -#pragma omp parallel for schedule(dynamic, 10) -#endif /* HAVE_OPENMP */ - for (i = samples - 1; i > 0; i--) { - cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; - } + proc->time_stamp = g_time; + proc->name = strndup(p[i].p_comm, text_buffer_size); + proc->amount = 100.0 * p[i].p_pctcpu / FSCALE; + /* TODO: vsize, rss, total_cpu_time */ } } - fclose(stat_fp); - return 0; } -int update_running_processes(void) { - update_stat(); - return 0; -} +/* empty stubs so conky links */ +void prepare_update() {} -int update_cpu_usage(void) { - update_stat(); - return 0; -} +int get_entropy_avail(unsigned int *val) { return 1; } -void free_cpu(struct text_object *) { +int get_entropy_poolsize(unsigned int *val) { return 1; } +WRITE] / 512); +for (cur = stats.next; cur; cur = cur->next) { + if (cur->dev && !strcmp(device_name, cur->dev)) { + update_diskio_values(cur, reads, writes); + break; + } } +} +update_diskio_values(&stats, total_reads, total_writes); -// fscanf() that reads floats with points even if you are using a locale where -// floats are with commas -int fscanf_no_i18n(FILE *stream, const char *format, ...) { - int returncode; - va_list ap; - -#ifdef BUILD_I18N - const char *oldlocale = setlocale(LC_NUMERIC, nullptr); +free(dev_select); +} - setlocale(LC_NUMERIC, "C"); -#endif - va_start(ap, format); - returncode = vfscanf(stream, format, ap); - va_end(ap); -#ifdef BUILD_I18N - setlocale(LC_NUMERIC, oldlocale); -#endif - return returncode; +if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); } +free(statinfo_cur.dinfo); +return 0; } -int update_load_average(void) { -#ifdef HAVE_GETLOADAVG - if (!prefer_proc) { - double v[3]; +/* While topless is obviously better, top is also not bad. */ - getloadavg(v, 3); - info.loadavg[0] = (float)v[0]; - info.loadavg[1] = (float)v[1]; - info.loadavg[2] = (float)v[2]; - } else -#endif - { - static int rep = 0; - FILE *fp; +void get_top_info(void) { + struct kinfo_proc *p; + struct process *proc; + int n_processes; + int i; - if (!(fp = open_file("/proc/loadavg", &rep))) { - info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; - return 0; + std::lock_guard guard(kvm_proc_mutex); + p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) { + proc = get_process(p[i].ki_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; + proc->vsize = p[i].ki_size; + proc->rss = (p[i].ki_rssize * getpagesize()); + /* ki_runtime is in microseconds, total_cpu_time in centiseconds. + * Therefore we divide by 10000. */ + proc->total_cpu_time = p[i].ki_runtime / 10000; } - if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], - &info.loadavg[2]) < 0) - info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; - fclose(fp); } - return 0; } -/***********************************************************/ -/***********************************************************/ -/***********************************************************/ +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("remaining", buffer, 9)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 9, n - 9); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} -static int no_dots(const struct dirent *d) { - if (d->d_name[0] == '.') { return 0; } +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; return 1; } -static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { - struct dirent **namelist; - int i, n; +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} +et_apm_adapter(void) { + int fd; + struct apm_info a_info; + char *out; - n = scandir(dir, &namelist, no_dots, alphasort); - if (n < 0) { - if (!rep || !*rep) { - NORM_ERR("scandir for %s: %s", dir, strerror(errno)); - if (rep) { *rep = 1; } - } - return 0; - } else { - if (n == 0) { return 0; } + out = (char *)calloc(16, sizeof(char)); - strncpy(s, namelist[0]->d_name, 255); - s[255] = '\0'; + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } -#ifdef HAVE_OPENMP -#pragma omp parallel for schedule(dynamic, 10) -#endif /* HAVE_OPENMP */ - for (i = 0; i < n; i++) { free(namelist[i]); } - free(namelist); + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); - return 1; + switch (a_info.ai_acline) { + case 0: + strncpy(out, "off-line", 16); + return out; + break; + case 1: + if (a_info.ai_batt_stat == 3) { + strncpy(out, "charging", 16); + return out; + } else { + strncpy(out, "on-line", 16); + return out; + } + break; + default: + strncpy(out, "unknown", 16); + return out; + break; } } -static int open_sysfs_sensor(const char *dir, const char *dev, const char *type, - int n, int *divisor, char *devtype) { - char path[256]; - char buf[256]; +char *get_apm_battery_life(void) { int fd; - int divfd; + u_int batt_life; + struct apm_info a_info; + char *out; - memset(buf, 0, sizeof(buf)); + out = (char *)calloc(16, sizeof(char)); - /* if device is nullptr or *, get first */ - if (dev == nullptr || strcmp(dev, "*") == 0) { - static int rep = 0; - - if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } - dev = buf; + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; } - if (strcmp(dir, "/sys/class/hwmon/") == 0) { - if (*buf) { - /* buf holds result from get_first_file_in_a_directory() above, - * e.g. "hwmon0" -- append "/device" */ - strncat(buf, "/device", 256); - } else { - /* dev holds device number N as a string, - * e.g. "0", -- convert to "hwmon0/device" */ - sprintf(buf, "hwmon%s/device", dev); - dev = buf; - } + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; } + close(fd); - /* change vol to in, tempf to temp */ - if (strcmp(type, "vol") == 0) { - type = "in"; - } else if (strcmp(type, "tempf") == 0) { - type = "temp"; - } else if (strcmp(type, "temp2") == 0) { - type = "temp"; + batt_life = a_info.ai_batt_life; + if (batt_life == APM_UNKNOWN) { + strncpy(out, "unknown", 16); + } else if (batt_life <= 100) { + snprintf(out, 16, "%d%%", batt_life); + return out; + } else { + strncpy(out, "ERR", 16); } - /* construct path */ - snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + return out; +} - /* first, attempt to open file in /device */ - fd = open(path, O_RDONLY); +char *get_apm_battery_time(void) { + int fd; + int batt_time; + int h, m, s; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); if (fd < 0) { - /* if it fails, strip the /device from dev and attempt again */ - buf[strlen(buf) - 7] = 0; - snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); - fd = open(path, O_RDONLY); - if (fd < 0) { - NORM_ERR( - "can't open '%s': %s\nplease check your device or remove this " - "var from " PACKAGE_NAME, - path, strerror(errno)); - } + strncpy(out, "ERR", 16); + return out; } - strncpy(devtype, path, 255); - - if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || - strcmp(type, "tempf") == 0) { - *divisor = 1; - } else { - *divisor = 0; + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; } - /* fan does not use *_div as a read divisor */ - if (strcmp("fan", type) == 0) { return fd; } + close(fd); - /* test if *_div file exist, open it and use it as divisor */ - if (strcmp(type, "tempf") == 0) { - snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + batt_time = a_info.ai_batt_time; + + if (batt_time == -1) { + strncpy(out, "unknown", 16); } else { - snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + h = batt_time; + s = h % 60; + h /= 60; + m = h % 60; + h /= 60; + snprintf(out, 16, "%2d:%02d:%02d", h, m, s); } - divfd = open(path, O_RDONLY); - if (divfd > 0) { - /* read integer */ - char divbuf[64]; - int divn; - - divn = read(divfd, divbuf, 63); - /* should read until n == 0 but I doubt that kernel will give these - * in multiple pieces. :) */ - if (divn < 0) { - NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); - } else { - divbuf[divn] = '\0'; - *divisor = atoi(divbuf); - } - close(divfd); + return out; +} + +#endif + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'A'; + memmove(buffer + 1, buffer + 12, n - 12); } +} - return fd; +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; } -static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { - int val = 0; +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + stat_fp) == nullptr) { break; } + + // Do some parsing here to handle skipped cpu numbers. For example, + // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports + // "0,3-7". I assume that chip is really an 8-core die with two cores + // disabled... Presumably you could also get "0,3-4,6", and other + // combos too... + for (str1 = buf;; str1 = nullptr) { + token = strtok_r(str1, ",", &saveptr1); + if (token == nullptr) break; + ++info.cpu_count; + + subtoken1 = -1; + subtoken2 = -1; + for (str2 = token;; str2 = nullptr) { + subtoken = strtok_r(str2, "-", &saveptr2); + if (subtoken == nullptr) break; + if (subtoken1 < 0) + subtoken1 = atoi(subtoken); + else + subtoken2 = atoi(subtoken); + } + if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; + } + } + info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + + fclose(stat_fp); + } - if (*fd <= 0) { return 0; } +#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" +#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" - lseek(*fd, 0, SEEK_SET); + int update_stat(void) { + FILE *stat_fp; + static int rep = 0; + static struct cpu_info *cpu = nullptr; + char buf[256]; + int i; + unsigned int idx; + double curtmp; + const char *stat_template = nullptr; + unsigned int malloc_cpu_size = 0; + extern void *global_cpu; + + static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; + static double last_stat_update = 0.0; + float cur_total = 0.0; + + /* since we use wrappers for this function, the update machinery + * can't eliminate double invocations of this function. Check for + * them here, otherwise cpu_usage counters are freaking out. */ + pthread_mutex_lock(&last_stat_update_mutex); + if (last_stat_update == current_update_time) { + pthread_mutex_unlock(&last_stat_update_mutex); + return 0; + } + last_stat_update = current_update_time; + pthread_mutex_unlock(&last_stat_update_mutex); + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if (!cpu_setup || !info.cpu_usage) { + get_cpu_count(); + cpu_setup = 1; + } + + if (!stat_template) { + stat_template = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + } + + if (!global_cpu) { + malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); + cpu = (struct cpu_info *)malloc(malloc_cpu_size); + memset(cpu, 0, malloc_cpu_size); + global_cpu = cpu; + } + + if (!(stat_fp = open_file("/proc/stat", &rep))) { + info.run_threads = 0; + if (info.cpu_usage) { + memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); + } + return 0; + } + + idx = 0; + while (!feof(stat_fp)) { + if (fgets(buf, 255, stat_fp) == nullptr) { break; } + + if (strncmp(buf, "procs_running ", 14) == 0) { + sscanf(buf, "%*s %hu", &info.run_threads); + } else if (strncmp(buf, "cpu", 3) == 0) { + double delta; + if (isdigit((unsigned char)buf[3])) { + idx++; // just increment here since the CPU index can skip numbers + } else { + idx = 0; + } + if (idx > info.cpu_count) { continue; } + sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), + &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), + &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), + &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); + + cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + + cpu[idx].cpu_system + cpu[idx].cpu_idle + + cpu[idx].cpu_iowait + cpu[idx].cpu_irq + + cpu[idx].cpu_softirq + cpu[idx].cpu_steal; + + cpu[idx].cpu_active_total = + cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); + + delta = current_update_time - last_update_time; + + if (delta <= 0.001) { break; } + + cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); + if (cur_total == 0.0) { + cpu[idx].cpu_val[0] = 1.0; + } else { + cpu[idx].cpu_val[0] = + (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / + cur_total; + } + curtmp = 0; + + int samples = cpu_avg_samples.get(*state); +#ifdef HAVE_OPENMP +#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } + info.cpu_usage[idx] = curtmp / samples; - /* read integer */ - { - char buf[64]; - int n; - n = read(*fd, buf, 63); - /* should read until n == 0 but I doubt that kernel will give these - * in multiple pieces. :) */ - if (n < 0) { - NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); - } else { - buf[n] = '\0'; - val = atoi(buf); - } - } + cpu[idx].cpu_last_total = cpu[idx].cpu_total; + cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = samples - 1; i > 0; i--) { + cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; + } + } + } + fclose(stat_fp); + return 0; + } + + int update_running_processes(void) { + update_stat(); + return 0; + } + + int update_cpu_usage(void) { + update_stat(); + return 0; + } + + void free_cpu(struct text_object *) { /* not used */ } + + // fscanf() that reads floats with points even if you are using a locale where + // floats are with commas + int fscanf_no_i18n(FILE *stream, const char *format, ...) { + int returncode; + va_list ap; - close(*fd); - /* open file */ - *fd = open(devtype, O_RDONLY); - if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } - - /* My dirty hack for computing CPU value - * Filedil, from forums.gentoo.org */ - /* if (strstr(devtype, "temp1_input") != nullptr) { - return -15.096 + 1.4893 * (val / 1000.0); - } */ - - /* divide voltage and temperature by 1000 */ - /* or if any other divisor is given, use that */ - if (0 == (strcmp(type, "temp2"))) { - temp2 = "temp2"; - } else { - temp2 = "empty"; - } - if (strcmp(type, "tempf") == 0) { - if (divisor > 1) { - return ((val / divisor + 40) * 9.0 / 5) - 40; - } else if (divisor) { - return ((val / 1000.0 + 40) * 9.0 / 5) - 40; - } else { - return ((val + 40) * 9.0 / 5) - 40; - } - } else { - if (divisor > 1) { - return val / divisor; - } else if (divisor) { - return val / 1000.0; - } else { - return val; - } - } -} +#ifdef BUILD_I18N + const char *oldlocale = setlocale(LC_NUMERIC, nullptr); + + setlocale(LC_NUMERIC, "C"); +#endif + va_start(ap, format); + returncode = vfscanf(stream, format, ap); + va_end(ap); +#ifdef BUILD_I18N + setlocale(LC_NUMERIC, oldlocale); +#endif + return returncode; + } + + int update_load_average(void) { +#ifdef HAVE_GETLOADAVG + if (!prefer_proc) { + double v[3]; + + getloadavg(v, 3); + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; + } else +#endif + { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file("/proc/loadavg", &rep))) { + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + return 0; + } + if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], + &info.loadavg[2]) < 0) + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + fclose(fp); + } + return 0; + } + + /***********************************************************/ + /***********************************************************/ + /***********************************************************/ + + static int no_dots(const struct dirent *d) { + if (d->d_name[0] == '.') { return 0; } + return 1; + } + + static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { + struct dirent **namelist; + int i, n; + + n = scandir(dir, &namelist, no_dots, alphasort); + if (n < 0) { + if (!rep || !*rep) { + NORM_ERR("scandir for %s: %s", dir, strerror(errno)); + if (rep) { *rep = 1; } + } + return 0; + } else { + if (n == 0) { return 0; } + + strncpy(s, namelist[0]->d_name, 255); + s[255] = '\0'; + +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < n; i++) { free(namelist[i]); } + free(namelist); + + return 1; + } + } + + static int open_sysfs_sensor(const char *dir, const char *dev, + const char *type, int n, int *divisor, + char *devtype) { + char path[256]; + char buf[256]; + int fd; + int divfd; + + memset(buf, 0, sizeof(buf)); + + /* if device is nullptr or *, get first */ + if (dev == nullptr || strcmp(dev, "*") == 0) { + static int rep = 0; + + if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } + dev = buf; + } + + if (strcmp(dir, "/sys/class/hwmon/") == 0) { + if (*buf) { + /* buf holds result from get_first_file_in_a_directory() above, + * e.g. "hwmon0" -- append "/device" */ + strncat(buf, "/device", 256); + } else { + /* dev holds device number N as a string, + * e.g. "0", -- convert to "hwmon0/device" */ + sprintf(buf, "hwmon%s/device", dev); + dev = buf; + } + } + + /* change vol to in, tempf to temp */ + if (strcmp(type, "vol") == 0) { + type = "in"; + } else if (strcmp(type, "tempf") == 0) { + type = "temp"; + } else if (strcmp(type, "temp2") == 0) { + type = "temp"; + } + + /* construct path */ + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + + /* first, attempt to open file in /device */ + fd = open(path, O_RDONLY); + if (fd < 0) { + /* if it fails, strip the /device from dev and attempt again */ + buf[strlen(buf) - 7] = 0; + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + fd = open(path, O_RDONLY); + if (fd < 0) { + NORM_ERR( + "can't open '%s': %s\nplease check your device or remove this " + "var from " PACKAGE_NAME, + path, strerror(errno)); + } + } + + strncpy(devtype, path, 255); + + if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || + strcmp(type, "tempf") == 0) { + *divisor = 1; + } else { + *divisor = 0; + } + /* fan does not use *_div as a read divisor */ + if (strcmp("fan", type) == 0) { return fd; } + + /* test if *_div file exist, open it and use it as divisor */ + if (strcmp(type, "tempf") == 0) { + snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + } else { + snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + } + + divfd = open(path, O_RDONLY); + if (divfd > 0) { + /* read integer */ + char divbuf[64]; + int divn; + + divn = read(divfd, divbuf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (divn < 0) { + NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); + } else { + divbuf[divn] = '\0'; + *divisor = atoi(divbuf); + } + close(divfd); + } + + return fd; + } + + static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { + int val = 0; + + if (*fd <= 0) { return 0; } + + lseek(*fd, 0, SEEK_SET); + + /* read integer */ + { + char buf[64]; + int n; + n = read(*fd, buf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (n < 0) { + NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); + } else { + buf[n] = '\0'; + val = atoi(buf); + } + } + + close(*fd); + /* open file */ + *fd = open(devtype, O_RDONLY); + if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } + + /* My dirty hack for computing CPU value + * Filedil, from forums.gentoo.org */ + /* if (strstr(devtype, "temp1_input") != nullptr) { + return -15.096 + 1.4893 * (val / 1000.0); + } */ + + /* divide voltage and temperature by 1000 */ + /* or if any other divisor is given, use that */ + if (0 == (strcmp(type, "temp2"))) { + temp2 = "temp2"; + } else { + temp2 = "empty"; + } + if (strcmp(type, "tempf") == 0) { + if (divisor > 1) { + return ((val / divisor + 40) * 9.0 / 5) - 40; + } else if (divisor) { + return ((val / 1000.0 + 40) * 9.0 / 5) - 40; + } else { + return ((val + 40) * 9.0 / 5) - 40; + } + } else { + if (divisor > 1) { + return val / divisor; + } else if (divisor) { + return val / 1000.0; + } else { + return val; + } + } + } #define HWMON_RESET() \ { \ @@ -1184,1660 +1282,1666 @@ static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { offset = 0.0; \ } -static void parse_sysfs_sensor(struct text_object *obj, const char *arg, - const char *path, const char *type) { - char buf1[64], buf2[64]; - float factor, offset; - int n, found = 0; - struct sysfs *sf; - - if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) - found = 1; - else - HWMON_RESET(); - if (!found && - sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) - found = 1; - else if (!found) - HWMON_RESET(); - if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) - found = 1; - else if (!found) - HWMON_RESET(); - if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) - found = 1; - else if (!found) - HWMON_RESET(); - - if (!found) { - obj_be_plain_text(obj, "fail"); - return; - } - DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, - offset); - sf = (struct sysfs *)malloc(sizeof(struct sysfs)); - memset(sf, 0, sizeof(struct sysfs)); - sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, - sf->devtype); - strncpy(sf->type, buf2, 63); - sf->factor = factor; - sf->offset = offset; - obj->data.opaque = sf; -} + static void parse_sysfs_sensor(struct text_object *obj, const char *arg, + const char *path, const char *type) { + char buf1[64], buf2[64]; + float factor, offset; + int n, found = 0; + struct sysfs *sf; + + if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) + found = 1; + else + HWMON_RESET(); + if (!found && + sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) + found = 1; + else if (!found) + HWMON_RESET(); + + if (!found) { + obj_be_plain_text(obj, "fail"); + return; + } + DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, + offset); + sf = (struct sysfs *)malloc(sizeof(struct sysfs)); + memset(sf, 0, sizeof(struct sysfs)); + sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, + sf->devtype); + strncpy(sf->type, buf2, 63); + sf->factor = factor; + sf->offset = offset; + obj->data.opaque = sf; + } #define PARSER_GENERATOR(name, path) \ void parse_##name##_sensor(struct text_object *obj, const char *arg) { \ parse_sysfs_sensor(obj, arg, path, #name); \ } -PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") -PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") -PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") + PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") + PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") + PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") -void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { - double r; - struct sysfs *sf = (struct sysfs *)obj->data.opaque; + void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { + double r; + struct sysfs *sf = (struct sysfs *)obj->data.opaque; - if (!sf || sf->fd < 0) return; + if (!sf || sf->fd < 0) return; - r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); + r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); - r = r * sf->factor + sf->offset; + r = r * sf->factor + sf->offset; - if (0 == (strcmp(temp2, "temp2"))) { - temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); - } else if (!strncmp(sf->type, "temp", 4)) { - temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); - } else if (r >= 100.0 || r == 0) { - snprintf(p, p_max_size, "%d", (int)r); - } else { - snprintf(p, p_max_size, "%.1f", r); - } -} + if (0 == (strcmp(temp2, "temp2"))) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); + } else if (!strncmp(sf->type, "temp", 4)) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); + } else if (r >= 100.0 || r == 0) { + snprintf(p, p_max_size, "%d", (int)r); + } else { + snprintf(p, p_max_size, "%.1f", r); + } + } -void free_sysfs_sensor(struct text_object *obj) { - struct sysfs *sf = (struct sysfs *)obj->data.opaque; + void free_sysfs_sensor(struct text_object *obj) { + struct sysfs *sf = (struct sysfs *)obj->data.opaque; - if (!sf) return; + if (!sf) return; - if (sf->fd >= 0) close(sf->fd); - free_and_zero(obj->data.opaque); -} + if (sf->fd >= 0) close(sf->fd); + free_and_zero(obj->data.opaque); + } #define CPUFREQ_PREFIX "/sys/devices/system/cpu" #define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq" -/* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ -char get_freq(char *p_client_buffer, size_t client_buffer_size, - const char *p_format, int divisor, unsigned int cpu) { - FILE *f; - static int rep = 0; - char frequency[32]; - char s[256]; - double freq = 0; - - if (!p_client_buffer || client_buffer_size <= 0 || !p_format || - divisor <= 0) { - return 0; - } - - if (!prefer_proc) { - char current_freq_file[128]; - - snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, - CPUFREQ_POSTFIX); - f = fopen(current_freq_file, "r"); - if (f) { - /* if there's a cpufreq /sys node, read the current frequency from - * this node and divide by 1000 to get Mhz. */ - if (fgets(s, sizeof(s), f)) { - s[strlen(s) - 1] = '\0'; - freq = strtod(s, nullptr); - } - fclose(f); - snprintf(p_client_buffer, client_buffer_size, p_format, - (freq / 1000) / divisor); - return 1; - } - } - - // open the CPU information file - f = open_file("/proc/cpuinfo", &rep); - if (!f) { - perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); - return 0; - } - - // read the file - while (fgets(s, sizeof(s), f) != nullptr) { + /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ + char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + static int rep = 0; + char frequency[32]; + char s[256]; + double freq = 0; + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + if (!prefer_proc) { + char current_freq_file[128]; + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, + CPUFREQ_POSTFIX); + f = fopen(current_freq_file, "r"); + if (f) { + /* if there's a cpufreq /sys node, read the current frequency from + * this node and divide by 1000 to get Mhz. */ + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (freq / 1000) / divisor); + return 1; + } + } + + // open the CPU information file + f = open_file("/proc/cpuinfo", &rep); + if (!f) { + perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); + return 0; + } + + // read the file + while (fgets(s, sizeof(s), f) != nullptr) { #if defined(__i386) || defined(__x86_64) - // and search for the cpu mhz - if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { + // and search for the cpu mhz + if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { #else #if defined(__alpha) - // different on alpha - if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { + // different on alpha + if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { #else - // this is different on ppc for some reason - if (strncmp(s, "clock", 5) == 0 && cpu == 0) { + // this is different on ppc for some reason + if (strncmp(s, "clock", 5) == 0 && cpu == 0) { #endif // defined(__alpha) #endif // defined(__i386) || defined(__x86_64) - // copy just the number - strncpy(frequency, strchr(s, ':') + 2, 32); + // copy just the number + strncpy(frequency, strchr(s, ':') + 2, 32); #if defined(__alpha) - // strip " est.\n" - frequency[strlen(frequency) - 6] = '\0'; - // kernel reports in Hz - freq = strtod(frequency, nullptr) / 1000000; + // strip " est.\n" + frequency[strlen(frequency) - 6] = '\0'; + // kernel reports in Hz + freq = strtod(frequency, nullptr) / 1000000; #else - // strip \n - frequency[strlen(frequency) - 1] = '\0'; - freq = strtod(frequency, nullptr); + // strip \n + frequency[strlen(frequency) - 1] = '\0'; + freq = strtod(frequency, nullptr); #endif - break; - } - if (strncmp(s, "processor", 9) == 0) { - cpu--; - continue; - } - } - - fclose(f); - snprintf(p_client_buffer, client_buffer_size, p_format, - (float)freq / divisor); - return 1; -} + break; + } + if (strncmp(s, "processor", 9) == 0) { + cpu--; + continue; + } + } + + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + return 1; + } #define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages" -/* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something - * like this: -# frequency voltage -1800000 1340 -1600000 1292 -1400000 1100 -1200000 988 -1000000 1116 -800000 1004 -600000 988 - * Peter Tarjan (ptarjan@citromail.hu) */ - -/* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ -static char get_voltage(char *p_client_buffer, size_t client_buffer_size, - const char *p_format, int divisor, unsigned int cpu) { - FILE *f; - char s[256]; - int freq = 0; - int voltage = 0; - char current_freq_file[128]; - int freq_comp = 0; - - /* build the voltage file name */ - cpu--; - snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, - CPUFREQ_POSTFIX); - - if (!p_client_buffer || client_buffer_size <= 0 || !p_format || - divisor <= 0) { - return 0; - } - - /* read the current cpu frequency from the /sys node */ - f = fopen(current_freq_file, "r"); - if (f) { - if (fgets(s, sizeof(s), f)) { - s[strlen(s) - 1] = '\0'; - freq = strtod(s, nullptr); - } - fclose(f); - } else { - fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", - current_freq_file); - perror("get_voltage()"); - return 0; - } - - snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, - CPUFREQ_VOLTAGE); - - /* use the current cpu frequency to find the corresponding voltage */ - f = fopen(current_freq_file, "r"); - - if (f) { - while (!feof(f)) { - char line[256]; - - if (fgets(line, 255, f) == nullptr) { break; } - sscanf(line, "%d %d", &freq_comp, &voltage); - if (freq_comp == freq) { break; } - } - fclose(f); - } else { - fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", - current_freq_file); - perror("get_voltage()"); - return 0; - } - snprintf(p_client_buffer, client_buffer_size, p_format, - (float)voltage / divisor); - return 1; -} - -void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { - static int ok = 1; - if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } -} - -void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { - static int ok = 1; - if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } -} + /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something + * like this: + # frequency voltage + 1800000 1340 + 1600000 1292 + 1400000 1100 + 1200000 988 + 1000000 1116 + 800000 1004 + 600000 988 + * Peter Tarjan (ptarjan@citromail.hu) */ + + /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ + static char get_voltage(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + char s[256]; + int freq = 0; + int voltage = 0; + char current_freq_file[128]; + int freq_comp = 0; + + /* build the voltage file name */ + cpu--; + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_POSTFIX); + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + /* read the current cpu frequency from the /sys node */ + f = fopen(current_freq_file, "r"); + if (f) { + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_VOLTAGE); + + /* use the current cpu frequency to find the corresponding voltage */ + f = fopen(current_freq_file, "r"); + + if (f) { + while (!feof(f)) { + char line[256]; + + if (fgets(line, 255, f) == nullptr) { break; } + sscanf(line, "%d %d", &freq_comp, &voltage); + if (freq_comp == freq) { break; } + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)voltage / divisor); + return 1; + } + + void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } + } + + void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } + } #define ACPI_FAN_DIR "/proc/acpi/fan/" -void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { - static int rep = 0; - char buf[256]; - char buf2[256]; - FILE *fp; + void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { + static int rep = 0; + char buf[256]; + char buf2[256]; + FILE *fp; - if (!p_client_buffer || client_buffer_size <= 0) { return; } + if (!p_client_buffer || client_buffer_size <= 0) { return; } - /* yeah, slow... :/ */ - if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { - snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); - return; - } + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); + return; + } - snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); - fp = open_file(buf2, &rep); - if (!fp) { - snprintf(p_client_buffer, client_buffer_size, "%s", - "can't open fan's state file"); - return; - } - memset(buf, 0, sizeof(buf)); - if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); - fclose(fp); + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "can't open fan's state file"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); - snprintf(p_client_buffer, client_buffer_size, "%s", buf); -} + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } #define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply" #define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/" -/* Linux 2.6.25 onwards ac adapter info is in - /sys/class/power_supply/AC/ - On my system I get the following. - /sys/class/power_supply/AC/uevent: - PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 - PHYSDEVBUS=acpi - PHYSDEVDRIVER=ac - POWER_SUPPLY_NAME=AC - POWER_SUPPLY_TYPE=Mains - POWER_SUPPLY_ONLINE=1 - - Update: it seems the folder name is hardware-dependent. We add an aditional - adapter argument, specifying the folder name. - - Update: on some systems it's /sys/class/power_supply/ADP1 instead of - /sys/class/power_supply/AC -*/ - -void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, - const char *adapter) { - static int rep = 0; - - char buf[256]; - char buf2[256]; - struct stat sb; - FILE *fp; - - if (!p_client_buffer || client_buffer_size <= 0) { return; } - - if (adapter) - snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, adapter); - else { - snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); - if (stat(buf2, &sb) == -1) - snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); - } - if (stat(buf2, &sb) == 0) - fp = open_file(buf2, &rep); - else - fp = 0; - if (fp) { - /* sysfs processing */ - while (!feof(fp)) { - if (fgets(buf, sizeof(buf), fp) == nullptr) break; - - if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { - int online = 0; - sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); - snprintf(p_client_buffer, client_buffer_size, "%s-line", - (online ? "on" : "off")); - break; - } - } - fclose(fp); - } else { - /* yeah, slow... :/ */ - if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { - snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); - return; - } - - snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); - - fp = open_file(buf2, &rep); - if (!fp) { - snprintf(p_client_buffer, client_buffer_size, "%s", - "No ac adapter found.... where is it?"); - return; - } - memset(buf, 0, sizeof(buf)); - if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); - fclose(fp); - - snprintf(p_client_buffer, client_buffer_size, "%s", buf); - } -} + /* Linux 2.6.25 onwards ac adapter info is in + /sys/class/power_supply/AC/ + On my system I get the following. + /sys/class/power_supply/AC/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=ac + POWER_SUPPLY_NAME=AC + POWER_SUPPLY_TYPE=Mains + POWER_SUPPLY_ONLINE=1 + + Update: it seems the folder name is hardware-dependent. We add an aditional + adapter argument, specifying the folder name. + + Update: on some systems it's /sys/class/power_supply/ADP1 instead of + /sys/class/power_supply/AC + */ -/* -/proc/acpi/thermal_zone/THRM/cooling_mode -cooling mode: active -/proc/acpi/thermal_zone/THRM/polling_frequency - -/proc/acpi/thermal_zone/THRM/state -state: ok -/proc/acpi/thermal_zone/THRM/temperature -temperature: 45 C -/proc/acpi/thermal_zone/THRM/trip_points -critical (S5): 73 C -passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 -*/ + void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, + const char *adapter) { + static int rep = 0; + + char buf[256]; + char buf2[256]; + struct stat sb; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + if (adapter) + snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, + adapter); + else { + snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); + if (stat(buf2, &sb) == -1) + snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); + } + if (stat(buf2, &sb) == 0) + fp = open_file(buf2, &rep); + else + fp = 0; + if (fp) { + /* sysfs processing */ + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { + int online = 0; + sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); + snprintf(p_client_buffer, client_buffer_size, "%s-line", + (online ? "on" : "off")); + break; + } + } + fclose(fp); + } else { + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "No ac adapter found.... where is it?"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + } + + /* + /proc/acpi/thermal_zone/THRM/cooling_mode + cooling mode: active + /proc/acpi/thermal_zone/THRM/polling_frequency + + /proc/acpi/thermal_zone/THRM/state + state: ok + /proc/acpi/thermal_zone/THRM/temperature + temperature: 45 C + /proc/acpi/thermal_zone/THRM/trip_points + critical (S5): 73 C + passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 + */ #define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0" #define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp" -int open_acpi_temperature(const char *name) { - char path[256]; - int fd; + int open_acpi_temperature(const char *name) { + char path[256]; + int fd; - if (name == nullptr || strcmp(name, "*") == 0) { - snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); - } else { - snprintf(path, 255, ACPI_THERMAL_FORMAT, name); - } + if (name == nullptr || strcmp(name, "*") == 0) { + snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); + } else { + snprintf(path, 255, ACPI_THERMAL_FORMAT, name); + } - fd = open(path, O_RDONLY); - if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } + fd = open(path, O_RDONLY); + if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } - return fd; -} + return fd; + } -static double last_acpi_temp; -static double last_acpi_temp_time; + static double last_acpi_temp; + static double last_acpi_temp_time; -// the maximum length of the string inside a ACPI_THERMAL_FORMAT file including -// the ending 0 + // the maximum length of the string inside a ACPI_THERMAL_FORMAT file including + // the ending 0 #define MAXTHERMZONELEN 6 -double get_acpi_temperature(int fd) { - if (fd <= 0) { return 0; } - - /* don't update acpi temperature too often */ - if (current_update_time - last_acpi_temp_time < 11.32) { - return last_acpi_temp; - } - last_acpi_temp_time = current_update_time; - - /* seek to beginning */ - lseek(fd, 0, SEEK_SET); + double get_acpi_temperature(int fd) { + if (fd <= 0) { return 0; } + + /* don't update acpi temperature too often */ + if (current_update_time - last_acpi_temp_time < 11.32) { + return last_acpi_temp; + } + last_acpi_temp_time = current_update_time; + + /* seek to beginning */ + lseek(fd, 0, SEEK_SET); + + /* read */ + { + char buf[MAXTHERMZONELEN]; + int n; + + n = read(fd, buf, MAXTHERMZONELEN - 1); + if (n < 0) { + NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); + } else { + buf[n] = '\0'; + sscanf(buf, "%lf", &last_acpi_temp); + last_acpi_temp /= 1000; + } + } + + return last_acpi_temp; + } + + /* + hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info + present: yes + design capacity: 4400 mAh + last full capacity: 4064 mAh + battery technology: rechargeable + design voltage: 14800 mV + design capacity warning: 300 mAh + design capacity low: 200 mAh + capacity granularity 1: 32 mAh + capacity granularity 2: 32 mAh + model number: 02KT + serial number: 16922 + battery type: LION + OEM info: SANYO + */ - /* read */ - { - char buf[MAXTHERMZONELEN]; - int n; + /* + hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state + present: yes + capacity state: ok + charging state: unknown + present rate: 0 mA + remaining capacity: 4064 mAh + present voltage: 16608 mV + */ - n = read(fd, buf, MAXTHERMZONELEN - 1); - if (n < 0) { - NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); - } else { - buf[n] = '\0'; - sscanf(buf, "%lf", &last_acpi_temp); - last_acpi_temp /= 1000; - } - } + /* + 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? + 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) + 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? - return last_acpi_temp; -} + 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman + verkkovirtaa 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? + verkkovirralla -/* -hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info -present: yes -design capacity: 4400 mAh -last full capacity: 4064 mAh -battery technology: rechargeable -design voltage: 14800 mV -design capacity warning: 300 mAh -design capacity low: 200 mAh -capacity granularity 1: 32 mAh -capacity granularity 2: 32 mAh -model number: 02KT -serial number: 16922 -battery type: LION -OEM info: SANYO -*/ + 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja + monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? + monitori p��ll� mutta ilman verkkovirtaa + */ -/* -hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state -present: yes -capacity state: ok -charging state: unknown -present rate: 0 mA -remaining capacity: 4064 mAh -present voltage: 16608 mV -*/ + /* Kapil Hari Paranjape + Linux 2.6.24 onwards battery info is in + /sys/class/power_supply/BAT0/ + On my system I get the following. + /sys/class/power_supply/BAT0/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=battery + POWER_SUPPLY_NAME=BAT0 + POWER_SUPPLY_TYPE=Battery + POWER_SUPPLY_STATUS=Discharging + POWER_SUPPLY_PRESENT=1 + POWER_SUPPLY_TECHNOLOGY=Li-ion + POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 + POWER_SUPPLY_VOLTAGE_NOW=10780000 + POWER_SUPPLY_CURRENT_NOW=13970000 + POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 + POWER_SUPPLY_ENERGY_FULL=27370000 + POWER_SUPPLY_ENERGY_NOW=11810000 + POWER_SUPPLY_MODEL_NAME=IBM-92P1060 + POWER_SUPPLY_MANUFACTURER=Panasonic + On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* + */ -/* -2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm -2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? -2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) -2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm -2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? - -2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman verkkovirtaa -2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? verkkovirralla - -2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja -monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? -monitori p��ll� mutta ilman verkkovirtaa -*/ - -/* Kapil Hari Paranjape - Linux 2.6.24 onwards battery info is in - /sys/class/power_supply/BAT0/ - On my system I get the following. - /sys/class/power_supply/BAT0/uevent: - PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 - PHYSDEVBUS=acpi - PHYSDEVDRIVER=battery - POWER_SUPPLY_NAME=BAT0 - POWER_SUPPLY_TYPE=Battery - POWER_SUPPLY_STATUS=Discharging - POWER_SUPPLY_PRESENT=1 - POWER_SUPPLY_TECHNOLOGY=Li-ion - POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 - POWER_SUPPLY_VOLTAGE_NOW=10780000 - POWER_SUPPLY_CURRENT_NOW=13970000 - POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 - POWER_SUPPLY_ENERGY_FULL=27370000 - POWER_SUPPLY_ENERGY_NOW=11810000 - POWER_SUPPLY_MODEL_NAME=IBM-92P1060 - POWER_SUPPLY_MANUFACTURER=Panasonic - On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* -*/ - -/* Tiago Marques Vale - Regarding the comment above, since kernel 2.6.36.1 I have - POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW - See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 -*/ + /* Tiago Marques Vale + Regarding the comment above, since kernel 2.6.36.1 I have + POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW + See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 + */ #define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply" #define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" #define APM_PATH "/proc/apm" #define MAX_BATTERY_COUNT 4 -static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; -static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; -static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; -static int batteries_initialized = 0; -static char batteries[MAX_BATTERY_COUNT][32]; + static int batteries_initialized = 0; + static char batteries[MAX_BATTERY_COUNT][32]; -static int acpi_last_full[MAX_BATTERY_COUNT]; -static int acpi_design_capacity[MAX_BATTERY_COUNT]; + static int acpi_last_full[MAX_BATTERY_COUNT]; + static int acpi_design_capacity[MAX_BATTERY_COUNT]; -/* e.g. "charging 75%" */ -static char last_battery_str[MAX_BATTERY_COUNT][64]; -/* e.g. "3h 15m" */ -static char last_battery_time_str[MAX_BATTERY_COUNT][64]; + /* e.g. "charging 75%" */ + static char last_battery_str[MAX_BATTERY_COUNT][64]; + /* e.g. "3h 15m" */ + static char last_battery_time_str[MAX_BATTERY_COUNT][64]; -static double last_battery_time[MAX_BATTERY_COUNT]; + static double last_battery_time[MAX_BATTERY_COUNT]; -static int last_battery_perct[MAX_BATTERY_COUNT]; -static double last_battery_perct_time[MAX_BATTERY_COUNT]; + static int last_battery_perct[MAX_BATTERY_COUNT]; + static double last_battery_perct_time[MAX_BATTERY_COUNT]; -void init_batteries(void) { - int idx; + void init_batteries(void) { + int idx; - if (batteries_initialized) { return; } + if (batteries_initialized) { return; } #ifdef HAVE_OPENMP #pragma omp parallel for schedule(dynamic, 10) #endif /* HAVE_OPENMP */ - for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } - batteries_initialized = 1; -} - -int get_battery_idx(const char *bat) { - int idx; - - for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { - if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } - } - - /* if not found, enter a new entry */ - if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } - - return idx; -} - -void set_return_value(char *buffer, unsigned int n, int item, int idx); - -void get_battery_stuff(char *buffer, unsigned int n, const char *bat, - int item) { - static int idx, rep = 0, rep1 = 0, rep2 = 0; - char acpi_path[128]; - char sysfs_path[128]; - - snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); - snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); - - init_batteries(); - - idx = get_battery_idx(bat); - - /* don't update battery too often */ - if (current_update_time - last_battery_time[idx] < 29.5) { - set_return_value(buffer, n, item, idx); - return; - } - - last_battery_time[idx] = current_update_time; - - memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); - memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); - - /* first try SYSFS if that fails try ACPI */ - - if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && - apm_bat_fp[idx] == nullptr) { - sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); - } - - if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && - apm_bat_fp[idx] == nullptr) { - acpi_bat_fp[idx] = open_file(acpi_path, &rep1); - } - - if (sysfs_bat_fp[idx] != nullptr) { - /* SYSFS */ - int present_rate = -1; - int remaining_capacity = -1; - char charging_state[64]; - char present[4]; - - strncpy(charging_state, "unknown", 64); - - while (!feof(sysfs_bat_fp[idx])) { - char buf[256]; - if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; - - /* let's just hope units are ok */ - if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) - strncpy(present, "yes", 4); - else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) - strncpy(present, "no", 4); - else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) - sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); - /* present_rate is not the same as the current flowing now but it - * is the same value which was used in the past. so we continue the - * tradition! */ - else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) - sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); - else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) - sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); - else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) - sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); - else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) - sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); - else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) - sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); - else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) - sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); - } - - fclose(sysfs_bat_fp[idx]); - sysfs_bat_fp[idx] = nullptr; - - /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ - if (remaining_capacity > acpi_last_full[idx]) - acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ - - /* not present */ - if (strcmp(present, "No") == 0) { - strncpy(last_battery_str[idx], "not present", 64); - } - /* charging */ - else if (strcmp(charging_state, "Charging") == 0) { - if (acpi_last_full[idx] != 0 && present_rate > 0) { - /* e.g. charging 75% */ - snprintf( - last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "charging %i%%", - (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); - /* e.g. 2h 37m */ - format_seconds( - last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, - (long)(((float)(acpi_last_full[idx] - remaining_capacity) / - present_rate) * - 3600)); - } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { - snprintf( - last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "charging %d%%", - (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } else { - strncpy(last_battery_str[idx], "charging", - sizeof(last_battery_str[idx]) - 1); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } - } - /* discharging */ - else if (strncmp(charging_state, "Discharging", 64) == 0) { - if (present_rate > 0) { - /* e.g. discharging 35% */ - snprintf( - last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "discharging %i%%", - (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); - /* e.g. 1h 12m */ - format_seconds( - last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, - (long)(((float)remaining_capacity / present_rate) * 3600)); - } else if (present_rate == 0) { /* Thanks to Nexox for this one */ - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "full"); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } else { - snprintf( - last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "discharging %d%%", - (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } - } - /* charged */ - /* thanks to Lukas Zapletal */ - else if (strncmp(charging_state, "Charged", 64) == 0 || - strncmp(charging_state, "Full", 64) == 0) { - /* Below happens with the second battery on my X40, - * when the second one is empty and the first one - * being charged. */ - if (remaining_capacity == 0) - strncpy(last_battery_str[idx], "empty", 64); - else - strncpy(last_battery_str[idx], "charged", 64); - } - /* unknown, probably full / AC */ - else { - if (acpi_last_full[idx] != 0 && remaining_capacity != acpi_last_full[idx]) - snprintf( - last_battery_str[idx], 64, "unknown %d%%", - (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); - else - strncpy(last_battery_str[idx], "not present", 64); - } - } else if (acpi_bat_fp[idx] != nullptr) { - /* ACPI */ - int present_rate = -1; - int remaining_capacity = -1; - char charging_state[64]; - char present[5]; - - /* read last full capacity if it's zero */ - if (acpi_last_full[idx] == 0) { - static int rep3 = 0; - char path[128]; - FILE *fp; - - snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); - fp = open_file(path, &rep3); - if (fp != nullptr) { - while (!feof(fp)) { - char b[256]; - - if (fgets(b, 256, fp) == nullptr) { break; } - if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { - break; - } - } - - fclose(fp); - } - } - - fseek(acpi_bat_fp[idx], 0, SEEK_SET); - - strncpy(charging_state, "unknown", 8); - - while (!feof(acpi_bat_fp[idx])) { - char buf[256]; - - if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } - - /* let's just hope units are ok */ - if (strncmp(buf, "present:", 8) == 0) { - sscanf(buf, "present: %4s", present); - } else if (strncmp(buf, "charging state:", 15) == 0) { - sscanf(buf, "charging state: %63s", charging_state); - } else if (strncmp(buf, "present rate:", 13) == 0) { - sscanf(buf, "present rate: %d", &present_rate); - } else if (strncmp(buf, "remaining capacity:", 19) == 0) { - sscanf(buf, "remaining capacity: %d", &remaining_capacity); - } - } - /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ - if (remaining_capacity > acpi_last_full[idx]) { - /* normalize to 100% */ - acpi_last_full[idx] = remaining_capacity; - } - - /* not present */ - if (strcmp(present, "no") == 0) { - strncpy(last_battery_str[idx], "not present", 64); - /* charging */ - } else if (strcmp(charging_state, "charging") == 0) { - if (acpi_last_full[idx] != 0 && present_rate > 0) { - /* e.g. charging 75% */ - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "charging %i%%", - (int)((remaining_capacity * 100) / acpi_last_full[idx])); - /* e.g. 2h 37m */ - format_seconds( - last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, - (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / - present_rate)); - } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "charging %d%%", - (int)((remaining_capacity * 100) / acpi_last_full[idx])); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } else { - strncpy(last_battery_str[idx], "charging", - sizeof(last_battery_str[idx]) - 1); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } - /* discharging */ - } else if (strncmp(charging_state, "discharging", 64) == 0) { - if (present_rate > 0) { - /* e.g. discharging 35% */ - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "discharging %i%%", - (int)((remaining_capacity * 100) / acpi_last_full[idx])); - /* e.g. 1h 12m */ - format_seconds(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, - (long)((remaining_capacity * 3600) / present_rate)); - } else if (present_rate == 0) { /* Thanks to Nexox for this one */ - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "charged"); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } else { - snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, - "discharging %d%%", - (int)((remaining_capacity * 100) / acpi_last_full[idx])); - snprintf(last_battery_time_str[idx], - sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); - } - /* charged */ - } else if (strncmp(charging_state, "charged", 64) == 0) { - /* thanks to Lukas Zapletal */ - /* Below happens with the second battery on my X40, - * when the second one is empty and the first one being charged. */ - if (remaining_capacity == 0) { - strncpy(last_battery_str[idx], "empty", 6); - } else { - strncpy(last_battery_str[idx], "charged", 8); - } - /* unknown, probably full / AC */ - } else { - if (strncmp(charging_state, "Full", 64) == 0) { - strncpy(last_battery_str[idx], "charged", 64); - } else if (acpi_last_full[idx] != 0 && - remaining_capacity != acpi_last_full[idx]) { - snprintf(last_battery_str[idx], 64, "unknown %d%%", - (int)((remaining_capacity * 100) / acpi_last_full[idx])); - } else { - strncpy(last_battery_str[idx], "not present", 64); - } - } - fclose(acpi_bat_fp[idx]); - acpi_bat_fp[idx] = nullptr; - } else { - /* APM */ - if (apm_bat_fp[idx] == nullptr) { - apm_bat_fp[idx] = open_file(APM_PATH, &rep2); - } - - if (apm_bat_fp[idx] != nullptr) { - unsigned int ac, status, flag; - int life; - - if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, - &status, &flag, &life) <= 0) - goto read_bat_fp_end; - - if (life == -1) { - /* could check now that there is ac */ - snprintf(last_battery_str[idx], 64, "%s", "not present"); - - /* could check that status == 3 here? */ - } else if (ac && life != 100) { - snprintf(last_battery_str[idx], 64, "charging %d%%", life); - } else { - snprintf(last_battery_str[idx], 64, "%d%%", life); - } - - read_bat_fp_end: - /* it seemed to buffer it so file must be closed (or could use - * syscalls directly but I don't feel like coding it now) */ - fclose(apm_bat_fp[idx]); - apm_bat_fp[idx] = nullptr; - } - } - set_return_value(buffer, n, item, idx); -} - -void set_return_value(char *buffer, unsigned int n, int item, int idx) { - switch (item) { - case BATTERY_STATUS: - snprintf(buffer, n, "%s", last_battery_str[idx]); - break; - case BATTERY_TIME: - snprintf(buffer, n, "%s", last_battery_time_str[idx]); - break; - default: - break; - } -} - -void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { - get_battery_stuff(buffer, n, bat, BATTERY_STATUS); - if (0 == strncmp("charging", buffer, 8)) { - buffer[0] = 'C'; - memmove(buffer + 1, buffer + 8, n - 8); - } else if (0 == strncmp("discharging", buffer, 11)) { - buffer[0] = 'D'; - memmove(buffer + 1, buffer + 11, n - 11); - } else if (0 == strncmp("charged", buffer, 7)) { - buffer[0] = 'F'; - memmove(buffer + 1, buffer + 7, n - 7); - } else if (0 == strncmp("not present", buffer, 11)) { - buffer[0] = 'N'; - memmove(buffer + 1, buffer + 11, n - 11); - } else if (0 == strncmp("empty", buffer, 5)) { - buffer[0] = 'E'; - memmove(buffer + 1, buffer + 5, n - 5); - } else if (0 == strncmp("unknown", buffer, 7)) { - buffer[0] = 'U'; - memmove(buffer + 1, buffer + 7, n - 7); - } - // Otherwise, don't shorten. -} - -int _get_battery_perct(const char *bat) { - static int rep = 0; - int idx; - char acpi_path[128]; - char sysfs_path[128]; - int remaining_capacity = -1; - - snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); - snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); - - idx = get_battery_idx(bat); - - /* don't update battery too often */ - if (current_update_time - last_battery_perct_time[idx] < 30) { - return last_battery_perct[idx]; - } - last_battery_perct_time[idx] = current_update_time; - - /* Only check for SYSFS or ACPI */ - - if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && - apm_bat_fp[idx] == nullptr) { - sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); - rep = 0; - } - - if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && - apm_bat_fp[idx] == nullptr) { - acpi_bat_fp[idx] = open_file(acpi_path, &rep); - } - - if (sysfs_bat_fp[idx] != nullptr) { - /* SYSFS */ - while (!feof(sysfs_bat_fp[idx])) { - char buf[256]; - if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; - - if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { - sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); - } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { - sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); - } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { - sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); - } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { - sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); - } - } - - fclose(sysfs_bat_fp[idx]); - sysfs_bat_fp[idx] = nullptr; - - } else if (acpi_bat_fp[idx] != nullptr) { - /* ACPI */ - /* read last full capacity if it's zero */ - if (acpi_design_capacity[idx] == 0) { - static int rep2; - char path[128]; - FILE *fp; - - snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); - fp = open_file(path, &rep2); - if (fp != nullptr) { - while (!feof(fp)) { - char b[256]; - - if (fgets(b, 256, fp) == nullptr) { break; } - if (sscanf(b, "last full capacity: %d", &acpi_design_capacity[idx]) != - 0) { - break; - } - } - fclose(fp); - } - } - - fseek(acpi_bat_fp[idx], 0, SEEK_SET); - - while (!feof(acpi_bat_fp[idx])) { - char buf[256]; - - if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } - - if (buf[0] == 'r') { - sscanf(buf, "remaining capacity: %d", &remaining_capacity); - } - } - } - if (remaining_capacity < 0) { return 0; } - /* compute the battery percentage */ - last_battery_perct[idx] = - (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); - if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; - return last_battery_perct[idx]; -} - -int get_battery_perct(const char *bat) { - int idx, n = 0, total_capacity = 0, remaining_capacity; - ; + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } + batteries_initialized = 1; + } + + int get_battery_idx(const char *bat) { + int idx; + + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } + } + + /* if not found, enter a new entry */ + if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } + + return idx; + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx); + + void get_battery_stuff(char *buffer, unsigned int n, const char *bat, + int item) { + static int idx, rep = 0, rep1 = 0, rep2 = 0; + char acpi_path[128]; + char sysfs_path[128]; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + init_batteries(); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_time[idx] < 29.5) { + set_return_value(buffer, n, item, idx); + return; + } + + last_battery_time[idx] = current_update_time; + + memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); + memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); + + /* first try SYSFS if that fails try ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep1); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[4]; + + strncpy(charging_state, "unknown", 64); + + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + /* let's just hope units are ok */ + if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) + strncpy(present, "yes", 4); + else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) + strncpy(present, "no", 4); + else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) + sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); + /* present_rate is not the same as the current flowing now but it + * is the same value which was used in the past. so we continue the + * tradition! */ + else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) + sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) + acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ + + /* not present */ + if (strcmp(present, "No") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + } + /* charging */ + else if (strcmp(charging_state, "Charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)(acpi_last_full[idx] - remaining_capacity) / + present_rate) * + 3600)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* discharging */ + else if (strncmp(charging_state, "Discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 1h 12m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)remaining_capacity / present_rate) * 3600)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "full"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* charged */ + /* thanks to Lukas Zapletal */ + else if (strncmp(charging_state, "Charged", 64) == 0 || + strncmp(charging_state, "Full", 64) == 0) { + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one + * being charged. */ + if (remaining_capacity == 0) + strncpy(last_battery_str[idx], "empty", 64); + else + strncpy(last_battery_str[idx], "charged", 64); + } + /* unknown, probably full / AC */ + else { + if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) + snprintf( + last_battery_str[idx], 64, "unknown %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + else + strncpy(last_battery_str[idx], "not present", 64); + } + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[5]; + + /* read last full capacity if it's zero */ + if (acpi_last_full[idx] == 0) { + static int rep3 = 0; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep3); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { + break; + } + } + + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + strncpy(charging_state, "unknown", 8); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + /* let's just hope units are ok */ + if (strncmp(buf, "present:", 8) == 0) { + sscanf(buf, "present: %4s", present); + } else if (strncmp(buf, "charging state:", 15) == 0) { + sscanf(buf, "charging state: %63s", charging_state); + } else if (strncmp(buf, "present rate:", 13) == 0) { + sscanf(buf, "present rate: %d", &present_rate); + } else if (strncmp(buf, "remaining capacity:", 19) == 0) { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) { + /* normalize to 100% */ + acpi_last_full[idx] = remaining_capacity; + } + + /* not present */ + if (strcmp(present, "no") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + /* charging */ + } else if (strcmp(charging_state, "charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / + present_rate)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* discharging */ + } else if (strncmp(charging_state, "discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 1h 12m */ + format_seconds(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, + (long)((remaining_capacity * 3600) / present_rate)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charged"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* charged */ + } else if (strncmp(charging_state, "charged", 64) == 0) { + /* thanks to Lukas Zapletal */ + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one being charged. */ + if (remaining_capacity == 0) { + strncpy(last_battery_str[idx], "empty", 6); + } else { + strncpy(last_battery_str[idx], "charged", 8); + } + /* unknown, probably full / AC */ + } else { + if (strncmp(charging_state, "Full", 64) == 0) { + strncpy(last_battery_str[idx], "charged", 64); + } else if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) { + snprintf(last_battery_str[idx], 64, "unknown %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + } else { + strncpy(last_battery_str[idx], "not present", 64); + } + } + fclose(acpi_bat_fp[idx]); + acpi_bat_fp[idx] = nullptr; + } else { + /* APM */ + if (apm_bat_fp[idx] == nullptr) { + apm_bat_fp[idx] = open_file(APM_PATH, &rep2); + } + + if (apm_bat_fp[idx] != nullptr) { + unsigned int ac, status, flag; + int life; + + if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, + &status, &flag, &life) <= 0) + goto read_bat_fp_end; + + if (life == -1) { + /* could check now that there is ac */ + snprintf(last_battery_str[idx], 64, "%s", "not present"); + + /* could check that status == 3 here? */ + } else if (ac && life != 100) { + snprintf(last_battery_str[idx], 64, "charging %d%%", life); + } else { + snprintf(last_battery_str[idx], 64, "%d%%", life); + } + + read_bat_fp_end: + /* it seemed to buffer it so file must be closed (or could use + * syscalls directly but I don't feel like coding it now) */ + fclose(apm_bat_fp[idx]); + apm_bat_fp[idx] = nullptr; + } + } + set_return_value(buffer, n, item, idx); + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx) { + switch (item) { + case BATTERY_STATUS: + snprintf(buffer, n, "%s", last_battery_str[idx]); + break; + case BATTERY_TIME: + snprintf(buffer, n, "%s", last_battery_time_str[idx]); + break; + default: + break; + } + } + + void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("not present", buffer, 11)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("empty", buffer, 5)) { + buffer[0] = 'E'; + memmove(buffer + 1, buffer + 5, n - 5); + } else if (0 == strncmp("unknown", buffer, 7)) { + buffer[0] = 'U'; + memmove(buffer + 1, buffer + 7, n - 7); + } + // Otherwise, don't shorten. + } + + int _get_battery_perct(const char *bat) { + static int rep = 0; + int idx; + char acpi_path[128]; + char sysfs_path[128]; + int remaining_capacity = -1; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_perct_time[idx] < 30) { + return last_battery_perct[idx]; + } + last_battery_perct_time[idx] = current_update_time; + + /* Only check for SYSFS or ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + rep = 0; + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); + } + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + /* read last full capacity if it's zero */ + if (acpi_design_capacity[idx] == 0) { + static int rep2; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep2); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", + &acpi_design_capacity[idx]) != 0) { + break; + } + } + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + if (buf[0] == 'r') { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + } + if (remaining_capacity < 0) { return 0; } + /* compute the battery percentage */ + last_battery_perct[idx] = + (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); + if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; + return last_battery_perct[idx]; + } + + int get_battery_perct(const char *bat) { + int idx, n = 0, total_capacity = 0, remaining_capacity; + ; #define BATTERY_LEN 8 - char battery[BATTERY_LEN]; + char battery[BATTERY_LEN]; - init_batteries(); + init_batteries(); - /* Check if user asked for the mean percentage of all batteries. */ - if (!strcmp(bat, "all")) { - for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { - snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); + /* Check if user asked for the mean percentage of all batteries. */ + if (!strcmp(bat, "all")) { + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); #undef BATTERY_LEN - remaining_capacity = _get_battery_perct(battery); - if (remaining_capacity > 0) { - total_capacity += remaining_capacity; - n++; - } - } - - if (n == 0) - return 0; - else - return total_capacity / n; - } else { - return _get_battery_perct(bat); - } -} - -double get_battery_perct_bar(struct text_object *obj) { - int idx; - - get_battery_perct(obj->data.s); - idx = get_battery_idx(obj->data.s); - return last_battery_perct[idx]; -} + remaining_capacity = _get_battery_perct(battery); + if (remaining_capacity > 0) { + total_capacity += remaining_capacity; + n++; + } + } + + if (n == 0) + return 0; + else + return total_capacity / n; + } else { + return _get_battery_perct(bat); + } + } + + double get_battery_perct_bar(struct text_object *obj) { + int idx; + + get_battery_perct(obj->data.s); + idx = get_battery_idx(obj->data.s); + return last_battery_perct[idx]; + } + + /* On Apple powerbook and ibook: + $ cat /proc/pmu/battery_0 + flags : 00000013 + charge : 3623 + max_charge : 3720 + current : 388 + voltage : 16787 + time rem. : 900 + $ cat /proc/pmu/info + PMU driver version : 2 + PMU firmware version : 0c + AC Power : 1 + Battery count : 1 + */ -/* On Apple powerbook and ibook: -$ cat /proc/pmu/battery_0 -flags : 00000013 -charge : 3623 -max_charge : 3720 -current : 388 -voltage : 16787 -time rem. : 900 -$ cat /proc/pmu/info -PMU driver version : 2 -PMU firmware version : 0c -AC Power : 1 -Battery count : 1 -*/ - -/* defines as in */ + /* defines as in */ #define PMU_BATT_PRESENT 0x00000001 #define PMU_BATT_CHARGING 0x00000002 -static FILE *pmu_battery_fp; -static FILE *pmu_info_fp; -static char pb_battery_info[3][32]; -static double pb_battery_info_update; + static FILE *pmu_battery_fp; + static FILE *pmu_info_fp; + static char pb_battery_info[3][32]; + static double pb_battery_info_update; #define PMU_PATH "/proc/pmu" -void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { - static int rep = 0; - const char *batt_path = PMU_PATH "/battery_0"; - const char *info_path = PMU_PATH "/info"; - unsigned int flags = 0; - int charge = 0; - int max_charge = 1; - int ac = -1; - long timeval = -1; - - /* don't update battery too often */ - if (current_update_time - pb_battery_info_update < 29.5) { - snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); - return; - } - pb_battery_info_update = current_update_time; - - if (pmu_battery_fp == nullptr) { - pmu_battery_fp = open_file(batt_path, &rep); - if (pmu_battery_fp == nullptr) { return; } - } - - if (pmu_battery_fp != nullptr) { - rewind(pmu_battery_fp); - while (!feof(pmu_battery_fp)) { - char buf[32]; - - if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } - - if (buf[0] == 'f') { - sscanf(buf, "flags : %8x", &flags); - } else if (buf[0] == 'c' && buf[1] == 'h') { - sscanf(buf, "charge : %d", &charge); - } else if (buf[0] == 'm') { - sscanf(buf, "max_charge : %d", &max_charge); - } else if (buf[0] == 't') { - sscanf(buf, "time rem. : %ld", &timeval); - } - } - } - if (pmu_info_fp == nullptr) { - pmu_info_fp = open_file(info_path, &rep); - if (pmu_info_fp == nullptr) { return; } - } - - if (pmu_info_fp != nullptr) { - rewind(pmu_info_fp); - while (!feof(pmu_info_fp)) { - char buf[32]; - - if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } - if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } - } - } - /* update status string */ - if ((ac && !(flags & PMU_BATT_PRESENT))) { - strncpy(pb_battery_info[PB_BATT_STATUS], "AC", - sizeof(pb_battery_info[PB_BATT_STATUS])); - } else if (ac && (flags & PMU_BATT_PRESENT) && !(flags & PMU_BATT_CHARGING)) { - strncpy(pb_battery_info[PB_BATT_STATUS], "charged", - sizeof(pb_battery_info[PB_BATT_STATUS])); - } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { - strncpy(pb_battery_info[PB_BATT_STATUS], "charging", - sizeof(pb_battery_info[PB_BATT_STATUS])); - } else { - strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", - sizeof(pb_battery_info[PB_BATT_STATUS])); - } - - /* update percentage string */ - if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && - !(flags & PMU_BATT_CHARGING)) { - snprintf(pb_battery_info[PB_BATT_PERCENT], - sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); - } else if (timeval == 0) { - snprintf(pb_battery_info[PB_BATT_PERCENT], - sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); - } else { - snprintf(pb_battery_info[PB_BATT_PERCENT], - sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", - (charge * 100) / max_charge); - } - - /* update time string */ - if (timeval == 0) { /* fully charged or battery not present */ - snprintf(pb_battery_info[PB_BATT_TIME], - sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); - } else if (timeval < 60 * 60) { /* don't show secs */ - format_seconds_short(pb_battery_info[PB_BATT_TIME], - sizeof(pb_battery_info[PB_BATT_TIME]), timeval); - } else { - format_seconds(pb_battery_info[PB_BATT_TIME], - sizeof(pb_battery_info[PB_BATT_TIME]), timeval); - } - - snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); -} + void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { + static int rep = 0; + const char *batt_path = PMU_PATH "/battery_0"; + const char *info_path = PMU_PATH "/info"; + unsigned int flags = 0; + int charge = 0; + int max_charge = 1; + int ac = -1; + long timeval = -1; + + /* don't update battery too often */ + if (current_update_time - pb_battery_info_update < 29.5) { + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + return; + } + pb_battery_info_update = current_update_time; + + if (pmu_battery_fp == nullptr) { + pmu_battery_fp = open_file(batt_path, &rep); + if (pmu_battery_fp == nullptr) { return; } + } + + if (pmu_battery_fp != nullptr) { + rewind(pmu_battery_fp); + while (!feof(pmu_battery_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } + + if (buf[0] == 'f') { + sscanf(buf, "flags : %8x", &flags); + } else if (buf[0] == 'c' && buf[1] == 'h') { + sscanf(buf, "charge : %d", &charge); + } else if (buf[0] == 'm') { + sscanf(buf, "max_charge : %d", &max_charge); + } else if (buf[0] == 't') { + sscanf(buf, "time rem. : %ld", &timeval); + } + } + } + if (pmu_info_fp == nullptr) { + pmu_info_fp = open_file(info_path, &rep); + if (pmu_info_fp == nullptr) { return; } + } + + if (pmu_info_fp != nullptr) { + rewind(pmu_info_fp); + while (!feof(pmu_info_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } + if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } + } + } + /* update status string */ + if ((ac && !(flags & PMU_BATT_PRESENT))) { + strncpy(pb_battery_info[PB_BATT_STATUS], "AC", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if (ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charged", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else { + strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } + + /* update percentage string */ + if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); + } else if (timeval == 0) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); + } else { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", + (charge * 100) / max_charge); + } + + /* update time string */ + if (timeval == 0) { /* fully charged or battery not present */ + snprintf(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); + } else if (timeval < 60 * 60) { /* don't show secs */ + format_seconds_short(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } else { + format_seconds(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } + + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + } #define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail" -int get_entropy_avail(unsigned int *val) { - static int rep = 0; - FILE *fp; + int get_entropy_avail(unsigned int *val) { + static int rep = 0; + FILE *fp; - if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; + if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; - if (fscanf(fp, "%u", val) != 1) return 1; + if (fscanf(fp, "%u", val) != 1) return 1; - fclose(fp); - return 0; -} + fclose(fp); + return 0; + } #define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize" -int get_entropy_poolsize(unsigned int *val) { - static int rep = 0; - FILE *fp; - - if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; - - if (fscanf(fp, "%u", val) != 1) return 1; - - fclose(fp); - return 0; -} - -void print_disk_protect_queue(struct text_object *obj, char *p, - int p_max_size) { - FILE *fp; - char path[128]; - int state; - - snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); - if (access(path, F_OK)) { - snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); - } - if ((fp = fopen(path, "r")) == nullptr) { - snprintf(p, p_max_size, "%s", "n/a "); - return; - } - if (fscanf(fp, "%d\n", &state) != 1) { - fclose(fp); - snprintf(p, p_max_size, "%s", "failed"); - return; - } - fclose(fp); - snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); -} - -std::unordered_map dev_list; - -/* Same as sf #2942117 but memoized using a linked list */ -int is_disk(char *dev) { - std::string orig(dev); - std::string syspath("/sys/block/"); - char *slash; - - auto i = dev_list.find(orig); - if (i != dev_list.end()) return i->second; - - while ((slash = strchr(dev, '/'))) *slash = '!'; - syspath += dev; - - return dev_list[orig] = !(access(syspath.c_str(), F_OK)); -} - -int update_diskio(void) { - FILE *fp; - static int rep = 0; - char buf[512], devbuf[64]; - unsigned int major, minor; - int col_count = 0; - struct diskio_stat *cur; - unsigned int reads, writes; - unsigned int total_reads = 0, total_writes = 0; - - stats.current = 0; - stats.current_read = 0; - stats.current_write = 0; - - if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } - - /* read reads and writes from all disks (minor = 0), including cd-roms - * and floppies, and sum them up */ - while (fgets(buf, 512, fp)) { - col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, - &minor, devbuf, &reads, &writes); - /* ignore subdevices (they have only 3 matching entries in their line) - * and virtual devices (LVM, network block devices, RAM disks, Loopback) - * - * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ - if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && - major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { - /* check needed for kernel >= 2.6.31, see sf #2942117 */ - if (is_disk(devbuf)) { - total_reads += reads; - total_writes += writes; - } - } else { - col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, - &reads, &writes); - if (col_count != 5) { continue; } - } - cur = stats.next; - while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; - - if (cur) update_diskio_values(cur, reads, writes); - } - update_diskio_values(&stats, total_reads, total_writes); - fclose(fp); - return 0; -} - -void print_distribution(struct text_object *obj, char *p, int p_max_size) { - (void)obj; - int i, bytes_read; - char *buf; - struct stat sb; - - if (stat("/etc/arch-release", &sb) == 0) { - snprintf(p, p_max_size, "%s", "Arch Linux"); - return; - } - snprintf(p, p_max_size, "Unknown"); - buf = readfile("/proc/version", &bytes_read, 1); - if (buf) { - /* I am assuming the distribution name is the first string in /proc/version - that: - - is preceded by a '(' - - starts with a capital - - is followed by a space and a number - but i am not sure if this is always true... */ - for (i = 1; i < bytes_read; i++) { - if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; - } - if (i < bytes_read) { - snprintf(p, p_max_size, "%s", &buf[i]); - for (i = 1; p[i]; i++) { - if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { - p[i - 1] = 0; - break; - } - } - } - free(buf); - } -} - -/****************************************** - * Calculate cpu total * - ******************************************/ + int get_entropy_poolsize(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + + void print_disk_protect_queue(struct text_object *obj, char *p, + int p_max_size) { + FILE *fp; + char path[128]; + int state; + + snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); + if (access(path, F_OK)) { + snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); + } + if ((fp = fopen(path, "r")) == nullptr) { + snprintf(p, p_max_size, "%s", "n/a "); + return; + } + if (fscanf(fp, "%d\n", &state) != 1) { + fclose(fp); + snprintf(p, p_max_size, "%s", "failed"); + return; + } + fclose(fp); + snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); + } + + std::unordered_map dev_list; + + /* Same as sf #2942117 but memoized using a linked list */ + int is_disk(char *dev) { + std::string orig(dev); + std::string syspath("/sys/block/"); + char *slash; + + auto i = dev_list.find(orig); + if (i != dev_list.end()) return i->second; + + while ((slash = strchr(dev, '/'))) *slash = '!'; + syspath += dev; + + return dev_list[orig] = !(access(syspath.c_str(), F_OK)); + } + + int update_diskio(void) { + FILE *fp; + static int rep = 0; + char buf[512], devbuf[64]; + unsigned int major, minor; + int col_count = 0; + struct diskio_stat *cur; + unsigned int reads, writes; + unsigned int total_reads = 0, total_writes = 0; + + stats.current = 0; + stats.current_read = 0; + stats.current_write = 0; + + if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } + + /* read reads and writes from all disks (minor = 0), including cd-roms + * and floppies, and sum them up */ + while (fgets(buf, 512, fp)) { + col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, + &minor, devbuf, &reads, &writes); + /* ignore subdevices (they have only 3 matching entries in their line) + * and virtual devices (LVM, network block devices, RAM disks, Loopback) + * + * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ + if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && + major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { + /* check needed for kernel >= 2.6.31, see sf #2942117 */ + if (is_disk(devbuf)) { + total_reads += reads; + total_writes += writes; + } + } else { + col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, + &reads, &writes); + if (col_count != 5) { continue; } + } + cur = stats.next; + while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; + + if (cur) update_diskio_values(cur, reads, writes); + } + update_diskio_values(&stats, total_reads, total_writes); + fclose(fp); + return 0; + } + + void print_distribution(struct text_object *obj, char *p, int p_max_size) { + (void)obj; + int i, bytes_read; + char *buf; + struct stat sb; + + if (stat("/etc/arch-release", &sb) == 0) { + snprintf(p, p_max_size, "%s", "Arch Linux"); + return; + } + snprintf(p, p_max_size, "Unknown"); + buf = readfile("/proc/version", &bytes_read, 1); + if (buf) { + /* I am assuming the distribution name is the first string in /proc/version + that: + - is preceded by a '(' + - starts with a capital + - is followed by a space and a number + but i am not sure if this is always true... */ + for (i = 1; i < bytes_read; i++) { + if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; + } + if (i < bytes_read) { + snprintf(p, p_max_size, "%s", &buf[i]); + for (i = 1; p[i]; i++) { + if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { + p[i - 1] = 0; + break; + } + } + } + free(buf); + } + } + + /****************************************** + * Calculate cpu total * + ******************************************/ #define TMPL_SHORTPROC "%*s %llu %llu %llu %llu" #define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu" -static unsigned long long calc_cpu_total(void) { - static unsigned long long previous_total = 0; - unsigned long long total = 0; - unsigned long long t = 0; - int rc; - int ps; - char line[BUFFER_LEN] = {0}; - unsigned long long cpu = 0; - unsigned long long niceval = 0; - unsigned long long systemval = 0; - unsigned long long idle = 0; - unsigned long long iowait = 0; - unsigned long long irq = 0; - unsigned long long softirq = 0; - unsigned long long steal = 0; - const char *template_ = - KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; - - ps = open("/proc/stat", O_RDONLY); - rc = read(ps, line, BUFFER_LEN - 1); - close(ps); - if (rc < 0) { return 0; } - - sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, - &softirq, &steal); - total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; - - t = total - previous_total; - previous_total = total; - - return t; -} - -/****************************************** - * Calculate each processes cpu * - ******************************************/ - -inline static void calc_cpu_each(unsigned long long total) { - float mul = 100.0; - if (top_cpu_separate.get(*state)) mul *= info.cpu_count; - - for (struct process *p = first_process; p; p = p->next) - p->amount = mul * (p->user_time + p->kernel_time) / (float)total; -} + static unsigned long long calc_cpu_total(void) { + static unsigned long long previous_total = 0; + unsigned long long total = 0; + unsigned long long t = 0; + int rc; + int ps; + char line[BUFFER_LEN] = {0}; + unsigned long long cpu = 0; + unsigned long long niceval = 0; + unsigned long long systemval = 0; + unsigned long long idle = 0; + unsigned long long iowait = 0; + unsigned long long irq = 0; + unsigned long long softirq = 0; + unsigned long long steal = 0; + const char *template_ = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; + + ps = open("/proc/stat", O_RDONLY); + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return 0; } + + sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, + &softirq, &steal); + total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; + + t = total - previous_total; + previous_total = total; + + return t; + } + + /****************************************** + * Calculate each processes cpu * + ******************************************/ + + inline static void calc_cpu_each(unsigned long long total) { + float mul = 100.0; + if (top_cpu_separate.get(*state)) mul *= info.cpu_count; + + for (struct process *p = first_process; p; p = p->next) + p->amount = mul * (p->user_time + p->kernel_time) / (float)total; + } #ifdef BUILD_IOSTATS -static void calc_io_each(void) { - struct process *p; - unsigned long long sum = 0; + static void calc_io_each(void) { + struct process *p; + unsigned long long sum = 0; - for (p = first_process; p; p = p->next) sum += p->read_bytes + p->write_bytes; + for (p = first_process; p; p = p->next) + sum += p->read_bytes + p->write_bytes; - if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ - for (p = first_process; p; p = p->next) - p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; -} + if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ + for (p = first_process; p; p = p->next) + p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; + } #endif /* BUILD_IOSTATS */ -/****************************************** - * Extract information from /proc * - ******************************************/ + /****************************************** + * Extract information from /proc * + ******************************************/ #define PROCFS_TEMPLATE "/proc/%d/stat" #define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline" -/* These are the guts that extract information out of /proc. - * Anyone hoping to port wmtop should look here first. */ -static void process_parse_stat(struct process *process) { - char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; - char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], - cmdline_procname[BUFFER_LEN]; - char basename[BUFFER_LEN] = {0}; - char tmpstr[BUFFER_LEN] = {0}; - char state[4]; - int ps, cmdline_ps; - unsigned long user_time = 0; - unsigned long kernel_time = 0; - int rc; - char *r, *q; - int endl; - int nice_val; - char *lparen, *rparen; - struct stat process_stat; - - snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); - snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, - process->pid); - - ps = open(filename, O_RDONLY); - if (ps == -1) { - /* The process must have finished in the last few jiffies! */ - return; - } - - if (fstat(ps, &process_stat) != 0) { - close(ps); - return; - } - process->uid = process_stat.st_uid; - - /* Mark process as up-to-date. */ - process->time_stamp = g_time; - - rc = read(ps, line, BUFFER_LEN - 1); - close(ps); - if (rc < 0) { return; } - - /* Read /proc//cmdline */ - cmdline_ps = open(cmdline_filename, O_RDONLY); - if (cmdline_ps < 0) { - /* The process must have finished in the last few jiffies! */ - return; - } - - endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); - close(cmdline_ps); - if (endl < 0) { return; } - - /* Some processes have null-separated arguments (see proc(5)); let's fix it */ - int i = endl; - while (i && cmdline[i - 1] == 0) { - /* Skip past any trailing null characters */ - --i; - } - while (i--) { - /* Replace null character between arguments with a space */ - if (cmdline[i] == 0) { cmdline[i] = ' '; } - } - - cmdline[endl] = 0; - - /* We want to transform for example "/usr/bin/python program.py" to "python - * program.py" - * 1. search for first space - * 2. search for last / before first space - * 3. copy string from its position - */ - char *space_ptr = strchr(cmdline, ' '); - if (space_ptr == nullptr) { - strncpy(tmpstr, cmdline, BUFFER_LEN); - } else { - long int space_pos = space_ptr - cmdline; - strncpy(tmpstr, cmdline, space_pos); - tmpstr[space_pos] = 0; - } - - char *slash_ptr = strrchr(tmpstr, '/'); - if (slash_ptr == nullptr) { - strncpy(cmdline_procname, cmdline, BUFFER_LEN); - } else { - long int slash_pos = slash_ptr - tmpstr; - strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); - cmdline_procname[BUFFER_LEN - slash_pos] = 0; - } - - /* Extract cpu times from data in /proc filesystem */ - lparen = strchr(line, '('); - rparen = strrchr(line, ')'); - if (!lparen || !rparen || rparen < lparen) return; // this should not happen - - rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); - strncpy(procname, lparen + 1, rc); - procname[rc] = '\0'; - strncpy(basename, procname, strlen(procname) + 1); - - if (strlen(procname) < strlen(cmdline_procname)) - strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); - - rc = sscanf(rparen + 1, - "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " - "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", - state, &process->user_time, &process->kernel_time, &nice_val, - &process->vsize, &process->rss); - if (rc < 6) { - NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); - return; - } - - if (state[0] == 'R') ++info.run_procs; - - free_and_zero(process->name); - free_and_zero(process->basename); - process->name = strndup(procname, text_buffer_size.get(*::state)); - process->basename = strndup(basename, text_buffer_size.get(*::state)); - process->rss *= getpagesize(); - - process->total_cpu_time = process->user_time + process->kernel_time; - if (process->previous_user_time == ULONG_MAX) { - process->previous_user_time = process->user_time; - } - if (process->previous_kernel_time == ULONG_MAX) { - process->previous_kernel_time = process->kernel_time; - } - - /* strangely, the values aren't monotonous */ - if (process->previous_user_time > process->user_time) - process->previous_user_time = process->user_time; - - if (process->previous_kernel_time > process->kernel_time) - process->previous_kernel_time = process->kernel_time; - - /* store the difference of the user_time */ - user_time = process->user_time - process->previous_user_time; - kernel_time = process->kernel_time - process->previous_kernel_time; - - /* backup the process->user_time for next time around */ - process->previous_user_time = process->user_time; - process->previous_kernel_time = process->kernel_time; - - /* store only the difference of the user_time here... */ - process->user_time = user_time; - process->kernel_time = kernel_time; -} + /* These are the guts that extract information out of /proc. + * Anyone hoping to port wmtop should look here first. */ + static void process_parse_stat(struct process *process) { + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; + char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], + cmdline_procname[BUFFER_LEN]; + char basename[BUFFER_LEN] = {0}; + char tmpstr[BUFFER_LEN] = {0}; + char state[4]; + int ps, cmdline_ps; + unsigned long user_time = 0; + unsigned long kernel_time = 0; + int rc; + char *r, *q; + int endl; + int nice_val; + char *lparen, *rparen; + struct stat process_stat; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); + snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, + process->pid); + + ps = open(filename, O_RDONLY); + if (ps == -1) { + /* The process must have finished in the last few jiffies! */ + return; + } + + if (fstat(ps, &process_stat) != 0) { + close(ps); + return; + } + process->uid = process_stat.st_uid; + + /* Mark process as up-to-date. */ + process->time_stamp = g_time; + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + /* Read /proc//cmdline */ + cmdline_ps = open(cmdline_filename, O_RDONLY); + if (cmdline_ps < 0) { + /* The process must have finished in the last few jiffies! */ + return; + } + + endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); + close(cmdline_ps); + if (endl < 0) { return; } + + /* Some processes have null-separated arguments (see proc(5)); let's fix it + */ + int i = endl; + while (i && cmdline[i - 1] == 0) { + /* Skip past any trailing null characters */ + --i; + } + while (i--) { + /* Replace null character between arguments with a space */ + if (cmdline[i] == 0) { cmdline[i] = ' '; } + } + + cmdline[endl] = 0; + + /* We want to transform for example "/usr/bin/python program.py" to "python + * program.py" + * 1. search for first space + * 2. search for last / before first space + * 3. copy string from its position + */ + char *space_ptr = strchr(cmdline, ' '); + if (space_ptr == nullptr) { + strncpy(tmpstr, cmdline, BUFFER_LEN); + } else { + long int space_pos = space_ptr - cmdline; + strncpy(tmpstr, cmdline, space_pos); + tmpstr[space_pos] = 0; + } + + char *slash_ptr = strrchr(tmpstr, '/'); + if (slash_ptr == nullptr) { + strncpy(cmdline_procname, cmdline, BUFFER_LEN); + } else { + long int slash_pos = slash_ptr - tmpstr; + strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); + cmdline_procname[BUFFER_LEN - slash_pos] = 0; + } + + /* Extract cpu times from data in /proc filesystem */ + lparen = strchr(line, '('); + rparen = strrchr(line, ')'); + if (!lparen || !rparen || rparen < lparen) return; // this should not happen + + rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); + strncpy(procname, lparen + 1, rc); + procname[rc] = '\0'; + strncpy(basename, procname, strlen(procname) + 1); + + if (strlen(procname) < strlen(cmdline_procname)) + strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); + + rc = sscanf(rparen + 1, + "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " + "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", + state, &process->user_time, &process->kernel_time, &nice_val, + &process->vsize, &process->rss); + if (rc < 6) { + NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); + return; + } + + if (state[0] == 'R') ++info.run_procs; + + free_and_zero(process->name); + free_and_zero(process->basename); + process->name = strndup(procname, text_buffer_size.get(*::state)); + process->basename = strndup(basename, text_buffer_size.get(*::state)); + process->rss *= getpagesize(); + + process->total_cpu_time = process->user_time + process->kernel_time; + if (process->previous_user_time == ULONG_MAX) { + process->previous_user_time = process->user_time; + } + if (process->previous_kernel_time == ULONG_MAX) { + process->previous_kernel_time = process->kernel_time; + } + + /* strangely, the values aren't monotonous */ + if (process->previous_user_time > process->user_time) + process->previous_user_time = process->user_time; + + if (process->previous_kernel_time > process->kernel_time) + process->previous_kernel_time = process->kernel_time; + + /* store the difference of the user_time */ + user_time = process->user_time - process->previous_user_time; + kernel_time = process->kernel_time - process->previous_kernel_time; + + /* backup the process->user_time for next time around */ + process->previous_user_time = process->user_time; + process->previous_kernel_time = process->kernel_time; + + /* store only the difference of the user_time here... */ + process->user_time = user_time; + process->kernel_time = kernel_time; + } #ifdef BUILD_IOSTATS #define PROCFS_TEMPLATE_IO "/proc/%d/io" -static void process_parse_io(struct process *process) { - static const char *read_bytes_str = "read_bytes:"; - static const char *write_bytes_str = "write_bytes:"; - - char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; - int ps; - int rc; - char *pos, *endpos; - unsigned long long read_bytes, write_bytes; - - snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); - - ps = open(filename, O_RDONLY); - if (ps < 0) { - /* The process must have finished in the last few jiffies! - * Or, the kernel doesn't support I/O accounting. - */ - return; - } - - rc = read(ps, line, BUFFER_LEN - 1); - close(ps); - if (rc < 0) { return; } - - pos = strstr(line, read_bytes_str); - if (pos == nullptr) { - /* these should not happen (unless the format of the file changes) */ - return; - } - pos += strlen(read_bytes_str); - process->read_bytes = strtoull(pos, &endpos, 10); - if (endpos == pos) { return; } - - pos = strstr(line, write_bytes_str); - if (pos == nullptr) { return; } - pos += strlen(write_bytes_str); - process->write_bytes = strtoull(pos, &endpos, 10); - if (endpos == pos) { return; } - - if (process->previous_read_bytes == ULLONG_MAX) { - process->previous_read_bytes = process->read_bytes; - } - if (process->previous_write_bytes == ULLONG_MAX) { - process->previous_write_bytes = process->write_bytes; - } - - /* store the difference of the byte counts */ - read_bytes = process->read_bytes - process->previous_read_bytes; - write_bytes = process->write_bytes - process->previous_write_bytes; - - /* backup the counts for next time around */ - process->previous_read_bytes = process->read_bytes; - process->previous_write_bytes = process->write_bytes; - - /* store only the difference here... */ - process->read_bytes = read_bytes; - process->write_bytes = write_bytes; -} + static void process_parse_io(struct process *process) { + static const char *read_bytes_str = "read_bytes:"; + static const char *write_bytes_str = "write_bytes:"; + + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; + int ps; + int rc; + char *pos, *endpos; + unsigned long long read_bytes, write_bytes; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); + + ps = open(filename, O_RDONLY); + if (ps < 0) { + /* The process must have finished in the last few jiffies! + * Or, the kernel doesn't support I/O accounting. + */ + return; + } + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + pos = strstr(line, read_bytes_str); + if (pos == nullptr) { + /* these should not happen (unless the format of the file changes) */ + return; + } + pos += strlen(read_bytes_str); + process->read_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + pos = strstr(line, write_bytes_str); + if (pos == nullptr) { return; } + pos += strlen(write_bytes_str); + process->write_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + if (process->previous_read_bytes == ULLONG_MAX) { + process->previous_read_bytes = process->read_bytes; + } + if (process->previous_write_bytes == ULLONG_MAX) { + process->previous_write_bytes = process->write_bytes; + } + + /* store the difference of the byte counts */ + read_bytes = process->read_bytes - process->previous_read_bytes; + write_bytes = process->write_bytes - process->previous_write_bytes; + + /* backup the counts for next time around */ + process->previous_read_bytes = process->read_bytes; + process->previous_write_bytes = process->write_bytes; + + /* store only the difference here... */ + process->read_bytes = read_bytes; + process->write_bytes = write_bytes; + } #endif /* BUILD_IOSTATS */ -/****************************************** - * Get process structure for process pid * - ******************************************/ + /****************************************** + * Get process structure for process pid * + ******************************************/ -/* This function seems to hog all of the CPU time. - * I can't figure out why - it doesn't do much. */ -static void calculate_stats(struct process *process) { - /* compute each process cpu usage by reading /proc//stat */ - process_parse_stat(process); + /* This function seems to hog all of the CPU time. + * I can't figure out why - it doesn't do much. */ + static void calculate_stats(struct process *process) { + /* compute each process cpu usage by reading /proc//stat */ + process_parse_stat(process); #ifdef BUILD_IOSTATS - process_parse_io(process); + process_parse_io(process); #endif /* BUILD_IOSTATS */ - /* - * Check name against the exclusion list - */ - /* if (process->counted && exclusion_expression && - * !regexec(exclusion_expression, process->name, 0, 0, 0)) - * process->counted = 0; */ -} + /* + * Check name against the exclusion list + */ + /* if (process->counted && exclusion_expression && + * !regexec(exclusion_expression, process->name, 0, 0, 0)) + * process->counted = 0; */ + } -/****************************************** - * Update process table * - ******************************************/ + /****************************************** + * Update process table * + ******************************************/ -static void update_process_table(void) { - DIR *dir; - struct dirent *entry; + static void update_process_table(void) { + DIR *dir; + struct dirent *entry; - if (!(dir = opendir("/proc"))) { return; } + if (!(dir = opendir("/proc"))) { return; } - info.run_procs = 0; + info.run_procs = 0; - /* Get list of processes from /proc directory */ - while ((entry = readdir(dir))) { - pid_t pid; + /* Get list of processes from /proc directory */ + while ((entry = readdir(dir))) { + pid_t pid; - if (sscanf(entry->d_name, "%d", &pid) > 0) { - /* compute each process cpu usage */ - calculate_stats(get_process(pid)); - } - } + if (sscanf(entry->d_name, "%d", &pid) > 0) { + /* compute each process cpu usage */ + calculate_stats(get_process(pid)); + } + } - closedir(dir); -} + closedir(dir); + } -void get_top_info(void) { - unsigned long long total = 0; + void get_top_info(void) { + unsigned long long total = 0; - total = calc_cpu_total(); /* calculate the total of the processor */ - update_process_table(); /* update the table with process list */ - calc_cpu_each(total); /* and then the percentage for each task */ + total = calc_cpu_total(); /* calculate the total of the processor */ + update_process_table(); /* update the table with process list */ + calc_cpu_each(total); /* and then the percentage for each task */ #ifdef BUILD_IOSTATS - calc_io_each(); /* percentage of I/O for each task */ -#endif /* BUILD_IOSTATS */ -} + calc_io_each(); /* percentage of I/O for each task */ +#endif /* BUILD_IOSTATS */ + } diff --git a/src/netbsd.cc b/src/netbsd.cc index 514657806c..8067f88c47 100644 --- a/src/netbsd.cc +++ b/src/netbsd.cc @@ -8,7 +8,7 @@ * * Please see COPYING for details * - * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen + * Copyright (c) 2007 Toni Spets * Copyright (c) 2005-2018 Brenden Matthews, Philip Kovacs, et. al. * (see AUTHORS) * All rights reserved. @@ -27,200 +27,234 @@ * */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "conky.h" +#include "diskio.h" +#include "logging.h" #include "net_stat.h" -#include "netbsd.h" +#include "openbsd.h" +#include "top.h" -static kvm_t *kd = nullptr; -int kd_init = 0, nkd_init = 0; -u_int32_t sensvalue; -char errbuf[_POSIX2_LINE_MAX]; +#define MAXSHOWDEVS 16 -static int init_kvm(void) { - if (kd_init) { return 0; } +#define LOG1024 10 +#define pagetok(size) ((size) << pageshift) - kd = kvm_openfiles(nullptr, NULL, NULL, KVM_NO_FILES, errbuf); +inline void proc_find_top(struct process **cpu, struct process **mem); + +static short cpu_setup = 0; +static kvm_t *kd = 0; + +struct ifmibdata *data = nullptr; +size_t len = 0; + +int init_kvm = 0; +int init_sensors = 0; + +static int kvm_init() { + if (init_kvm) { return 1; } + + kd = kvm_open(nullptr, NULL, NULL, KVM_NO_FILES, NULL); if (kd == nullptr) { - warnx("cannot kvm_openfiles: %s", errbuf); - return -1; + NORM_ERR("error opening kvm"); + } else { + init_kvm = 1; } - kd_init = 1; - return 0; + + return 1; } -static int swapmode(int *retavail, int *retfree) { - int n; - struct swapent *sep; +/* note: swapmode taken from 'top' source */ +/* swapmode is rewritten by Tobias Weingartner + * to be based on the new swapctl(2) system call. */ +static int swapmode(int *used, int *total) { + struct swapent *swdev; + int nswap, rnswap, i; - *retavail = 0; - *retfree = 0; + nswap = swapctl(SWAP_NSWAP, 0, 0); + if (nswap == 0) { return 0; } - n = swapctl(SWAP_NSWAP, 0, 0); + swdev = malloc(nswap * sizeof(*swdev)); + if (swdev == nullptr) { return 0; } - if (n < 1) { - warn("could not get swap information"); + rnswap = swapctl(SWAP_STATS, swdev, nswap); + if (rnswap == -1) { + free(swdev); return 0; } - sep = (struct swapent *)malloc(n * (sizeof(*sep))); - - if (sep == nullptr) { - warn("memory allocation failed"); - return 0; - } + /* if rnswap != nswap, then what? */ - if (swapctl(SWAP_STATS, (void *)sep, n) < n) { - warn("could not get swap stats"); - return 0; - } - for (; n > 0; n--) { - *retavail += (int)dbtob(sep[n - 1].se_nblks); - *retfree += (int)dbtob(sep[n - 1].se_nblks - sep[n - 1].se_inuse); + /* Total things up */ + *total = *used = 0; + for (i = 0; i < nswap; i++) { + if (swdev[i].se_flags & SWF_ENABLE) { + *used += (swdev[i].se_inuse / (1024 / DEV_BSIZE)); + *total += (swdev[i].se_nblks / (1024 / DEV_BSIZE)); + } } - *retavail = (int)(*retavail / 1024); - *retfree = (int)(*retfree / 1024); - + free(swdev); return 1; } -void prepare_update() {} +int check_mount(struct text_object *obj) { + /* stub */ + (void)obj; + return 0; +} void update_uptime() { int mib[2] = {CTL_KERN, KERN_BOOTTIME}; struct timeval boottime; time_t now; - int size = sizeof(boottime); + size_t size = sizeof(boottime); if ((sysctl(mib, 2, &boottime, &size, nullptr, 0) != -1) && (boottime.tv_sec != 0)) { time(&now); info.uptime = now - boottime.tv_sec; } else { - warn("could not get uptime"); + NORM_ERR("Could not get uptime"); info.uptime = 0; } } -int check_mount(struct text_object *obj) { - /* stub */ - (void)obj; - return 0; -} - void update_meminfo() { - int mib[] = {CTL_VM, VM_UVMEXP2}; - int total_pages, inactive_pages, free_pages; - int swap_avail, swap_free; - const int pagesize = getpagesize(); - struct uvmexp_sysctl uvmexp; - size_t size = sizeof(uvmexp); - - if (sysctl(mib, 2, &uvmexp, &size, nullptr, 0) < 0) { - warn("could not get memory info"); - return; + static int mib[2] = {CTL_VM, VM_METER}; + struct vmtotal vmtotal; + size_t size; + int pagesize, pageshift, swap_avail, swap_used; + + pagesize = getpagesize(); + pageshift = 0; + while (pagesize > 1) { + pageshift++; + pagesize >>= 1; } - total_pages = uvmexp.npages; - free_pages = uvmexp.free; - inactive_pages = uvmexp.inactive; + /* we only need the amount of log(2)1024 for our conversion */ + pageshift -= LOG1024; - info.memmax = (total_pages * pagesize) >> 10; - info.mem = ((total_pages - free_pages - inactive_pages) * pagesize) >> 10; - info.memwithbuffers = info.mem; + /* get total -- systemwide main memory usage structure */ + size = sizeof(vmtotal); + if (sysctl(mib, 2, &vmtotal, &size, nullptr, 0) < 0) { + warn("sysctl failed"); + bzero(&vmtotal, sizeof(vmtotal)); + } + + info.memmax = pagetok(vmtotal.t_rm) + pagetok(vmtotal.t_free); + info.mem = info.memwithbuffers = pagetok(vmtotal.t_rm); info.memeasyfree = info.memfree = info.memmax - info.mem; - if (swapmode(&swap_avail, &swap_free) >= 0) { + if ((swapmode(&swap_used, &swap_avail)) >= 0) { info.swapmax = swap_avail; - info.swap = (swap_avail - swap_free); - info.swapfree = swap_free; + info.swap = swap_used; + info.swapfree = swap_avail - swap_used; + } else { + info.swapmax = 0; + info.swap = 0; + info.swapfree = 0; } } void update_net_stats() { - int i; + struct net_stat *ns; double delta; - struct ifnet ifnet; - struct ifnet_head ifhead; /* interfaces are in a tail queue */ - u_long ifnetaddr; - static struct nlist namelist[] = {{"_ifnet"}, {nullptr}}; - static kvm_t *nkd; - - if (!nkd_init) { - nkd = kvm_openfiles(nullptr, NULL, NULL, O_RDONLY, errbuf); - if (nkd == nullptr) { - warnx("cannot kvm_openfiles: %s", errbuf); - warnx("maybe you need to setgid kmem this program?"); - return; - } else if (kvm_nlist(nkd, namelist) != 0) { - warn("cannot kvm_nlist"); - return; - } else { - nkd_init = 1; - } - } - - if (kvm_read(nkd, (u_long)namelist[0].n_value, (void *)&ifhead, - sizeof(ifhead)) < 0) { - warn("cannot kvm_read"); - return; - } + long long r, t, last_recv, last_trans; + struct ifaddrs *ifap, *ifa; + struct if_data *ifd; /* get delta */ delta = current_update_time - last_update_time; if (delta <= 0.0001) { return; } - for (i = 0, ifnetaddr = (u_long)ifhead.tqh_first; - ifnet.if_list.tqe_next && i < 16; - ifnetaddr = (u_long)ifnet.if_list.tqe_next, i++) { - struct net_stat *ns; - long long last_recv, last_trans; - - kvm_read(nkd, (u_long)ifnetaddr, (void *)&ifnet, sizeof(ifnet)); - ns = get_net_stat(ifnet.if_xname, nullptr, NULL); - ns->up = 1; - last_recv = ns->recv; - last_trans = ns->trans; - - if (ifnet.if_ibytes < ns->last_read_recv) { - ns->recv += - ((long long)4294967295U - ns->last_read_recv) + ifnet.if_ibytes; - } else { - ns->recv += (ifnet.if_ibytes - ns->last_read_recv); - } + if (getifaddrs(&ifap) < 0) { return; } - ns->last_read_recv = ifnet.if_ibytes; + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *)ifa->ifa_name, nullptr, NULL); - if (ifnet.if_obytes < ns->last_read_trans) { - ns->trans += - ((long long)4294967295U - ns->last_read_trans) + ifnet.if_obytes; - } else { - ns->trans += (ifnet.if_obytes - ns->last_read_trans); - } + if (ifa->ifa_flags & IFF_UP) { + struct ifaddrs *iftmp; + + ns->up = 1; + last_recv = ns->recv; + last_trans = ns->trans; - ns->last_read_trans = ifnet.if_obytes; + if (ifa->ifa_addr->sa_family != AF_LINK) { continue; } - ns->recv += (ifnet.if_ibytes - ns->last_read_recv); - ns->last_read_recv = ifnet.if_ibytes; - ns->trans += (ifnet.if_obytes - ns->last_read_trans); - ns->last_read_trans = ifnet.if_obytes; + for (iftmp = ifa->ifa_next; + iftmp != nullptr && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0; + iftmp = iftmp->ifa_next) { + if (iftmp->ifa_addr->sa_family == AF_INET) { + memcpy(&(ns->addr), iftmp->ifa_addr, iftmp->ifa_addr->sa_len); + } + } - ns->recv_speed = (ns->recv - last_recv) / delta; - ns->trans_speed = (ns->trans - last_trans) / delta; + ifd = (struct if_data *)ifa->ifa_data; + r = ifd->ifi_ibytes; + t = ifd->ifi_obytes; + + if (r < ns->last_read_recv) { + ns->recv += ((long long)4294967295U - ns->last_read_recv) + r; + } else { + ns->recv += (r - ns->last_read_recv); + } + + ns->last_read_recv = r; + + if (t < ns->last_read_trans) { + ns->trans += (long long)4294967295U - ns->last_read_trans + t; + } else { + ns->trans += (t - ns->last_read_trans); + } + + ns->last_read_trans = t; + + /* calculate speeds */ + ns->recv_speed = (ns->recv - last_recv) / delta; + ns->trans_speed = (ns->trans - last_trans) / delta; + } else { + ns->up = 0; + } } + + freeifaddrs(ifap); } int update_total_processes() { - /* It's easier to use kvm here than sysctl */ - int n_processes; - info.procs = 0; - - if (init_kvm() < 0) { - return; - } else { - kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), - &n_processes); - } + kvm_init(); + kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes); info.procs = n_processes; } @@ -230,41 +264,80 @@ void update_running_processes() { int n_processes; int i, cnt = 0; - info.run_procs = 0; + kvm_init(); + int max_size = sizeof(struct kinfo_proc2); - if (init_kvm() < 0) { - return; - } else { - p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), - &n_processes); - for (i = 0; i < n_processes; i++) { - if (p[i].p_stat == LSRUN || p[i].p_stat == LSIDL || - p[i].p_stat == LSONPROC) { - cnt++; - } - } + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, max_size, &n_processes); + for (i = 0; i < n_processes; i++) { + if (p[i].p_stat == SRUN) { cnt++; } } info.run_procs = cnt; } +/* new SMP code can be enabled by commenting the following line */ +#define OLDCPU + +#ifdef OLDCPU struct cpu_load_struct { unsigned long load[5]; }; struct cpu_load_struct fresh = {{0, 0, 0, 0, 0}}; - long cpu_used, oldtotal, oldused; +#else +#include +int64_t *fresh = nullptr; + +/* XXX is 8 enough? - What's the constant for MAXCPU? */ +/* allocate this with malloc would be better */ +int64_t oldtotal[8], oldused[8]; +#endif + +void get_cpu_count() { + int cpu_count = 1; /* default to 1 cpu */ +#ifndef OLDCPU + int mib[2] = {CTL_HW, HW_NCPU}; + size_t len = sizeof(cpu_count); + + if (sysctl(mib, 2, &cpu_count, &len, nullptr, 0) != 0) { + NORM_ERR("error getting cpu count, defaulting to 1"); + } +#endif + info.cpu_count = cpu_count; + + info.cpu_usage = malloc(info.cpu_count * sizeof(float)); + if (info.cpu_usage == nullptr) { CRIT_ERR(nullptr, NULL, "malloc"); } + +#ifndef OLDCPU + assert(fresh == nullptr); /* XXX Is this leaking memory? */ + /* XXX Where shall I free this? */ + if (nullptr == (fresh = calloc(cpu_count, sizeof(int64_t) * CPUSTATES))) { + CRIT_ERR(nullptr, NULL, "calloc"); + } +#endif +} void update_cpu_usage() { +#ifdef OLDCPU + int mib[2] = {CTL_KERN, KERN_CPTIME}; long used, total; - static u_int64_t cp_time[CPUSTATES]; + long cp_time[CPUSTATES]; size_t len = sizeof(cp_time); +#else + size_t size; + unsigned int i; +#endif + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if ((cpu_setup == 0) || (!info.cpu_usage)) { + get_cpu_count(); + cpu_setup = 1; + } - info.cpu_usage = 0; - - if (sysctlbyname("kern.cp_time", &cp_time, &len, nullptr, 0) < 0) { - warn("cannot get kern.cp_time"); +#ifdef OLDCPU + if (sysctl(mib, 2, &cp_time, &len, nullptr, 0) < 0) { + NORM_ERR("Cannot get kern.cp_time"); } fresh.load[0] = cp_time[CP_USER]; @@ -277,18 +350,58 @@ void update_cpu_usage() { total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3]; if ((total - oldtotal) != 0) { - info.cpu_usage = ((double)(used - oldused)) / (double)(total - oldtotal); + info.cpu_usage[0] = ((double)(used - oldused)) / (double)(total - oldtotal); } else { - info.cpu_usage = 0; + info.cpu_usage[0] = 0; } oldused = used; oldtotal = total; -} +#else + if (info.cpu_count > 1) { + size = CPUSTATES * sizeof(int64_t); + for (i = 0; i < info.cpu_count; i++) { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME2, i}; + if (sysctl(cp_time_mib, 3, &(fresh[i * CPUSTATES]), &size, nullptr, 0) < + 0) { + NORM_ERR("sysctl kern.cp_time2 failed"); + } + } + } else { + int cp_time_mib[] = {CTL_KERN, KERN_CPTIME}; + long cp_time_tmp[CPUSTATES]; + + size = sizeof(cp_time_tmp); + if (sysctl(cp_time_mib, 2, cp_time_tmp, &size, nullptr, 0) < 0) { + NORM_ERR("sysctl kern.cp_time failed"); + } + + for (i = 0; i < CPUSTATES; i++) { fresh[i] = (int64_t)cp_time_tmp[i]; } + } + + /* XXX Do sg with this int64_t => long => double ? float hell. */ + for (i = 0; i < info.cpu_count; i++) { + int64_t used, total; + int at = i * CPUSTATES; -void free_cpu(struct text_object *) { + used = fresh[at + CP_USER] + fresh[at + CP_NICE] + fresh[at + CP_SYS]; + total = used + fresh[at + CP_IDLE]; + + if ((total - oldtotal[i]) != 0) { + info.cpu_usage[i] = + ((double)(used - oldused[i])) / (double)(total - oldtotal[i]); + } else { + info.cpu_usage[i] = 0; + } + + oldused[i] = used; + oldtotal[i] = total; + } +#endif } +void free_cpu(struct text_object *) { /* not used */ } + void update_load_average() { double v[3]; @@ -299,30 +412,2536 @@ void update_load_average() { info.loadavg[2] = (float)v[2]; } -double get_acpi_temperature(int fd) { return -1; } +#define OBSD_MAX_SENSORS 256 +static struct obsd_sensors_struct { + int device; + float temp[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + unsigned int fan[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; + float volt[MAXSENSORDEVICES][OBSD_MAX_SENSORS]; +} obsd_sensors; + +static conky::simple_config_setting sensor_device("sensor_device", 0, + false); + +/* read sensors from sysctl */ +void update_obsd_sensors() { + int sensor_cnt, dev, numt, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0}; + struct sensor sensor; + struct sensordev sensordev; + size_t slen, sdlen; + enum sensor_type type; + + slen = sizeof(sensor); + sdlen = sizeof(sensordev); + + sensor_cnt = 0; + + dev = obsd_sensors.device; // FIXME: read more than one device + + /* for (dev = 0; dev < MAXSENSORDEVICES; dev++) { */ + mib[2] = dev; + if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + return; + // continue; + } + for (type = 0; type < SENSOR_MAX_TYPES; type++) { + mib[3] = type; + for (numt = 0; numt < sensordev.maxnumt[type]; numt++) { + mib[4] = numt; + if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) == -1) { + if (errno != ENOENT) { warn("sysctl"); } + continue; + } + if (sensor.flags & SENSOR_FINVALID) { continue; } + + switch (type) { + case SENSOR_TEMP: + obsd_sensors.temp[dev][sensor.numt] = + (sensor.value - 273150000) / 1000000.0; + break; + case SENSOR_FANRPM: + obsd_sensors.fan[dev][sensor.numt] = sensor.value; + break; + case SENSOR_VOLTS_DC: + obsd_sensors.volt[dev][sensor.numt] = sensor.value / 1000000.0; + break; + default: + break; + } + + sensor_cnt++; + } + } + /* } */ + + init_sensors = 1; +} + +void parse_obsd_sensor(struct text_object *obj, const char *arg) { + if (!isdigit((unsigned char)arg[0]) || atoi(&arg[0]) < 0 || + atoi(&arg[0]) > OBSD_MAX_SENSORS - 1) { + obj->data.l = 0; + NORM_ERR("Invalid sensor number!"); + } else + obj->data.l = atoi(&arg[0]); +} + +void print_obsd_sensors_temp(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + temp_print(p, p_max_size, obsd_sensors.temp[obsd_sensors.device][obj->data.l], + TEMP_CELSIUS, 1); +} + +void print_obsd_sensors_fan(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%d", + obsd_sensors.fan[obsd_sensors.device][obj->data.l]); +} + +void print_obsd_sensors_volt(struct text_object *obj, char *p, int p_max_size) { + obsd_sensors.device = sensor_device.get(*state); + update_obsd_sensors(); + snprintf(p, p_max_size, "%.2f", + obsd_sensors.volt[obsd_sensors.device][obj->data.l]); +} + +/* chipset vendor */ +void get_obsd_vendor(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char vendor[64]; + size_t size = sizeof(vendor); + + (void)obj; + + mib[0] = CTL_HW; + mib[1] = HW_VENDOR; + + if (sysctl(mib, 2, vendor, &size, nullptr, 0) == -1) { + NORM_ERR("error reading vendor"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", vendor); + } +} + +/* chipset name */ +void get_obsd_product(struct text_object *obj, char *buf, + size_t client_buffer_size) { + int mib[2]; + char product[64]; + size_t size = sizeof(product); + + (void)obj; -void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item) {} + mib[0] = CTL_HW; + mib[1] = HW_PRODUCT; -int open_acpi_temperature(const char *name) { return -1; } + if (sysctl(mib, 2, product, &size, nullptr, 0) == -1) { + NORM_ERR("error reading product"); + snprintf(buf, client_buffer_size, "%s", "unknown"); + } else { + snprintf(buf, client_buffer_size, "%s", product); + } +} -void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, - const char *adapter) { - (void)adapter; // only linux uses this +/* void */ +char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + int freq = cpu; + int mib[2] = {CTL_HW, HW_CPUSPEED}; - if (!p_client_buffer || client_buffer_size <= 0) { return; } + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + size_t size = sizeof(freq); + + if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) { + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + } else { + snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f); + } + + return 1; +} - /* not implemented */ - memset(p_client_buffer, 0, client_buffer_size); +#if 0 +/* deprecated, will rewrite this soon in update_net_stats() -hifi */ +void update_wifi_stats() +{ + struct net_stat *ns; + struct ifaddrs *ifap, *ifa; + struct ifmediareq ifmr; + struct ieee80211_nodereq nr; + struct ieee80211_bssid bssid; + int s, ibssid; + + /* Get iface table */ + if (getifaddrs(&ifap) < 0) { + return; + } + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + ns = get_net_stat((const char *) ifa->ifa_name); + + s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + /* Get media type */ + bzero(&ifmr, sizeof(ifmr)); + strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ); + if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) { + close(s); + return; + } + + /* We can monitor only wireless interfaces + * which are not in hostap mode */ + if ((ifmr.ifm_active & IFM_IEEE80211) + && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) { + /* Get wi status */ + + memset(&bssid, 0, sizeof(bssid)); + strlcpy(bssid.i_name, ifa->ifa_name, sizeof(bssid.i_name)); + ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + + bzero(&nr, sizeof(nr)); + bcopy(bssid.i_bssid, &nr.nr_macaddr, sizeof(nr.nr_macaddr)); + strlcpy(nr.nr_ifname, ifa->ifa_name, sizeof(nr.nr_ifname)); + + if (ioctl(s, SIOCG80211NODE, &nr) == 0 && nr.nr_rssi) { + ns->linkstatus = nr.nr_rssi; + } + } +cleanup: + close(s); + } } +#endif + +void clear_diskio_stats() {} + +struct diskio_stat *prepare_diskio_stat(const char *s) {} + +void update_diskio() { return; /* XXX: implement? hifi: not sure how */ } -/* char *get_acpi_fan() */ -void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { - if (!p_client_buffer || client_buffer_size <= 0) { return; } +/* While topless is obviously better, top is also not bad. */ + +void get_top_info(void) { + struct kinfo_proc2 *p; + struct process *proc; + int n_processes; + int i; - /* not implemented */ - memset(p_client_buffer, 0, client_buffer_size); + kvm_init(); + + p = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), + &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].p_flag & P_SYSTEM)) && p[i].p_comm != nullptr) { + proc = find_process(p[i].p_pid); + if (!proc) proc = new_process(p[i].p_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].p_comm, text_buffer_size); + proc->amount = 100.0 * p[i].p_pctcpu / FSCALE; + /* TODO: vsize, rss, total_cpu_time */ + } + } } +/* empty stubs so conky links */ +void prepare_update() {} + int get_entropy_avail(unsigned int *val) { return 1; } int get_entropy_poolsize(unsigned int *val) { return 1; } +WRITE] / 512); +for (cur = stats.next; cur; cur = cur->next) { + if (cur->dev && !strcmp(device_name, cur->dev)) { + update_diskio_values(cur, reads, writes); + break; + } +} +} +update_diskio_values(&stats, total_reads, total_writes); + +free(dev_select); +} + +if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); } +free(statinfo_cur.dinfo); +return 0; +} + +/* While topless is obviously better, top is also not bad. */ + +void get_top_info(void) { + struct kinfo_proc *p; + struct process *proc; + int n_processes; + int i; + + std::lock_guard guard(kvm_proc_mutex); + p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) { + proc = get_process(p[i].ki_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; + proc->vsize = p[i].ki_size; + proc->rss = (p[i].ki_rssize * getpagesize()); + /* ki_runtime is in microseconds, total_cpu_time in centiseconds. + * Therefore we divide by 10000. */ + proc->total_cpu_time = p[i].ki_runtime / 10000; + } + } +} + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("remaining", buffer, 9)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 9, n - 9); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} +et_apm_adapter(void) { + int fd; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + switch (a_info.ai_acline) { + case 0: + strncpy(out, "off-line", 16); + return out; + break; + case 1: + if (a_info.ai_batt_stat == 3) { + strncpy(out, "charging", 16); + return out; + } else { + strncpy(out, "on-line", 16); + return out; + } + break; + default: + strncpy(out, "unknown", 16); + return out; + break; + } +} + +char *get_apm_battery_life(void) { + int fd; + u_int batt_life; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_life = a_info.ai_batt_life; + if (batt_life == APM_UNKNOWN) { + strncpy(out, "unknown", 16); + } else if (batt_life <= 100) { + snprintf(out, 16, "%d%%", batt_life); + return out; + } else { + strncpy(out, "ERR", 16); + } + + return out; +} + +char *get_apm_battery_time(void) { + int fd; + int batt_time; + int h, m, s; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_time = a_info.ai_batt_time; + + if (batt_time == -1) { + strncpy(out, "unknown", 16); + } else { + h = batt_time; + s = h % 60; + h /= 60; + m = h % 60; + h /= 60; + snprintf(out, 16, "%2d:%02d:%02d", h, m, s); + } + + return out; +} + +#endif + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'A'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + stat_fp) == nullptr) { break; } + + // Do some parsing here to handle skipped cpu numbers. For example, + // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports + // "0,3-7". I assume that chip is really an 8-core die with two cores + // disabled... Presumably you could also get "0,3-4,6", and other + // combos too... + for (str1 = buf;; str1 = nullptr) { + token = strtok_r(str1, ",", &saveptr1); + if (token == nullptr) break; + ++info.cpu_count; + + subtoken1 = -1; + subtoken2 = -1; + for (str2 = token;; str2 = nullptr) { + subtoken = strtok_r(str2, "-", &saveptr2); + if (subtoken == nullptr) break; + if (subtoken1 < 0) + subtoken1 = atoi(subtoken); + else + subtoken2 = atoi(subtoken); + } + if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; + } + } + info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + + fclose(stat_fp); + } + +#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" +#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" + + int update_stat(void) { + FILE *stat_fp; + static int rep = 0; + static struct cpu_info *cpu = nullptr; + char buf[256]; + int i; + unsigned int idx; + double curtmp; + const char *stat_template = nullptr; + unsigned int malloc_cpu_size = 0; + extern void *global_cpu; + + static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; + static double last_stat_update = 0.0; + float cur_total = 0.0; + + /* since we use wrappers for this function, the update machinery + * can't eliminate double invocations of this function. Check for + * them here, otherwise cpu_usage counters are freaking out. */ + pthread_mutex_lock(&last_stat_update_mutex); + if (last_stat_update == current_update_time) { + pthread_mutex_unlock(&last_stat_update_mutex); + return 0; + } + last_stat_update = current_update_time; + pthread_mutex_unlock(&last_stat_update_mutex); + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if (!cpu_setup || !info.cpu_usage) { + get_cpu_count(); + cpu_setup = 1; + } + + if (!stat_template) { + stat_template = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + } + + if (!global_cpu) { + malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); + cpu = (struct cpu_info *)malloc(malloc_cpu_size); + memset(cpu, 0, malloc_cpu_size); + global_cpu = cpu; + } + + if (!(stat_fp = open_file("/proc/stat", &rep))) { + info.run_threads = 0; + if (info.cpu_usage) { + memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); + } + return 0; + } + + idx = 0; + while (!feof(stat_fp)) { + if (fgets(buf, 255, stat_fp) == nullptr) { break; } + + if (strncmp(buf, "procs_running ", 14) == 0) { + sscanf(buf, "%*s %hu", &info.run_threads); + } else if (strncmp(buf, "cpu", 3) == 0) { + double delta; + if (isdigit((unsigned char)buf[3])) { + idx++; // just increment here since the CPU index can skip numbers + } else { + idx = 0; + } + if (idx > info.cpu_count) { continue; } + sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), + &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), + &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), + &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); + + cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + + cpu[idx].cpu_system + cpu[idx].cpu_idle + + cpu[idx].cpu_iowait + cpu[idx].cpu_irq + + cpu[idx].cpu_softirq + cpu[idx].cpu_steal; + + cpu[idx].cpu_active_total = + cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); + + delta = current_update_time - last_update_time; + + if (delta <= 0.001) { break; } + + cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); + if (cur_total == 0.0) { + cpu[idx].cpu_val[0] = 1.0; + } else { + cpu[idx].cpu_val[0] = + (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / + cur_total; + } + curtmp = 0; + + int samples = cpu_avg_samples.get(*state); +#ifdef HAVE_OPENMP +#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } + info.cpu_usage[idx] = curtmp / samples; + + cpu[idx].cpu_last_total = cpu[idx].cpu_total; + cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = samples - 1; i > 0; i--) { + cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; + } + } + } + fclose(stat_fp); + return 0; + } + + int update_running_processes(void) { + update_stat(); + return 0; + } + + int update_cpu_usage(void) { + update_stat(); + return 0; + } + + void free_cpu(struct text_object *) { /* not used */ } + + // fscanf() that reads floats with points even if you are using a locale where + // floats are with commas + int fscanf_no_i18n(FILE *stream, const char *format, ...) { + int returncode; + va_list ap; + +#ifdef BUILD_I18N + const char *oldlocale = setlocale(LC_NUMERIC, nullptr); + + setlocale(LC_NUMERIC, "C"); +#endif + va_start(ap, format); + returncode = vfscanf(stream, format, ap); + va_end(ap); +#ifdef BUILD_I18N + setlocale(LC_NUMERIC, oldlocale); +#endif + return returncode; + } + + int update_load_average(void) { +#ifdef HAVE_GETLOADAVG + if (!prefer_proc) { + double v[3]; + + getloadavg(v, 3); + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; + } else +#endif + { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file("/proc/loadavg", &rep))) { + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + return 0; + } + if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], + &info.loadavg[2]) < 0) + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + fclose(fp); + } + return 0; + } + + /***********************************************************/ + /***********************************************************/ + /***********************************************************/ + + static int no_dots(const struct dirent *d) { + if (d->d_name[0] == '.') { return 0; } + return 1; + } + + static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { + struct dirent **namelist; + int i, n; + + n = scandir(dir, &namelist, no_dots, alphasort); + if (n < 0) { + if (!rep || !*rep) { + NORM_ERR("scandir for %s: %s", dir, strerror(errno)); + if (rep) { *rep = 1; } + } + return 0; + } else { + if (n == 0) { return 0; } + + strncpy(s, namelist[0]->d_name, 255); + s[255] = '\0'; + +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < n; i++) { free(namelist[i]); } + free(namelist); + + return 1; + } + } + + static int open_sysfs_sensor(const char *dir, const char *dev, + const char *type, int n, int *divisor, + char *devtype) { + char path[256]; + char buf[256]; + int fd; + int divfd; + + memset(buf, 0, sizeof(buf)); + + /* if device is nullptr or *, get first */ + if (dev == nullptr || strcmp(dev, "*") == 0) { + static int rep = 0; + + if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } + dev = buf; + } + + if (strcmp(dir, "/sys/class/hwmon/") == 0) { + if (*buf) { + /* buf holds result from get_first_file_in_a_directory() above, + * e.g. "hwmon0" -- append "/device" */ + strncat(buf, "/device", 256); + } else { + /* dev holds device number N as a string, + * e.g. "0", -- convert to "hwmon0/device" */ + sprintf(buf, "hwmon%s/device", dev); + dev = buf; + } + } + + /* change vol to in, tempf to temp */ + if (strcmp(type, "vol") == 0) { + type = "in"; + } else if (strcmp(type, "tempf") == 0) { + type = "temp"; + } else if (strcmp(type, "temp2") == 0) { + type = "temp"; + } + + /* construct path */ + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + + /* first, attempt to open file in /device */ + fd = open(path, O_RDONLY); + if (fd < 0) { + /* if it fails, strip the /device from dev and attempt again */ + buf[strlen(buf) - 7] = 0; + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + fd = open(path, O_RDONLY); + if (fd < 0) { + NORM_ERR( + "can't open '%s': %s\nplease check your device or remove this " + "var from " PACKAGE_NAME, + path, strerror(errno)); + } + } + + strncpy(devtype, path, 255); + + if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || + strcmp(type, "tempf") == 0) { + *divisor = 1; + } else { + *divisor = 0; + } + /* fan does not use *_div as a read divisor */ + if (strcmp("fan", type) == 0) { return fd; } + + /* test if *_div file exist, open it and use it as divisor */ + if (strcmp(type, "tempf") == 0) { + snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + } else { + snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + } + + divfd = open(path, O_RDONLY); + if (divfd > 0) { + /* read integer */ + char divbuf[64]; + int divn; + + divn = read(divfd, divbuf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (divn < 0) { + NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); + } else { + divbuf[divn] = '\0'; + *divisor = atoi(divbuf); + } + close(divfd); + } + + return fd; + } + + static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { + int val = 0; + + if (*fd <= 0) { return 0; } + + lseek(*fd, 0, SEEK_SET); + + /* read integer */ + { + char buf[64]; + int n; + n = read(*fd, buf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (n < 0) { + NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); + } else { + buf[n] = '\0'; + val = atoi(buf); + } + } + + close(*fd); + /* open file */ + *fd = open(devtype, O_RDONLY); + if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } + + /* My dirty hack for computing CPU value + * Filedil, from forums.gentoo.org */ + /* if (strstr(devtype, "temp1_input") != nullptr) { + return -15.096 + 1.4893 * (val / 1000.0); + } */ + + /* divide voltage and temperature by 1000 */ + /* or if any other divisor is given, use that */ + if (0 == (strcmp(type, "temp2"))) { + temp2 = "temp2"; + } else { + temp2 = "empty"; + } + if (strcmp(type, "tempf") == 0) { + if (divisor > 1) { + return ((val / divisor + 40) * 9.0 / 5) - 40; + } else if (divisor) { + return ((val / 1000.0 + 40) * 9.0 / 5) - 40; + } else { + return ((val + 40) * 9.0 / 5) - 40; + } + } else { + if (divisor > 1) { + return val / divisor; + } else if (divisor) { + return val / 1000.0; + } else { + return val; + } + } + } + +#define HWMON_RESET() \ + { \ + buf1[0] = 0; \ + factor = 1.0; \ + offset = 0.0; \ + } + + static void parse_sysfs_sensor(struct text_object *obj, const char *arg, + const char *path, const char *type) { + char buf1[64], buf2[64]; + float factor, offset; + int n, found = 0; + struct sysfs *sf; + + if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) + found = 1; + else + HWMON_RESET(); + if (!found && + sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) + found = 1; + else if (!found) + HWMON_RESET(); + + if (!found) { + obj_be_plain_text(obj, "fail"); + return; + } + DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, + offset); + sf = (struct sysfs *)malloc(sizeof(struct sysfs)); + memset(sf, 0, sizeof(struct sysfs)); + sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, + sf->devtype); + strncpy(sf->type, buf2, 63); + sf->factor = factor; + sf->offset = offset; + obj->data.opaque = sf; + } + +#define PARSER_GENERATOR(name, path) \ + void parse_##name##_sensor(struct text_object *obj, const char *arg) { \ + parse_sysfs_sensor(obj, arg, path, #name); \ + } + + PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") + PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") + PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") + + void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { + double r; + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf || sf->fd < 0) return; + + r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); + + r = r * sf->factor + sf->offset; + + if (0 == (strcmp(temp2, "temp2"))) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); + } else if (!strncmp(sf->type, "temp", 4)) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); + } else if (r >= 100.0 || r == 0) { + snprintf(p, p_max_size, "%d", (int)r); + } else { + snprintf(p, p_max_size, "%.1f", r); + } + } + + void free_sysfs_sensor(struct text_object *obj) { + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf) return; + + if (sf->fd >= 0) close(sf->fd); + free_and_zero(obj->data.opaque); + } + +#define CPUFREQ_PREFIX "/sys/devices/system/cpu" +#define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq" + + /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ + char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + static int rep = 0; + char frequency[32]; + char s[256]; + double freq = 0; + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + if (!prefer_proc) { + char current_freq_file[128]; + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, + CPUFREQ_POSTFIX); + f = fopen(current_freq_file, "r"); + if (f) { + /* if there's a cpufreq /sys node, read the current frequency from + * this node and divide by 1000 to get Mhz. */ + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (freq / 1000) / divisor); + return 1; + } + } + + // open the CPU information file + f = open_file("/proc/cpuinfo", &rep); + if (!f) { + perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); + return 0; + } + + // read the file + while (fgets(s, sizeof(s), f) != nullptr) { +#if defined(__i386) || defined(__x86_64) + // and search for the cpu mhz + if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { +#else +#if defined(__alpha) + // different on alpha + if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { +#else + // this is different on ppc for some reason + if (strncmp(s, "clock", 5) == 0 && cpu == 0) { +#endif // defined(__alpha) +#endif // defined(__i386) || defined(__x86_64) + + // copy just the number + strncpy(frequency, strchr(s, ':') + 2, 32); +#if defined(__alpha) + // strip " est.\n" + frequency[strlen(frequency) - 6] = '\0'; + // kernel reports in Hz + freq = strtod(frequency, nullptr) / 1000000; +#else + // strip \n + frequency[strlen(frequency) - 1] = '\0'; + freq = strtod(frequency, nullptr); +#endif + break; + } + if (strncmp(s, "processor", 9) == 0) { + cpu--; + continue; + } + } + + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + return 1; + } + +#define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages" + + /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something + * like this: + # frequency voltage + 1800000 1340 + 1600000 1292 + 1400000 1100 + 1200000 988 + 1000000 1116 + 800000 1004 + 600000 988 + * Peter Tarjan (ptarjan@citromail.hu) */ + + /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ + static char get_voltage(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + char s[256]; + int freq = 0; + int voltage = 0; + char current_freq_file[128]; + int freq_comp = 0; + + /* build the voltage file name */ + cpu--; + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_POSTFIX); + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + /* read the current cpu frequency from the /sys node */ + f = fopen(current_freq_file, "r"); + if (f) { + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_VOLTAGE); + + /* use the current cpu frequency to find the corresponding voltage */ + f = fopen(current_freq_file, "r"); + + if (f) { + while (!feof(f)) { + char line[256]; + + if (fgets(line, 255, f) == nullptr) { break; } + sscanf(line, "%d %d", &freq_comp, &voltage); + if (freq_comp == freq) { break; } + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)voltage / divisor); + return 1; + } + + void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } + } + + void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } + } + +#define ACPI_FAN_DIR "/proc/acpi/fan/" + + void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { + static int rep = 0; + char buf[256]; + char buf2[256]; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "can't open fan's state file"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + +#define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply" +#define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/" + /* Linux 2.6.25 onwards ac adapter info is in + /sys/class/power_supply/AC/ + On my system I get the following. + /sys/class/power_supply/AC/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=ac + POWER_SUPPLY_NAME=AC + POWER_SUPPLY_TYPE=Mains + POWER_SUPPLY_ONLINE=1 + + Update: it seems the folder name is hardware-dependent. We add an aditional + adapter argument, specifying the folder name. + + Update: on some systems it's /sys/class/power_supply/ADP1 instead of + /sys/class/power_supply/AC + */ + + void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, + const char *adapter) { + static int rep = 0; + + char buf[256]; + char buf2[256]; + struct stat sb; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + if (adapter) + snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, + adapter); + else { + snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); + if (stat(buf2, &sb) == -1) + snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); + } + if (stat(buf2, &sb) == 0) + fp = open_file(buf2, &rep); + else + fp = 0; + if (fp) { + /* sysfs processing */ + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { + int online = 0; + sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); + snprintf(p_client_buffer, client_buffer_size, "%s-line", + (online ? "on" : "off")); + break; + } + } + fclose(fp); + } else { + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "No ac adapter found.... where is it?"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + } + + /* + /proc/acpi/thermal_zone/THRM/cooling_mode + cooling mode: active + /proc/acpi/thermal_zone/THRM/polling_frequency + + /proc/acpi/thermal_zone/THRM/state + state: ok + /proc/acpi/thermal_zone/THRM/temperature + temperature: 45 C + /proc/acpi/thermal_zone/THRM/trip_points + critical (S5): 73 C + passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 + */ + +#define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0" +#define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp" + + int open_acpi_temperature(const char *name) { + char path[256]; + int fd; + + if (name == nullptr || strcmp(name, "*") == 0) { + snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); + } else { + snprintf(path, 255, ACPI_THERMAL_FORMAT, name); + } + + fd = open(path, O_RDONLY); + if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } + + return fd; + } + + static double last_acpi_temp; + static double last_acpi_temp_time; + + // the maximum length of the string inside a ACPI_THERMAL_FORMAT file including + // the ending 0 +#define MAXTHERMZONELEN 6 + + double get_acpi_temperature(int fd) { + if (fd <= 0) { return 0; } + + /* don't update acpi temperature too often */ + if (current_update_time - last_acpi_temp_time < 11.32) { + return last_acpi_temp; + } + last_acpi_temp_time = current_update_time; + + /* seek to beginning */ + lseek(fd, 0, SEEK_SET); + + /* read */ + { + char buf[MAXTHERMZONELEN]; + int n; + + n = read(fd, buf, MAXTHERMZONELEN - 1); + if (n < 0) { + NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); + } else { + buf[n] = '\0'; + sscanf(buf, "%lf", &last_acpi_temp); + last_acpi_temp /= 1000; + } + } + + return last_acpi_temp; + } + + /* + hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info + present: yes + design capacity: 4400 mAh + last full capacity: 4064 mAh + battery technology: rechargeable + design voltage: 14800 mV + design capacity warning: 300 mAh + design capacity low: 200 mAh + capacity granularity 1: 32 mAh + capacity granularity 2: 32 mAh + model number: 02KT + serial number: 16922 + battery type: LION + OEM info: SANYO + */ + + /* + hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state + present: yes + capacity state: ok + charging state: unknown + present rate: 0 mA + remaining capacity: 4064 mAh + present voltage: 16608 mV + */ + + /* + 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? + 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) + 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? + + 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman + verkkovirtaa 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? + verkkovirralla + + 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja + monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? + monitori p��ll� mutta ilman verkkovirtaa + */ + + /* Kapil Hari Paranjape + Linux 2.6.24 onwards battery info is in + /sys/class/power_supply/BAT0/ + On my system I get the following. + /sys/class/power_supply/BAT0/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=battery + POWER_SUPPLY_NAME=BAT0 + POWER_SUPPLY_TYPE=Battery + POWER_SUPPLY_STATUS=Discharging + POWER_SUPPLY_PRESENT=1 + POWER_SUPPLY_TECHNOLOGY=Li-ion + POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 + POWER_SUPPLY_VOLTAGE_NOW=10780000 + POWER_SUPPLY_CURRENT_NOW=13970000 + POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 + POWER_SUPPLY_ENERGY_FULL=27370000 + POWER_SUPPLY_ENERGY_NOW=11810000 + POWER_SUPPLY_MODEL_NAME=IBM-92P1060 + POWER_SUPPLY_MANUFACTURER=Panasonic + On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* + */ + + /* Tiago Marques Vale + Regarding the comment above, since kernel 2.6.36.1 I have + POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW + See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 + */ + +#define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply" +#define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" +#define APM_PATH "/proc/apm" +#define MAX_BATTERY_COUNT 4 + + static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + + static int batteries_initialized = 0; + static char batteries[MAX_BATTERY_COUNT][32]; + + static int acpi_last_full[MAX_BATTERY_COUNT]; + static int acpi_design_capacity[MAX_BATTERY_COUNT]; + + /* e.g. "charging 75%" */ + static char last_battery_str[MAX_BATTERY_COUNT][64]; + /* e.g. "3h 15m" */ + static char last_battery_time_str[MAX_BATTERY_COUNT][64]; + + static double last_battery_time[MAX_BATTERY_COUNT]; + + static int last_battery_perct[MAX_BATTERY_COUNT]; + static double last_battery_perct_time[MAX_BATTERY_COUNT]; + + void init_batteries(void) { + int idx; + + if (batteries_initialized) { return; } +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } + batteries_initialized = 1; + } + + int get_battery_idx(const char *bat) { + int idx; + + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } + } + + /* if not found, enter a new entry */ + if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } + + return idx; + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx); + + void get_battery_stuff(char *buffer, unsigned int n, const char *bat, + int item) { + static int idx, rep = 0, rep1 = 0, rep2 = 0; + char acpi_path[128]; + char sysfs_path[128]; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + init_batteries(); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_time[idx] < 29.5) { + set_return_value(buffer, n, item, idx); + return; + } + + last_battery_time[idx] = current_update_time; + + memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); + memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); + + /* first try SYSFS if that fails try ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep1); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[4]; + + strncpy(charging_state, "unknown", 64); + + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + /* let's just hope units are ok */ + if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) + strncpy(present, "yes", 4); + else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) + strncpy(present, "no", 4); + else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) + sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); + /* present_rate is not the same as the current flowing now but it + * is the same value which was used in the past. so we continue the + * tradition! */ + else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) + sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) + acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ + + /* not present */ + if (strcmp(present, "No") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + } + /* charging */ + else if (strcmp(charging_state, "Charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)(acpi_last_full[idx] - remaining_capacity) / + present_rate) * + 3600)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* discharging */ + else if (strncmp(charging_state, "Discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 1h 12m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)remaining_capacity / present_rate) * 3600)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "full"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* charged */ + /* thanks to Lukas Zapletal */ + else if (strncmp(charging_state, "Charged", 64) == 0 || + strncmp(charging_state, "Full", 64) == 0) { + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one + * being charged. */ + if (remaining_capacity == 0) + strncpy(last_battery_str[idx], "empty", 64); + else + strncpy(last_battery_str[idx], "charged", 64); + } + /* unknown, probably full / AC */ + else { + if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) + snprintf( + last_battery_str[idx], 64, "unknown %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + else + strncpy(last_battery_str[idx], "not present", 64); + } + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[5]; + + /* read last full capacity if it's zero */ + if (acpi_last_full[idx] == 0) { + static int rep3 = 0; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep3); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { + break; + } + } + + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + strncpy(charging_state, "unknown", 8); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + /* let's just hope units are ok */ + if (strncmp(buf, "present:", 8) == 0) { + sscanf(buf, "present: %4s", present); + } else if (strncmp(buf, "charging state:", 15) == 0) { + sscanf(buf, "charging state: %63s", charging_state); + } else if (strncmp(buf, "present rate:", 13) == 0) { + sscanf(buf, "present rate: %d", &present_rate); + } else if (strncmp(buf, "remaining capacity:", 19) == 0) { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) { + /* normalize to 100% */ + acpi_last_full[idx] = remaining_capacity; + } + + /* not present */ + if (strcmp(present, "no") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + /* charging */ + } else if (strcmp(charging_state, "charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / + present_rate)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* discharging */ + } else if (strncmp(charging_state, "discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 1h 12m */ + format_seconds(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, + (long)((remaining_capacity * 3600) / present_rate)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charged"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* charged */ + } else if (strncmp(charging_state, "charged", 64) == 0) { + /* thanks to Lukas Zapletal */ + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one being charged. */ + if (remaining_capacity == 0) { + strncpy(last_battery_str[idx], "empty", 6); + } else { + strncpy(last_battery_str[idx], "charged", 8); + } + /* unknown, probably full / AC */ + } else { + if (strncmp(charging_state, "Full", 64) == 0) { + strncpy(last_battery_str[idx], "charged", 64); + } else if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) { + snprintf(last_battery_str[idx], 64, "unknown %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + } else { + strncpy(last_battery_str[idx], "not present", 64); + } + } + fclose(acpi_bat_fp[idx]); + acpi_bat_fp[idx] = nullptr; + } else { + /* APM */ + if (apm_bat_fp[idx] == nullptr) { + apm_bat_fp[idx] = open_file(APM_PATH, &rep2); + } + + if (apm_bat_fp[idx] != nullptr) { + unsigned int ac, status, flag; + int life; + + if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, + &status, &flag, &life) <= 0) + goto read_bat_fp_end; + + if (life == -1) { + /* could check now that there is ac */ + snprintf(last_battery_str[idx], 64, "%s", "not present"); + + /* could check that status == 3 here? */ + } else if (ac && life != 100) { + snprintf(last_battery_str[idx], 64, "charging %d%%", life); + } else { + snprintf(last_battery_str[idx], 64, "%d%%", life); + } + + read_bat_fp_end: + /* it seemed to buffer it so file must be closed (or could use + * syscalls directly but I don't feel like coding it now) */ + fclose(apm_bat_fp[idx]); + apm_bat_fp[idx] = nullptr; + } + } + set_return_value(buffer, n, item, idx); + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx) { + switch (item) { + case BATTERY_STATUS: + snprintf(buffer, n, "%s", last_battery_str[idx]); + break; + case BATTERY_TIME: + snprintf(buffer, n, "%s", last_battery_time_str[idx]); + break; + default: + break; + } + } + + void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("not present", buffer, 11)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("empty", buffer, 5)) { + buffer[0] = 'E'; + memmove(buffer + 1, buffer + 5, n - 5); + } else if (0 == strncmp("unknown", buffer, 7)) { + buffer[0] = 'U'; + memmove(buffer + 1, buffer + 7, n - 7); + } + // Otherwise, don't shorten. + } + + int _get_battery_perct(const char *bat) { + static int rep = 0; + int idx; + char acpi_path[128]; + char sysfs_path[128]; + int remaining_capacity = -1; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_perct_time[idx] < 30) { + return last_battery_perct[idx]; + } + last_battery_perct_time[idx] = current_update_time; + + /* Only check for SYSFS or ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + rep = 0; + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); + } + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + /* read last full capacity if it's zero */ + if (acpi_design_capacity[idx] == 0) { + static int rep2; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep2); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", + &acpi_design_capacity[idx]) != 0) { + break; + } + } + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + if (buf[0] == 'r') { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + } + if (remaining_capacity < 0) { return 0; } + /* compute the battery percentage */ + last_battery_perct[idx] = + (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); + if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; + return last_battery_perct[idx]; + } + + int get_battery_perct(const char *bat) { + int idx, n = 0, total_capacity = 0, remaining_capacity; + ; +#define BATTERY_LEN 8 + char battery[BATTERY_LEN]; + + init_batteries(); + + /* Check if user asked for the mean percentage of all batteries. */ + if (!strcmp(bat, "all")) { + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); +#undef BATTERY_LEN + remaining_capacity = _get_battery_perct(battery); + if (remaining_capacity > 0) { + total_capacity += remaining_capacity; + n++; + } + } + + if (n == 0) + return 0; + else + return total_capacity / n; + } else { + return _get_battery_perct(bat); + } + } + + double get_battery_perct_bar(struct text_object *obj) { + int idx; + + get_battery_perct(obj->data.s); + idx = get_battery_idx(obj->data.s); + return last_battery_perct[idx]; + } + + /* On Apple powerbook and ibook: + $ cat /proc/pmu/battery_0 + flags : 00000013 + charge : 3623 + max_charge : 3720 + current : 388 + voltage : 16787 + time rem. : 900 + $ cat /proc/pmu/info + PMU driver version : 2 + PMU firmware version : 0c + AC Power : 1 + Battery count : 1 + */ + + /* defines as in */ +#define PMU_BATT_PRESENT 0x00000001 +#define PMU_BATT_CHARGING 0x00000002 + + static FILE *pmu_battery_fp; + static FILE *pmu_info_fp; + static char pb_battery_info[3][32]; + static double pb_battery_info_update; + +#define PMU_PATH "/proc/pmu" + void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { + static int rep = 0; + const char *batt_path = PMU_PATH "/battery_0"; + const char *info_path = PMU_PATH "/info"; + unsigned int flags = 0; + int charge = 0; + int max_charge = 1; + int ac = -1; + long timeval = -1; + + /* don't update battery too often */ + if (current_update_time - pb_battery_info_update < 29.5) { + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + return; + } + pb_battery_info_update = current_update_time; + + if (pmu_battery_fp == nullptr) { + pmu_battery_fp = open_file(batt_path, &rep); + if (pmu_battery_fp == nullptr) { return; } + } + + if (pmu_battery_fp != nullptr) { + rewind(pmu_battery_fp); + while (!feof(pmu_battery_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } + + if (buf[0] == 'f') { + sscanf(buf, "flags : %8x", &flags); + } else if (buf[0] == 'c' && buf[1] == 'h') { + sscanf(buf, "charge : %d", &charge); + } else if (buf[0] == 'm') { + sscanf(buf, "max_charge : %d", &max_charge); + } else if (buf[0] == 't') { + sscanf(buf, "time rem. : %ld", &timeval); + } + } + } + if (pmu_info_fp == nullptr) { + pmu_info_fp = open_file(info_path, &rep); + if (pmu_info_fp == nullptr) { return; } + } + + if (pmu_info_fp != nullptr) { + rewind(pmu_info_fp); + while (!feof(pmu_info_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } + if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } + } + } + /* update status string */ + if ((ac && !(flags & PMU_BATT_PRESENT))) { + strncpy(pb_battery_info[PB_BATT_STATUS], "AC", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if (ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charged", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else { + strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } + + /* update percentage string */ + if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); + } else if (timeval == 0) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); + } else { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", + (charge * 100) / max_charge); + } + + /* update time string */ + if (timeval == 0) { /* fully charged or battery not present */ + snprintf(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); + } else if (timeval < 60 * 60) { /* don't show secs */ + format_seconds_short(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } else { + format_seconds(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } + + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + } + +#define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail" + + int get_entropy_avail(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + +#define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize" + + int get_entropy_poolsize(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + + void print_disk_protect_queue(struct text_object *obj, char *p, + int p_max_size) { + FILE *fp; + char path[128]; + int state; + + snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); + if (access(path, F_OK)) { + snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); + } + if ((fp = fopen(path, "r")) == nullptr) { + snprintf(p, p_max_size, "%s", "n/a "); + return; + } + if (fscanf(fp, "%d\n", &state) != 1) { + fclose(fp); + snprintf(p, p_max_size, "%s", "failed"); + return; + } + fclose(fp); + snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); + } + + std::unordered_map dev_list; + + /* Same as sf #2942117 but memoized using a linked list */ + int is_disk(char *dev) { + std::string orig(dev); + std::string syspath("/sys/block/"); + char *slash; + + auto i = dev_list.find(orig); + if (i != dev_list.end()) return i->second; + + while ((slash = strchr(dev, '/'))) *slash = '!'; + syspath += dev; + + return dev_list[orig] = !(access(syspath.c_str(), F_OK)); + } + + int update_diskio(void) { + FILE *fp; + static int rep = 0; + char buf[512], devbuf[64]; + unsigned int major, minor; + int col_count = 0; + struct diskio_stat *cur; + unsigned int reads, writes; + unsigned int total_reads = 0, total_writes = 0; + + stats.current = 0; + stats.current_read = 0; + stats.current_write = 0; + + if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } + + /* read reads and writes from all disks (minor = 0), including cd-roms + * and floppies, and sum them up */ + while (fgets(buf, 512, fp)) { + col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, + &minor, devbuf, &reads, &writes); + /* ignore subdevices (they have only 3 matching entries in their line) + * and virtual devices (LVM, network block devices, RAM disks, Loopback) + * + * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ + if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && + major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { + /* check needed for kernel >= 2.6.31, see sf #2942117 */ + if (is_disk(devbuf)) { + total_reads += reads; + total_writes += writes; + } + } else { + col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, + &reads, &writes); + if (col_count != 5) { continue; } + } + cur = stats.next; + while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; + + if (cur) update_diskio_values(cur, reads, writes); + } + update_diskio_values(&stats, total_reads, total_writes); + fclose(fp); + return 0; + } + + void print_distribution(struct text_object *obj, char *p, int p_max_size) { + (void)obj; + int i, bytes_read; + char *buf; + struct stat sb; + + if (stat("/etc/arch-release", &sb) == 0) { + snprintf(p, p_max_size, "%s", "Arch Linux"); + return; + } + snprintf(p, p_max_size, "Unknown"); + buf = readfile("/proc/version", &bytes_read, 1); + if (buf) { + /* I am assuming the distribution name is the first string in /proc/version + that: + - is preceded by a '(' + - starts with a capital + - is followed by a space and a number + but i am not sure if this is always true... */ + for (i = 1; i < bytes_read; i++) { + if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; + } + if (i < bytes_read) { + snprintf(p, p_max_size, "%s", &buf[i]); + for (i = 1; p[i]; i++) { + if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { + p[i - 1] = 0; + break; + } + } + } + free(buf); + } + } + + /****************************************** + * Calculate cpu total * + ******************************************/ +#define TMPL_SHORTPROC "%*s %llu %llu %llu %llu" +#define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu" + + static unsigned long long calc_cpu_total(void) { + static unsigned long long previous_total = 0; + unsigned long long total = 0; + unsigned long long t = 0; + int rc; + int ps; + char line[BUFFER_LEN] = {0}; + unsigned long long cpu = 0; + unsigned long long niceval = 0; + unsigned long long systemval = 0; + unsigned long long idle = 0; + unsigned long long iowait = 0; + unsigned long long irq = 0; + unsigned long long softirq = 0; + unsigned long long steal = 0; + const char *template_ = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; + + ps = open("/proc/stat", O_RDONLY); + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return 0; } + + sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, + &softirq, &steal); + total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; + + t = total - previous_total; + previous_total = total; + + return t; + } + + /****************************************** + * Calculate each processes cpu * + ******************************************/ + + inline static void calc_cpu_each(unsigned long long total) { + float mul = 100.0; + if (top_cpu_separate.get(*state)) mul *= info.cpu_count; + + for (struct process *p = first_process; p; p = p->next) + p->amount = mul * (p->user_time + p->kernel_time) / (float)total; + } + +#ifdef BUILD_IOSTATS + static void calc_io_each(void) { + struct process *p; + unsigned long long sum = 0; + + for (p = first_process; p; p = p->next) + sum += p->read_bytes + p->write_bytes; + + if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ + for (p = first_process; p; p = p->next) + p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Extract information from /proc * + ******************************************/ + +#define PROCFS_TEMPLATE "/proc/%d/stat" +#define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline" + + /* These are the guts that extract information out of /proc. + * Anyone hoping to port wmtop should look here first. */ + static void process_parse_stat(struct process *process) { + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; + char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], + cmdline_procname[BUFFER_LEN]; + char basename[BUFFER_LEN] = {0}; + char tmpstr[BUFFER_LEN] = {0}; + char state[4]; + int ps, cmdline_ps; + unsigned long user_time = 0; + unsigned long kernel_time = 0; + int rc; + char *r, *q; + int endl; + int nice_val; + char *lparen, *rparen; + struct stat process_stat; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); + snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, + process->pid); + + ps = open(filename, O_RDONLY); + if (ps == -1) { + /* The process must have finished in the last few jiffies! */ + return; + } + + if (fstat(ps, &process_stat) != 0) { + close(ps); + return; + } + process->uid = process_stat.st_uid; + + /* Mark process as up-to-date. */ + process->time_stamp = g_time; + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + /* Read /proc//cmdline */ + cmdline_ps = open(cmdline_filename, O_RDONLY); + if (cmdline_ps < 0) { + /* The process must have finished in the last few jiffies! */ + return; + } + + endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); + close(cmdline_ps); + if (endl < 0) { return; } + + /* Some processes have null-separated arguments (see proc(5)); let's fix it + */ + int i = endl; + while (i && cmdline[i - 1] == 0) { + /* Skip past any trailing null characters */ + --i; + } + while (i--) { + /* Replace null character between arguments with a space */ + if (cmdline[i] == 0) { cmdline[i] = ' '; } + } + + cmdline[endl] = 0; + + /* We want to transform for example "/usr/bin/python program.py" to "python + * program.py" + * 1. search for first space + * 2. search for last / before first space + * 3. copy string from its position + */ + char *space_ptr = strchr(cmdline, ' '); + if (space_ptr == nullptr) { + strncpy(tmpstr, cmdline, BUFFER_LEN); + } else { + long int space_pos = space_ptr - cmdline; + strncpy(tmpstr, cmdline, space_pos); + tmpstr[space_pos] = 0; + } + + char *slash_ptr = strrchr(tmpstr, '/'); + if (slash_ptr == nullptr) { + strncpy(cmdline_procname, cmdline, BUFFER_LEN); + } else { + long int slash_pos = slash_ptr - tmpstr; + strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); + cmdline_procname[BUFFER_LEN - slash_pos] = 0; + } + + /* Extract cpu times from data in /proc filesystem */ + lparen = strchr(line, '('); + rparen = strrchr(line, ')'); + if (!lparen || !rparen || rparen < lparen) return; // this should not happen + + rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); + strncpy(procname, lparen + 1, rc); + procname[rc] = '\0'; + strncpy(basename, procname, strlen(procname) + 1); + + if (strlen(procname) < strlen(cmdline_procname)) + strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); + + rc = sscanf(rparen + 1, + "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " + "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", + state, &process->user_time, &process->kernel_time, &nice_val, + &process->vsize, &process->rss); + if (rc < 6) { + NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); + return; + } + + if (state[0] == 'R') ++info.run_procs; + + free_and_zero(process->name); + free_and_zero(process->basename); + process->name = strndup(procname, text_buffer_size.get(*::state)); + process->basename = strndup(basename, text_buffer_size.get(*::state)); + process->rss *= getpagesize(); + + process->total_cpu_time = process->user_time + process->kernel_time; + if (process->previous_user_time == ULONG_MAX) { + process->previous_user_time = process->user_time; + } + if (process->previous_kernel_time == ULONG_MAX) { + process->previous_kernel_time = process->kernel_time; + } + + /* strangely, the values aren't monotonous */ + if (process->previous_user_time > process->user_time) + process->previous_user_time = process->user_time; + + if (process->previous_kernel_time > process->kernel_time) + process->previous_kernel_time = process->kernel_time; + + /* store the difference of the user_time */ + user_time = process->user_time - process->previous_user_time; + kernel_time = process->kernel_time - process->previous_kernel_time; + + /* backup the process->user_time for next time around */ + process->previous_user_time = process->user_time; + process->previous_kernel_time = process->kernel_time; + + /* store only the difference of the user_time here... */ + process->user_time = user_time; + process->kernel_time = kernel_time; + } + +#ifdef BUILD_IOSTATS +#define PROCFS_TEMPLATE_IO "/proc/%d/io" + static void process_parse_io(struct process *process) { + static const char *read_bytes_str = "read_bytes:"; + static const char *write_bytes_str = "write_bytes:"; + + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; + int ps; + int rc; + char *pos, *endpos; + unsigned long long read_bytes, write_bytes; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); + + ps = open(filename, O_RDONLY); + if (ps < 0) { + /* The process must have finished in the last few jiffies! + * Or, the kernel doesn't support I/O accounting. + */ + return; + } + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + pos = strstr(line, read_bytes_str); + if (pos == nullptr) { + /* these should not happen (unless the format of the file changes) */ + return; + } + pos += strlen(read_bytes_str); + process->read_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + pos = strstr(line, write_bytes_str); + if (pos == nullptr) { return; } + pos += strlen(write_bytes_str); + process->write_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + if (process->previous_read_bytes == ULLONG_MAX) { + process->previous_read_bytes = process->read_bytes; + } + if (process->previous_write_bytes == ULLONG_MAX) { + process->previous_write_bytes = process->write_bytes; + } + + /* store the difference of the byte counts */ + read_bytes = process->read_bytes - process->previous_read_bytes; + write_bytes = process->write_bytes - process->previous_write_bytes; + + /* backup the counts for next time around */ + process->previous_read_bytes = process->read_bytes; + process->previous_write_bytes = process->write_bytes; + + /* store only the difference here... */ + process->read_bytes = read_bytes; + process->write_bytes = write_bytes; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Get process structure for process pid * + ******************************************/ + + /* This function seems to hog all of the CPU time. + * I can't figure out why - it doesn't do much. */ + static void calculate_stats(struct process *process) { + /* compute each process cpu usage by reading /proc//stat */ + process_parse_stat(process); + +#ifdef BUILD_IOSTATS + process_parse_io(process); +#endif /* BUILD_IOSTATS */ + + /* + * Check name against the exclusion list + */ + /* if (process->counted && exclusion_expression && + * !regexec(exclusion_expression, process->name, 0, 0, 0)) + * process->counted = 0; */ + } + + /****************************************** + * Update process table * + ******************************************/ + + static void update_process_table(void) { + DIR *dir; + struct dirent *entry; + + if (!(dir = opendir("/proc"))) { return; } + + info.run_procs = 0; + + /* Get list of processes from /proc directory */ + while ((entry = readdir(dir))) { + pid_t pid; + + if (sscanf(entry->d_name, "%d", &pid) > 0) { + /* compute each process cpu usage */ + calculate_stats(get_process(pid)); + } + } + + closedir(dir); + } + + void get_top_info(void) { + unsigned long long total = 0; + + total = calc_cpu_total(); /* calculate the total of the processor */ + update_process_table(); /* update the table with process list */ + calc_cpu_each(total); /* and then the percentage for each task */ +#ifdef BUILD_IOSTATS + calc_io_each(); /* percentage of I/O for each task */ +#endif /* BUILD_IOSTATS */ + } diff --git a/src/openbsd.cc b/src/openbsd.cc index 36568ebb6f..8067f88c47 100644 --- a/src/openbsd.cc +++ b/src/openbsd.cc @@ -400,8 +400,7 @@ void update_cpu_usage() { #endif } -void free_cpu(struct text_object *) { -} +void free_cpu(struct text_object *) { /* not used */ } void update_load_average() { double v[3]; @@ -663,3 +662,2286 @@ void prepare_update() {} int get_entropy_avail(unsigned int *val) { return 1; } int get_entropy_poolsize(unsigned int *val) { return 1; } +WRITE] / 512); +for (cur = stats.next; cur; cur = cur->next) { + if (cur->dev && !strcmp(device_name, cur->dev)) { + update_diskio_values(cur, reads, writes); + break; + } +} +} +update_diskio_values(&stats, total_reads, total_writes); + +free(dev_select); +} + +if (statinfo_cur.dinfo->mem_ptr) { free(statinfo_cur.dinfo->mem_ptr); } +free(statinfo_cur.dinfo); +return 0; +} + +/* While topless is obviously better, top is also not bad. */ + +void get_top_info(void) { + struct kinfo_proc *p; + struct process *proc; + int n_processes; + int i; + + std::lock_guard guard(kvm_proc_mutex); + p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes); + + for (i = 0; i < n_processes; i++) { + if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != nullptr) { + proc = get_process(p[i].ki_pid); + + proc->time_stamp = g_time; + proc->name = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->basename = strndup(p[i].ki_comm, text_buffer_size.get(*state)); + proc->amount = 100.0 * p[i].ki_pctcpu / FSCALE; + proc->vsize = p[i].ki_size; + proc->rss = (p[i].ki_rssize * getpagesize()); + /* ki_runtime is in microseconds, total_cpu_time in centiseconds. + * Therefore we divide by 10000. */ + proc->total_cpu_time = p[i].ki_runtime / 10000; + } + } +} + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("remaining", buffer, 9)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 9, n - 9); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} +et_apm_adapter(void) { + int fd; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + switch (a_info.ai_acline) { + case 0: + strncpy(out, "off-line", 16); + return out; + break; + case 1: + if (a_info.ai_batt_stat == 3) { + strncpy(out, "charging", 16); + return out; + } else { + strncpy(out, "on-line", 16); + return out; + } + break; + default: + strncpy(out, "unknown", 16); + return out; + break; + } +} + +char *get_apm_battery_life(void) { + int fd; + u_int batt_life; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_life = a_info.ai_batt_life; + if (batt_life == APM_UNKNOWN) { + strncpy(out, "unknown", 16); + } else if (batt_life <= 100) { + snprintf(out, 16, "%d%%", batt_life); + return out; + } else { + strncpy(out, "ERR", 16); + } + + return out; +} + +char *get_apm_battery_time(void) { + int fd; + int batt_time; + int h, m, s; + struct apm_info a_info; + char *out; + + out = (char *)calloc(16, sizeof(char)); + + fd = open(APMDEV, O_RDONLY); + if (fd < 0) { + strncpy(out, "ERR", 16); + return out; + } + + if (apm_getinfo(fd, &a_info) != 0) { + close(fd); + strncpy(out, "ERR", 16); + return out; + } + close(fd); + + batt_time = a_info.ai_batt_time; + + if (batt_time == -1) { + strncpy(out, "unknown", 16); + } else { + h = batt_time; + s = h % 60; + h /= 60; + m = h % 60; + h /= 60; + snprintf(out, 16, "%2d:%02d:%02d", h, m, s); + } + + return out; +} + +#endif + +void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("absent/on AC", buffer, 12)) { + buffer[0] = 'A'; + memmove(buffer + 1, buffer + 12, n - 12); + } +} + +int get_entropy_avail(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + +int get_entropy_poolsize(unsigned int *val) { + /* Not applicable for FreeBSD as it uses the yarrow prng. */ + (void)val; + return 1; +} + stat_fp) == nullptr) { break; } + + // Do some parsing here to handle skipped cpu numbers. For example, + // for an AMD FX(tm)-6350 Six-Core Processor /sys/.../present reports + // "0,3-7". I assume that chip is really an 8-core die with two cores + // disabled... Presumably you could also get "0,3-4,6", and other + // combos too... + for (str1 = buf;; str1 = nullptr) { + token = strtok_r(str1, ",", &saveptr1); + if (token == nullptr) break; + ++info.cpu_count; + + subtoken1 = -1; + subtoken2 = -1; + for (str2 = token;; str2 = nullptr) { + subtoken = strtok_r(str2, "-", &saveptr2); + if (subtoken == nullptr) break; + if (subtoken1 < 0) + subtoken1 = atoi(subtoken); + else + subtoken2 = atoi(subtoken); + } + if (subtoken2 > 0) info.cpu_count += subtoken2 - subtoken1; + } + } + info.cpu_usage = (float *)malloc((info.cpu_count + 1) * sizeof(float)); + + fclose(stat_fp); + } + +#define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu" +#define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu" + + int update_stat(void) { + FILE *stat_fp; + static int rep = 0; + static struct cpu_info *cpu = nullptr; + char buf[256]; + int i; + unsigned int idx; + double curtmp; + const char *stat_template = nullptr; + unsigned int malloc_cpu_size = 0; + extern void *global_cpu; + + static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER; + static double last_stat_update = 0.0; + float cur_total = 0.0; + + /* since we use wrappers for this function, the update machinery + * can't eliminate double invocations of this function. Check for + * them here, otherwise cpu_usage counters are freaking out. */ + pthread_mutex_lock(&last_stat_update_mutex); + if (last_stat_update == current_update_time) { + pthread_mutex_unlock(&last_stat_update_mutex); + return 0; + } + last_stat_update = current_update_time; + pthread_mutex_unlock(&last_stat_update_mutex); + + /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */ + if (!cpu_setup || !info.cpu_usage) { + get_cpu_count(); + cpu_setup = 1; + } + + if (!stat_template) { + stat_template = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT; + } + + if (!global_cpu) { + malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info); + cpu = (struct cpu_info *)malloc(malloc_cpu_size); + memset(cpu, 0, malloc_cpu_size); + global_cpu = cpu; + } + + if (!(stat_fp = open_file("/proc/stat", &rep))) { + info.run_threads = 0; + if (info.cpu_usage) { + memset(info.cpu_usage, 0, info.cpu_count * sizeof(float)); + } + return 0; + } + + idx = 0; + while (!feof(stat_fp)) { + if (fgets(buf, 255, stat_fp) == nullptr) { break; } + + if (strncmp(buf, "procs_running ", 14) == 0) { + sscanf(buf, "%*s %hu", &info.run_threads); + } else if (strncmp(buf, "cpu", 3) == 0) { + double delta; + if (isdigit((unsigned char)buf[3])) { + idx++; // just increment here since the CPU index can skip numbers + } else { + idx = 0; + } + if (idx > info.cpu_count) { continue; } + sscanf(buf, stat_template, &(cpu[idx].cpu_user), &(cpu[idx].cpu_nice), + &(cpu[idx].cpu_system), &(cpu[idx].cpu_idle), + &(cpu[idx].cpu_iowait), &(cpu[idx].cpu_irq), + &(cpu[idx].cpu_softirq), &(cpu[idx].cpu_steal)); + + cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice + + cpu[idx].cpu_system + cpu[idx].cpu_idle + + cpu[idx].cpu_iowait + cpu[idx].cpu_irq + + cpu[idx].cpu_softirq + cpu[idx].cpu_steal; + + cpu[idx].cpu_active_total = + cpu[idx].cpu_total - (cpu[idx].cpu_idle + cpu[idx].cpu_iowait); + + delta = current_update_time - last_update_time; + + if (delta <= 0.001) { break; } + + cur_total = (float)(cpu[idx].cpu_total - cpu[idx].cpu_last_total); + if (cur_total == 0.0) { + cpu[idx].cpu_val[0] = 1.0; + } else { + cpu[idx].cpu_val[0] = + (cpu[idx].cpu_active_total - cpu[idx].cpu_last_active_total) / + cur_total; + } + curtmp = 0; + + int samples = cpu_avg_samples.get(*state); +#ifdef HAVE_OPENMP +#pragma omp parallel for reduction(+ : curtmp) schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < samples; i++) { curtmp = curtmp + cpu[idx].cpu_val[i]; } + info.cpu_usage[idx] = curtmp / samples; + + cpu[idx].cpu_last_total = cpu[idx].cpu_total; + cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total; +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = samples - 1; i > 0; i--) { + cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1]; + } + } + } + fclose(stat_fp); + return 0; + } + + int update_running_processes(void) { + update_stat(); + return 0; + } + + int update_cpu_usage(void) { + update_stat(); + return 0; + } + + void free_cpu(struct text_object *) { /* not used */ } + + // fscanf() that reads floats with points even if you are using a locale where + // floats are with commas + int fscanf_no_i18n(FILE *stream, const char *format, ...) { + int returncode; + va_list ap; + +#ifdef BUILD_I18N + const char *oldlocale = setlocale(LC_NUMERIC, nullptr); + + setlocale(LC_NUMERIC, "C"); +#endif + va_start(ap, format); + returncode = vfscanf(stream, format, ap); + va_end(ap); +#ifdef BUILD_I18N + setlocale(LC_NUMERIC, oldlocale); +#endif + return returncode; + } + + int update_load_average(void) { +#ifdef HAVE_GETLOADAVG + if (!prefer_proc) { + double v[3]; + + getloadavg(v, 3); + info.loadavg[0] = (float)v[0]; + info.loadavg[1] = (float)v[1]; + info.loadavg[2] = (float)v[2]; + } else +#endif + { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file("/proc/loadavg", &rep))) { + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + return 0; + } + if (fscanf_no_i18n(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1], + &info.loadavg[2]) < 0) + info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0; + fclose(fp); + } + return 0; + } + + /***********************************************************/ + /***********************************************************/ + /***********************************************************/ + + static int no_dots(const struct dirent *d) { + if (d->d_name[0] == '.') { return 0; } + return 1; + } + + static int get_first_file_in_a_directory(const char *dir, char *s, int *rep) { + struct dirent **namelist; + int i, n; + + n = scandir(dir, &namelist, no_dots, alphasort); + if (n < 0) { + if (!rep || !*rep) { + NORM_ERR("scandir for %s: %s", dir, strerror(errno)); + if (rep) { *rep = 1; } + } + return 0; + } else { + if (n == 0) { return 0; } + + strncpy(s, namelist[0]->d_name, 255); + s[255] = '\0'; + +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (i = 0; i < n; i++) { free(namelist[i]); } + free(namelist); + + return 1; + } + } + + static int open_sysfs_sensor(const char *dir, const char *dev, + const char *type, int n, int *divisor, + char *devtype) { + char path[256]; + char buf[256]; + int fd; + int divfd; + + memset(buf, 0, sizeof(buf)); + + /* if device is nullptr or *, get first */ + if (dev == nullptr || strcmp(dev, "*") == 0) { + static int rep = 0; + + if (!get_first_file_in_a_directory(dir, buf, &rep)) { return -1; } + dev = buf; + } + + if (strcmp(dir, "/sys/class/hwmon/") == 0) { + if (*buf) { + /* buf holds result from get_first_file_in_a_directory() above, + * e.g. "hwmon0" -- append "/device" */ + strncat(buf, "/device", 256); + } else { + /* dev holds device number N as a string, + * e.g. "0", -- convert to "hwmon0/device" */ + sprintf(buf, "hwmon%s/device", dev); + dev = buf; + } + } + + /* change vol to in, tempf to temp */ + if (strcmp(type, "vol") == 0) { + type = "in"; + } else if (strcmp(type, "tempf") == 0) { + type = "temp"; + } else if (strcmp(type, "temp2") == 0) { + type = "temp"; + } + + /* construct path */ + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + + /* first, attempt to open file in /device */ + fd = open(path, O_RDONLY); + if (fd < 0) { + /* if it fails, strip the /device from dev and attempt again */ + buf[strlen(buf) - 7] = 0; + snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n); + fd = open(path, O_RDONLY); + if (fd < 0) { + NORM_ERR( + "can't open '%s': %s\nplease check your device or remove this " + "var from " PACKAGE_NAME, + path, strerror(errno)); + } + } + + strncpy(devtype, path, 255); + + if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0 || + strcmp(type, "tempf") == 0) { + *divisor = 1; + } else { + *divisor = 0; + } + /* fan does not use *_div as a read divisor */ + if (strcmp("fan", type) == 0) { return fd; } + + /* test if *_div file exist, open it and use it as divisor */ + if (strcmp(type, "tempf") == 0) { + snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n); + } else { + snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n); + } + + divfd = open(path, O_RDONLY); + if (divfd > 0) { + /* read integer */ + char divbuf[64]; + int divn; + + divn = read(divfd, divbuf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (divn < 0) { + NORM_ERR("open_sysfs_sensor(): can't read from sysfs"); + } else { + divbuf[divn] = '\0'; + *divisor = atoi(divbuf); + } + close(divfd); + } + + return fd; + } + + static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type) { + int val = 0; + + if (*fd <= 0) { return 0; } + + lseek(*fd, 0, SEEK_SET); + + /* read integer */ + { + char buf[64]; + int n; + n = read(*fd, buf, 63); + /* should read until n == 0 but I doubt that kernel will give these + * in multiple pieces. :) */ + if (n < 0) { + NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype); + } else { + buf[n] = '\0'; + val = atoi(buf); + } + } + + close(*fd); + /* open file */ + *fd = open(devtype, O_RDONLY); + if (*fd < 0) { NORM_ERR("can't open '%s': %s", devtype, strerror(errno)); } + + /* My dirty hack for computing CPU value + * Filedil, from forums.gentoo.org */ + /* if (strstr(devtype, "temp1_input") != nullptr) { + return -15.096 + 1.4893 * (val / 1000.0); + } */ + + /* divide voltage and temperature by 1000 */ + /* or if any other divisor is given, use that */ + if (0 == (strcmp(type, "temp2"))) { + temp2 = "temp2"; + } else { + temp2 = "empty"; + } + if (strcmp(type, "tempf") == 0) { + if (divisor > 1) { + return ((val / divisor + 40) * 9.0 / 5) - 40; + } else if (divisor) { + return ((val / 1000.0 + 40) * 9.0 / 5) - 40; + } else { + return ((val + 40) * 9.0 / 5) - 40; + } + } else { + if (divisor > 1) { + return val / divisor; + } else if (divisor) { + return val / 1000.0; + } else { + return val; + } + } + } + +#define HWMON_RESET() \ + { \ + buf1[0] = 0; \ + factor = 1.0; \ + offset = 0.0; \ + } + + static void parse_sysfs_sensor(struct text_object *obj, const char *arg, + const char *path, const char *type) { + char buf1[64], buf2[64]; + float factor, offset; + int n, found = 0; + struct sysfs *sf; + + if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) + found = 1; + else + HWMON_RESET(); + if (!found && + sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) + found = 1; + else if (!found) + HWMON_RESET(); + if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) + found = 1; + else if (!found) + HWMON_RESET(); + + if (!found) { + obj_be_plain_text(obj, "fail"); + return; + } + DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, + offset); + sf = (struct sysfs *)malloc(sizeof(struct sysfs)); + memset(sf, 0, sizeof(struct sysfs)); + sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n, &sf->arg, + sf->devtype); + strncpy(sf->type, buf2, 63); + sf->factor = factor; + sf->offset = offset; + obj->data.opaque = sf; + } + +#define PARSER_GENERATOR(name, path) \ + void parse_##name##_sensor(struct text_object *obj, const char *arg) { \ + parse_sysfs_sensor(obj, arg, path, #name); \ + } + + PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/") + PARSER_GENERATOR(hwmon, "/sys/class/hwmon/") + PARSER_GENERATOR(platform, "/sys/bus/platform/devices/") + + void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size) { + double r; + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf || sf->fd < 0) return; + + r = get_sysfs_info(&sf->fd, sf->arg, sf->devtype, sf->type); + + r = r * sf->factor + sf->offset; + + if (0 == (strcmp(temp2, "temp2"))) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 0); + } else if (!strncmp(sf->type, "temp", 4)) { + temp_print(p, p_max_size, r, TEMP_CELSIUS, 1); + } else if (r >= 100.0 || r == 0) { + snprintf(p, p_max_size, "%d", (int)r); + } else { + snprintf(p, p_max_size, "%.1f", r); + } + } + + void free_sysfs_sensor(struct text_object *obj) { + struct sysfs *sf = (struct sysfs *)obj->data.opaque; + + if (!sf) return; + + if (sf->fd >= 0) close(sf->fd); + free_and_zero(obj->data.opaque); + } + +#define CPUFREQ_PREFIX "/sys/devices/system/cpu" +#define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq" + + /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */ + char get_freq(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + static int rep = 0; + char frequency[32]; + char s[256]; + double freq = 0; + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + if (!prefer_proc) { + char current_freq_file[128]; + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1, + CPUFREQ_POSTFIX); + f = fopen(current_freq_file, "r"); + if (f) { + /* if there's a cpufreq /sys node, read the current frequency from + * this node and divide by 1000 to get Mhz. */ + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (freq / 1000) / divisor); + return 1; + } + } + + // open the CPU information file + f = open_file("/proc/cpuinfo", &rep); + if (!f) { + perror(PACKAGE_NAME ": Failed to access '/proc/cpuinfo' at get_freq()"); + return 0; + } + + // read the file + while (fgets(s, sizeof(s), f) != nullptr) { +#if defined(__i386) || defined(__x86_64) + // and search for the cpu mhz + if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) { +#else +#if defined(__alpha) + // different on alpha + if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) { +#else + // this is different on ppc for some reason + if (strncmp(s, "clock", 5) == 0 && cpu == 0) { +#endif // defined(__alpha) +#endif // defined(__i386) || defined(__x86_64) + + // copy just the number + strncpy(frequency, strchr(s, ':') + 2, 32); +#if defined(__alpha) + // strip " est.\n" + frequency[strlen(frequency) - 6] = '\0'; + // kernel reports in Hz + freq = strtod(frequency, nullptr) / 1000000; +#else + // strip \n + frequency[strlen(frequency) - 1] = '\0'; + freq = strtod(frequency, nullptr); +#endif + break; + } + if (strncmp(s, "processor", 9) == 0) { + cpu--; + continue; + } + } + + fclose(f); + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)freq / divisor); + return 1; + } + +#define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages" + + /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something + * like this: + # frequency voltage + 1800000 1340 + 1600000 1292 + 1400000 1100 + 1200000 988 + 1000000 1116 + 800000 1004 + 600000 988 + * Peter Tarjan (ptarjan@citromail.hu) */ + + /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */ + static char get_voltage(char *p_client_buffer, size_t client_buffer_size, + const char *p_format, int divisor, unsigned int cpu) { + FILE *f; + char s[256]; + int freq = 0; + int voltage = 0; + char current_freq_file[128]; + int freq_comp = 0; + + /* build the voltage file name */ + cpu--; + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_POSTFIX); + + if (!p_client_buffer || client_buffer_size <= 0 || !p_format || + divisor <= 0) { + return 0; + } + + /* read the current cpu frequency from the /sys node */ + f = fopen(current_freq_file, "r"); + if (f) { + if (fgets(s, sizeof(s), f)) { + s[strlen(s) - 1] = '\0'; + freq = strtod(s, nullptr); + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + + snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu, + CPUFREQ_VOLTAGE); + + /* use the current cpu frequency to find the corresponding voltage */ + f = fopen(current_freq_file, "r"); + + if (f) { + while (!feof(f)) { + char line[256]; + + if (fgets(line, 255, f) == nullptr) { break; } + sscanf(line, "%d %d", &freq_comp, &voltage); + if (freq_comp == freq) { break; } + } + fclose(f); + } else { + fprintf(stderr, PACKAGE_NAME ": Failed to access '%s' at ", + current_freq_file); + perror("get_voltage()"); + return 0; + } + snprintf(p_client_buffer, client_buffer_size, p_format, + (float)voltage / divisor); + return 1; + } + + void print_voltage_mv(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i); } + } + + void print_voltage_v(struct text_object *obj, char *p, int p_max_size) { + static int ok = 1; + if (ok) { ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i); } + } + +#define ACPI_FAN_DIR "/proc/acpi/fan/" + + void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size) { + static int rep = 0; + char buf[256]; + char buf2[256]; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no fans?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "can't open fan's state file"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + +#define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply" +#define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/" + /* Linux 2.6.25 onwards ac adapter info is in + /sys/class/power_supply/AC/ + On my system I get the following. + /sys/class/power_supply/AC/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=ac + POWER_SUPPLY_NAME=AC + POWER_SUPPLY_TYPE=Mains + POWER_SUPPLY_ONLINE=1 + + Update: it seems the folder name is hardware-dependent. We add an aditional + adapter argument, specifying the folder name. + + Update: on some systems it's /sys/class/power_supply/ADP1 instead of + /sys/class/power_supply/AC + */ + + void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, + const char *adapter) { + static int rep = 0; + + char buf[256]; + char buf2[256]; + struct stat sb; + FILE *fp; + + if (!p_client_buffer || client_buffer_size <= 0) { return; } + + if (adapter) + snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, + adapter); + else { + snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR); + if (stat(buf2, &sb) == -1) + snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR); + } + if (stat(buf2, &sb) == 0) + fp = open_file(buf2, &rep); + else + fp = 0; + if (fp) { + /* sysfs processing */ + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) { + int online = 0; + sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online); + snprintf(p_client_buffer, client_buffer_size, "%s-line", + (online ? "on" : "off")); + break; + } + } + fclose(fp); + } else { + /* yeah, slow... :/ */ + if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) { + snprintf(p_client_buffer, client_buffer_size, "%s", "no ac_adapters?"); + return; + } + + snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf); + + fp = open_file(buf2, &rep); + if (!fp) { + snprintf(p_client_buffer, client_buffer_size, "%s", + "No ac adapter found.... where is it?"); + return; + } + memset(buf, 0, sizeof(buf)); + if (fscanf(fp, "%*s %99s", buf) <= 0) perror("fscanf()"); + fclose(fp); + + snprintf(p_client_buffer, client_buffer_size, "%s", buf); + } + } + + /* + /proc/acpi/thermal_zone/THRM/cooling_mode + cooling mode: active + /proc/acpi/thermal_zone/THRM/polling_frequency + + /proc/acpi/thermal_zone/THRM/state + state: ok + /proc/acpi/thermal_zone/THRM/temperature + temperature: 45 C + /proc/acpi/thermal_zone/THRM/trip_points + critical (S5): 73 C + passive: 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0 + */ + +#define ACPI_THERMAL_ZONE_DEFAULT "thermal_zone0" +#define ACPI_THERMAL_FORMAT "/sys/class/thermal/%s/temp" + + int open_acpi_temperature(const char *name) { + char path[256]; + int fd; + + if (name == nullptr || strcmp(name, "*") == 0) { + snprintf(path, 255, ACPI_THERMAL_FORMAT, ACPI_THERMAL_ZONE_DEFAULT); + } else { + snprintf(path, 255, ACPI_THERMAL_FORMAT, name); + } + + fd = open(path, O_RDONLY); + if (fd < 0) { NORM_ERR("can't open '%s': %s", path, strerror(errno)); } + + return fd; + } + + static double last_acpi_temp; + static double last_acpi_temp_time; + + // the maximum length of the string inside a ACPI_THERMAL_FORMAT file including + // the ending 0 +#define MAXTHERMZONELEN 6 + + double get_acpi_temperature(int fd) { + if (fd <= 0) { return 0; } + + /* don't update acpi temperature too often */ + if (current_update_time - last_acpi_temp_time < 11.32) { + return last_acpi_temp; + } + last_acpi_temp_time = current_update_time; + + /* seek to beginning */ + lseek(fd, 0, SEEK_SET); + + /* read */ + { + char buf[MAXTHERMZONELEN]; + int n; + + n = read(fd, buf, MAXTHERMZONELEN - 1); + if (n < 0) { + NORM_ERR("can't read fd %d: %s", fd, strerror(errno)); + } else { + buf[n] = '\0'; + sscanf(buf, "%lf", &last_acpi_temp); + last_acpi_temp /= 1000; + } + } + + return last_acpi_temp; + } + + /* + hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info + present: yes + design capacity: 4400 mAh + last full capacity: 4064 mAh + battery technology: rechargeable + design voltage: 14800 mV + design capacity warning: 300 mAh + design capacity low: 200 mAh + capacity granularity 1: 32 mAh + capacity granularity 2: 32 mAh + model number: 02KT + serial number: 16922 + battery type: LION + OEM info: SANYO + */ + + /* + hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state + present: yes + capacity state: ok + charging state: unknown + present rate: 0 mA + remaining capacity: 4064 mAh + present voltage: 16608 mV + */ + + /* + 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ? + 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�) + 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm + 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ? + + 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman + verkkovirtaa 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? + verkkovirralla + + 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja + monitori p��ll� 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? + monitori p��ll� mutta ilman verkkovirtaa + */ + + /* Kapil Hari Paranjape + Linux 2.6.24 onwards battery info is in + /sys/class/power_supply/BAT0/ + On my system I get the following. + /sys/class/power_supply/BAT0/uevent: + PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00 + PHYSDEVBUS=acpi + PHYSDEVDRIVER=battery + POWER_SUPPLY_NAME=BAT0 + POWER_SUPPLY_TYPE=Battery + POWER_SUPPLY_STATUS=Discharging + POWER_SUPPLY_PRESENT=1 + POWER_SUPPLY_TECHNOLOGY=Li-ion + POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000 + POWER_SUPPLY_VOLTAGE_NOW=10780000 + POWER_SUPPLY_CURRENT_NOW=13970000 + POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000 + POWER_SUPPLY_ENERGY_FULL=27370000 + POWER_SUPPLY_ENERGY_NOW=11810000 + POWER_SUPPLY_MODEL_NAME=IBM-92P1060 + POWER_SUPPLY_MANUFACTURER=Panasonic + On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_* + */ + + /* Tiago Marques Vale + Regarding the comment above, since kernel 2.6.36.1 I have + POWER_SUPPLY_POWER_NOW instead of POWER_SUPPLY_CURRENT_NOW + See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532000 + */ + +#define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply" +#define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" +#define APM_PATH "/proc/apm" +#define MAX_BATTERY_COUNT 4 + + static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = {nullptr, NULL, NULL, NULL}; + + static int batteries_initialized = 0; + static char batteries[MAX_BATTERY_COUNT][32]; + + static int acpi_last_full[MAX_BATTERY_COUNT]; + static int acpi_design_capacity[MAX_BATTERY_COUNT]; + + /* e.g. "charging 75%" */ + static char last_battery_str[MAX_BATTERY_COUNT][64]; + /* e.g. "3h 15m" */ + static char last_battery_time_str[MAX_BATTERY_COUNT][64]; + + static double last_battery_time[MAX_BATTERY_COUNT]; + + static int last_battery_perct[MAX_BATTERY_COUNT]; + static double last_battery_perct_time[MAX_BATTERY_COUNT]; + + void init_batteries(void) { + int idx; + + if (batteries_initialized) { return; } +#ifdef HAVE_OPENMP +#pragma omp parallel for schedule(dynamic, 10) +#endif /* HAVE_OPENMP */ + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { batteries[idx][0] = '\0'; } + batteries_initialized = 1; + } + + int get_battery_idx(const char *bat) { + int idx; + + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) { break; } + } + + /* if not found, enter a new entry */ + if (!strlen(batteries[idx])) { snprintf(batteries[idx], 31, "%s", bat); } + + return idx; + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx); + + void get_battery_stuff(char *buffer, unsigned int n, const char *bat, + int item) { + static int idx, rep = 0, rep1 = 0, rep2 = 0; + char acpi_path[128]; + char sysfs_path[128]; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + init_batteries(); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_time[idx] < 29.5) { + set_return_value(buffer, n, item, idx); + return; + } + + last_battery_time[idx] = current_update_time; + + memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx])); + memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx])); + + /* first try SYSFS if that fails try ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep1); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[4]; + + strncpy(charging_state, "unknown", 64); + + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + /* let's just hope units are ok */ + if (strncmp(buf, "POWER_SUPPLY_PRESENT=1", 22) == 0) + strncpy(present, "yes", 4); + else if (strncmp(buf, "POWER_SUPPLY_PRESENT=0", 22) == 0) + strncpy(present, "no", 4); + else if (strncmp(buf, "POWER_SUPPLY_STATUS=", 20) == 0) + sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state); + /* present_rate is not the same as the current flowing now but it + * is the same value which was used in the past. so we continue the + * tradition! */ + else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_POWER_NOW=", 23) == 0) + sscanf(buf, "POWER_SUPPLY_POWER_NOW=%d", &present_rate); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]); + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) + acpi_last_full[idx] = remaining_capacity; /* normalize to 100% */ + + /* not present */ + if (strcmp(present, "No") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + } + /* charging */ + else if (strcmp(charging_state, "Charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)(acpi_last_full[idx] - remaining_capacity) / + present_rate) * + 3600)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* discharging */ + else if (strncmp(charging_state, "Discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + /* e.g. 1h 12m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((float)remaining_capacity / present_rate) * 3600)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "full"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf( + last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + } + /* charged */ + /* thanks to Lukas Zapletal */ + else if (strncmp(charging_state, "Charged", 64) == 0 || + strncmp(charging_state, "Full", 64) == 0) { + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one + * being charged. */ + if (remaining_capacity == 0) + strncpy(last_battery_str[idx], "empty", 64); + else + strncpy(last_battery_str[idx], "charged", 64); + } + /* unknown, probably full / AC */ + else { + if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) + snprintf( + last_battery_str[idx], 64, "unknown %d%%", + (int)(((float)remaining_capacity / acpi_last_full[idx]) * 100)); + else + strncpy(last_battery_str[idx], "not present", 64); + } + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + int present_rate = -1; + int remaining_capacity = -1; + char charging_state[64]; + char present[5]; + + /* read last full capacity if it's zero */ + if (acpi_last_full[idx] == 0) { + static int rep3 = 0; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep3); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", &acpi_last_full[idx]) != 0) { + break; + } + } + + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + strncpy(charging_state, "unknown", 8); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + /* let's just hope units are ok */ + if (strncmp(buf, "present:", 8) == 0) { + sscanf(buf, "present: %4s", present); + } else if (strncmp(buf, "charging state:", 15) == 0) { + sscanf(buf, "charging state: %63s", charging_state); + } else if (strncmp(buf, "present rate:", 13) == 0) { + sscanf(buf, "present rate: %d", &present_rate); + } else if (strncmp(buf, "remaining capacity:", 19) == 0) { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */ + if (remaining_capacity > acpi_last_full[idx]) { + /* normalize to 100% */ + acpi_last_full[idx] = remaining_capacity; + } + + /* not present */ + if (strcmp(present, "no") == 0) { + strncpy(last_battery_str[idx], "not present", 64); + /* charging */ + } else if (strcmp(charging_state, "charging") == 0) { + if (acpi_last_full[idx] != 0 && present_rate > 0) { + /* e.g. charging 75% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 2h 37m */ + format_seconds( + last_battery_time_str[idx], sizeof(last_battery_time_str[idx]) - 1, + (long)(((acpi_last_full[idx] - remaining_capacity) * 3600) / + present_rate)); + } else if (acpi_last_full[idx] != 0 && present_rate <= 0) { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + strncpy(last_battery_str[idx], "charging", + sizeof(last_battery_str[idx]) - 1); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* discharging */ + } else if (strncmp(charging_state, "discharging", 64) == 0) { + if (present_rate > 0) { + /* e.g. discharging 35% */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %i%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + /* e.g. 1h 12m */ + format_seconds(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, + (long)((remaining_capacity * 3600) / present_rate)); + } else if (present_rate == 0) { /* Thanks to Nexox for this one */ + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "charged"); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } else { + snprintf(last_battery_str[idx], sizeof(last_battery_str[idx]) - 1, + "discharging %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + snprintf(last_battery_time_str[idx], + sizeof(last_battery_time_str[idx]) - 1, "%s", "unknown"); + } + /* charged */ + } else if (strncmp(charging_state, "charged", 64) == 0) { + /* thanks to Lukas Zapletal */ + /* Below happens with the second battery on my X40, + * when the second one is empty and the first one being charged. */ + if (remaining_capacity == 0) { + strncpy(last_battery_str[idx], "empty", 6); + } else { + strncpy(last_battery_str[idx], "charged", 8); + } + /* unknown, probably full / AC */ + } else { + if (strncmp(charging_state, "Full", 64) == 0) { + strncpy(last_battery_str[idx], "charged", 64); + } else if (acpi_last_full[idx] != 0 && + remaining_capacity != acpi_last_full[idx]) { + snprintf(last_battery_str[idx], 64, "unknown %d%%", + (int)((remaining_capacity * 100) / acpi_last_full[idx])); + } else { + strncpy(last_battery_str[idx], "not present", 64); + } + } + fclose(acpi_bat_fp[idx]); + acpi_bat_fp[idx] = nullptr; + } else { + /* APM */ + if (apm_bat_fp[idx] == nullptr) { + apm_bat_fp[idx] = open_file(APM_PATH, &rep2); + } + + if (apm_bat_fp[idx] != nullptr) { + unsigned int ac, status, flag; + int life; + + if (fscanf(apm_bat_fp[idx], "%*s %*s %*x %x %x %x %d%%", &ac, + &status, &flag, &life) <= 0) + goto read_bat_fp_end; + + if (life == -1) { + /* could check now that there is ac */ + snprintf(last_battery_str[idx], 64, "%s", "not present"); + + /* could check that status == 3 here? */ + } else if (ac && life != 100) { + snprintf(last_battery_str[idx], 64, "charging %d%%", life); + } else { + snprintf(last_battery_str[idx], 64, "%d%%", life); + } + + read_bat_fp_end: + /* it seemed to buffer it so file must be closed (or could use + * syscalls directly but I don't feel like coding it now) */ + fclose(apm_bat_fp[idx]); + apm_bat_fp[idx] = nullptr; + } + } + set_return_value(buffer, n, item, idx); + } + + void set_return_value(char *buffer, unsigned int n, int item, int idx) { + switch (item) { + case BATTERY_STATUS: + snprintf(buffer, n, "%s", last_battery_str[idx]); + break; + case BATTERY_TIME: + snprintf(buffer, n, "%s", last_battery_time_str[idx]); + break; + default: + break; + } + } + + void get_battery_short_status(char *buffer, unsigned int n, const char *bat) { + get_battery_stuff(buffer, n, bat, BATTERY_STATUS); + if (0 == strncmp("charging", buffer, 8)) { + buffer[0] = 'C'; + memmove(buffer + 1, buffer + 8, n - 8); + } else if (0 == strncmp("discharging", buffer, 11)) { + buffer[0] = 'D'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("charged", buffer, 7)) { + buffer[0] = 'F'; + memmove(buffer + 1, buffer + 7, n - 7); + } else if (0 == strncmp("not present", buffer, 11)) { + buffer[0] = 'N'; + memmove(buffer + 1, buffer + 11, n - 11); + } else if (0 == strncmp("empty", buffer, 5)) { + buffer[0] = 'E'; + memmove(buffer + 1, buffer + 5, n - 5); + } else if (0 == strncmp("unknown", buffer, 7)) { + buffer[0] = 'U'; + memmove(buffer + 1, buffer + 7, n - 7); + } + // Otherwise, don't shorten. + } + + int _get_battery_perct(const char *bat) { + static int rep = 0; + int idx; + char acpi_path[128]; + char sysfs_path[128]; + int remaining_capacity = -1; + + snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat); + snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat); + + idx = get_battery_idx(bat); + + /* don't update battery too often */ + if (current_update_time - last_battery_perct_time[idx] < 30) { + return last_battery_perct[idx]; + } + last_battery_perct_time[idx] = current_update_time; + + /* Only check for SYSFS or ACPI */ + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + sysfs_bat_fp[idx] = open_file(sysfs_path, &rep); + rep = 0; + } + + if (sysfs_bat_fp[idx] == nullptr && acpi_bat_fp[idx] == NULL && + apm_bat_fp[idx] == nullptr) { + acpi_bat_fp[idx] = open_file(acpi_path, &rep); + } + + if (sysfs_bat_fp[idx] != nullptr) { + /* SYSFS */ + while (!feof(sysfs_bat_fp[idx])) { + char buf[256]; + if (fgets(buf, 256, sysfs_bat_fp[idx]) == nullptr) break; + + if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity); + } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0) { + sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]); + } + } + + fclose(sysfs_bat_fp[idx]); + sysfs_bat_fp[idx] = nullptr; + + } else if (acpi_bat_fp[idx] != nullptr) { + /* ACPI */ + /* read last full capacity if it's zero */ + if (acpi_design_capacity[idx] == 0) { + static int rep2; + char path[128]; + FILE *fp; + + snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat); + fp = open_file(path, &rep2); + if (fp != nullptr) { + while (!feof(fp)) { + char b[256]; + + if (fgets(b, 256, fp) == nullptr) { break; } + if (sscanf(b, "last full capacity: %d", + &acpi_design_capacity[idx]) != 0) { + break; + } + } + fclose(fp); + } + } + + fseek(acpi_bat_fp[idx], 0, SEEK_SET); + + while (!feof(acpi_bat_fp[idx])) { + char buf[256]; + + if (fgets(buf, 256, acpi_bat_fp[idx]) == nullptr) { break; } + + if (buf[0] == 'r') { + sscanf(buf, "remaining capacity: %d", &remaining_capacity); + } + } + } + if (remaining_capacity < 0) { return 0; } + /* compute the battery percentage */ + last_battery_perct[idx] = + (int)(((float)remaining_capacity / acpi_design_capacity[idx]) * 100); + if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100; + return last_battery_perct[idx]; + } + + int get_battery_perct(const char *bat) { + int idx, n = 0, total_capacity = 0, remaining_capacity; + ; +#define BATTERY_LEN 8 + char battery[BATTERY_LEN]; + + init_batteries(); + + /* Check if user asked for the mean percentage of all batteries. */ + if (!strcmp(bat, "all")) { + for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) { + snprintf(battery, BATTERY_LEN - 1, "BAT%d", idx); +#undef BATTERY_LEN + remaining_capacity = _get_battery_perct(battery); + if (remaining_capacity > 0) { + total_capacity += remaining_capacity; + n++; + } + } + + if (n == 0) + return 0; + else + return total_capacity / n; + } else { + return _get_battery_perct(bat); + } + } + + double get_battery_perct_bar(struct text_object *obj) { + int idx; + + get_battery_perct(obj->data.s); + idx = get_battery_idx(obj->data.s); + return last_battery_perct[idx]; + } + + /* On Apple powerbook and ibook: + $ cat /proc/pmu/battery_0 + flags : 00000013 + charge : 3623 + max_charge : 3720 + current : 388 + voltage : 16787 + time rem. : 900 + $ cat /proc/pmu/info + PMU driver version : 2 + PMU firmware version : 0c + AC Power : 1 + Battery count : 1 + */ + + /* defines as in */ +#define PMU_BATT_PRESENT 0x00000001 +#define PMU_BATT_CHARGING 0x00000002 + + static FILE *pmu_battery_fp; + static FILE *pmu_info_fp; + static char pb_battery_info[3][32]; + static double pb_battery_info_update; + +#define PMU_PATH "/proc/pmu" + void get_powerbook_batt_info(struct text_object *obj, char *buffer, int n) { + static int rep = 0; + const char *batt_path = PMU_PATH "/battery_0"; + const char *info_path = PMU_PATH "/info"; + unsigned int flags = 0; + int charge = 0; + int max_charge = 1; + int ac = -1; + long timeval = -1; + + /* don't update battery too often */ + if (current_update_time - pb_battery_info_update < 29.5) { + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + return; + } + pb_battery_info_update = current_update_time; + + if (pmu_battery_fp == nullptr) { + pmu_battery_fp = open_file(batt_path, &rep); + if (pmu_battery_fp == nullptr) { return; } + } + + if (pmu_battery_fp != nullptr) { + rewind(pmu_battery_fp); + while (!feof(pmu_battery_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_battery_fp) == nullptr) { break; } + + if (buf[0] == 'f') { + sscanf(buf, "flags : %8x", &flags); + } else if (buf[0] == 'c' && buf[1] == 'h') { + sscanf(buf, "charge : %d", &charge); + } else if (buf[0] == 'm') { + sscanf(buf, "max_charge : %d", &max_charge); + } else if (buf[0] == 't') { + sscanf(buf, "time rem. : %ld", &timeval); + } + } + } + if (pmu_info_fp == nullptr) { + pmu_info_fp = open_file(info_path, &rep); + if (pmu_info_fp == nullptr) { return; } + } + + if (pmu_info_fp != nullptr) { + rewind(pmu_info_fp); + while (!feof(pmu_info_fp)) { + char buf[32]; + + if (fgets(buf, sizeof(buf), pmu_info_fp) == nullptr) { break; } + if (buf[0] == 'A') { sscanf(buf, "AC Power : %d", &ac); } + } + } + /* update status string */ + if ((ac && !(flags & PMU_BATT_PRESENT))) { + strncpy(pb_battery_info[PB_BATT_STATUS], "AC", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if (ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charged", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) { + strncpy(pb_battery_info[PB_BATT_STATUS], "charging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } else { + strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", + sizeof(pb_battery_info[PB_BATT_STATUS])); + } + + /* update percentage string */ + if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT) && + !(flags & PMU_BATT_CHARGING)) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "100%%"); + } else if (timeval == 0) { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%s", "unknown"); + } else { + snprintf(pb_battery_info[PB_BATT_PERCENT], + sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%", + (charge * 100) / max_charge); + } + + /* update time string */ + if (timeval == 0) { /* fully charged or battery not present */ + snprintf(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), "%s", "unknown"); + } else if (timeval < 60 * 60) { /* don't show secs */ + format_seconds_short(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } else { + format_seconds(pb_battery_info[PB_BATT_TIME], + sizeof(pb_battery_info[PB_BATT_TIME]), timeval); + } + + snprintf(buffer, n, "%s", pb_battery_info[obj->data.i]); + } + +#define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail" + + int get_entropy_avail(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + +#define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize" + + int get_entropy_poolsize(unsigned int *val) { + static int rep = 0; + FILE *fp; + + if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep))) return 1; + + if (fscanf(fp, "%u", val) != 1) return 1; + + fclose(fp); + return 0; + } + + void print_disk_protect_queue(struct text_object *obj, char *p, + int p_max_size) { + FILE *fp; + char path[128]; + int state; + + snprintf(path, 127, "/sys/block/%s/device/unload_heads", obj->data.s); + if (access(path, F_OK)) { + snprintf(path, 127, "/sys/block/%s/queue/protect", obj->data.s); + } + if ((fp = fopen(path, "r")) == nullptr) { + snprintf(p, p_max_size, "%s", "n/a "); + return; + } + if (fscanf(fp, "%d\n", &state) != 1) { + fclose(fp); + snprintf(p, p_max_size, "%s", "failed"); + return; + } + fclose(fp); + snprintf(p, p_max_size, "%s", (state > 0) ? "frozen" : "free "); + } + + std::unordered_map dev_list; + + /* Same as sf #2942117 but memoized using a linked list */ + int is_disk(char *dev) { + std::string orig(dev); + std::string syspath("/sys/block/"); + char *slash; + + auto i = dev_list.find(orig); + if (i != dev_list.end()) return i->second; + + while ((slash = strchr(dev, '/'))) *slash = '!'; + syspath += dev; + + return dev_list[orig] = !(access(syspath.c_str(), F_OK)); + } + + int update_diskio(void) { + FILE *fp; + static int rep = 0; + char buf[512], devbuf[64]; + unsigned int major, minor; + int col_count = 0; + struct diskio_stat *cur; + unsigned int reads, writes; + unsigned int total_reads = 0, total_writes = 0; + + stats.current = 0; + stats.current_read = 0; + stats.current_write = 0; + + if (!(fp = open_file("/proc/diskstats", &rep))) { return 0; } + + /* read reads and writes from all disks (minor = 0), including cd-roms + * and floppies, and sum them up */ + while (fgets(buf, 512, fp)) { + col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major, + &minor, devbuf, &reads, &writes); + /* ignore subdevices (they have only 3 matching entries in their line) + * and virtual devices (LVM, network block devices, RAM disks, Loopback) + * + * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */ + if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR && + major != RAMDISK_MAJOR && major != LOOP_MAJOR && major != DM_MAJOR) { + /* check needed for kernel >= 2.6.31, see sf #2942117 */ + if (is_disk(devbuf)) { + total_reads += reads; + total_writes += writes; + } + } else { + col_count = sscanf(buf, "%u %u %s %*u %u %*u %u", &major, &minor, devbuf, + &reads, &writes); + if (col_count != 5) { continue; } + } + cur = stats.next; + while (cur && strcmp(devbuf, cur->dev)) cur = cur->next; + + if (cur) update_diskio_values(cur, reads, writes); + } + update_diskio_values(&stats, total_reads, total_writes); + fclose(fp); + return 0; + } + + void print_distribution(struct text_object *obj, char *p, int p_max_size) { + (void)obj; + int i, bytes_read; + char *buf; + struct stat sb; + + if (stat("/etc/arch-release", &sb) == 0) { + snprintf(p, p_max_size, "%s", "Arch Linux"); + return; + } + snprintf(p, p_max_size, "Unknown"); + buf = readfile("/proc/version", &bytes_read, 1); + if (buf) { + /* I am assuming the distribution name is the first string in /proc/version + that: + - is preceded by a '(' + - starts with a capital + - is followed by a space and a number + but i am not sure if this is always true... */ + for (i = 1; i < bytes_read; i++) { + if (buf[i - 1] == '(' && buf[i] >= 'A' && buf[i] <= 'Z') break; + } + if (i < bytes_read) { + snprintf(p, p_max_size, "%s", &buf[i]); + for (i = 1; p[i]; i++) { + if (p[i - 1] == ' ' && p[i] >= '0' && p[i] <= '9') { + p[i - 1] = 0; + break; + } + } + } + free(buf); + } + } + + /****************************************** + * Calculate cpu total * + ******************************************/ +#define TMPL_SHORTPROC "%*s %llu %llu %llu %llu" +#define TMPL_LONGPROC "%*s %llu %llu %llu %llu %llu %llu %llu %llu" + + static unsigned long long calc_cpu_total(void) { + static unsigned long long previous_total = 0; + unsigned long long total = 0; + unsigned long long t = 0; + int rc; + int ps; + char line[BUFFER_LEN] = {0}; + unsigned long long cpu = 0; + unsigned long long niceval = 0; + unsigned long long systemval = 0; + unsigned long long idle = 0; + unsigned long long iowait = 0; + unsigned long long irq = 0; + unsigned long long softirq = 0; + unsigned long long steal = 0; + const char *template_ = + KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGPROC : TMPL_SHORTPROC; + + ps = open("/proc/stat", O_RDONLY); + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return 0; } + + sscanf(line, template_, &cpu, &niceval, &systemval, &idle, &iowait, &irq, + &softirq, &steal); + total = cpu + niceval + systemval + idle + iowait + irq + softirq + steal; + + t = total - previous_total; + previous_total = total; + + return t; + } + + /****************************************** + * Calculate each processes cpu * + ******************************************/ + + inline static void calc_cpu_each(unsigned long long total) { + float mul = 100.0; + if (top_cpu_separate.get(*state)) mul *= info.cpu_count; + + for (struct process *p = first_process; p; p = p->next) + p->amount = mul * (p->user_time + p->kernel_time) / (float)total; + } + +#ifdef BUILD_IOSTATS + static void calc_io_each(void) { + struct process *p; + unsigned long long sum = 0; + + for (p = first_process; p; p = p->next) + sum += p->read_bytes + p->write_bytes; + + if (sum == 0) sum = 1; /* to avoid having NANs if no I/O occured */ + for (p = first_process; p; p = p->next) + p->io_perc = 100.0 * (p->read_bytes + p->write_bytes) / (float)sum; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Extract information from /proc * + ******************************************/ + +#define PROCFS_TEMPLATE "/proc/%d/stat" +#define PROCFS_CMDLINE_TEMPLATE "/proc/%d/cmdline" + + /* These are the guts that extract information out of /proc. + * Anyone hoping to port wmtop should look here first. */ + static void process_parse_stat(struct process *process) { + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN], procname[BUFFER_LEN]; + char cmdline[BUFFER_LEN] = {0}, cmdline_filename[BUFFER_LEN], + cmdline_procname[BUFFER_LEN]; + char basename[BUFFER_LEN] = {0}; + char tmpstr[BUFFER_LEN] = {0}; + char state[4]; + int ps, cmdline_ps; + unsigned long user_time = 0; + unsigned long kernel_time = 0; + int rc; + char *r, *q; + int endl; + int nice_val; + char *lparen, *rparen; + struct stat process_stat; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE, process->pid); + snprintf(cmdline_filename, sizeof(cmdline_filename), PROCFS_CMDLINE_TEMPLATE, + process->pid); + + ps = open(filename, O_RDONLY); + if (ps == -1) { + /* The process must have finished in the last few jiffies! */ + return; + } + + if (fstat(ps, &process_stat) != 0) { + close(ps); + return; + } + process->uid = process_stat.st_uid; + + /* Mark process as up-to-date. */ + process->time_stamp = g_time; + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + /* Read /proc//cmdline */ + cmdline_ps = open(cmdline_filename, O_RDONLY); + if (cmdline_ps < 0) { + /* The process must have finished in the last few jiffies! */ + return; + } + + endl = read(cmdline_ps, cmdline, BUFFER_LEN - 1); + close(cmdline_ps); + if (endl < 0) { return; } + + /* Some processes have null-separated arguments (see proc(5)); let's fix it + */ + int i = endl; + while (i && cmdline[i - 1] == 0) { + /* Skip past any trailing null characters */ + --i; + } + while (i--) { + /* Replace null character between arguments with a space */ + if (cmdline[i] == 0) { cmdline[i] = ' '; } + } + + cmdline[endl] = 0; + + /* We want to transform for example "/usr/bin/python program.py" to "python + * program.py" + * 1. search for first space + * 2. search for last / before first space + * 3. copy string from its position + */ + char *space_ptr = strchr(cmdline, ' '); + if (space_ptr == nullptr) { + strncpy(tmpstr, cmdline, BUFFER_LEN); + } else { + long int space_pos = space_ptr - cmdline; + strncpy(tmpstr, cmdline, space_pos); + tmpstr[space_pos] = 0; + } + + char *slash_ptr = strrchr(tmpstr, '/'); + if (slash_ptr == nullptr) { + strncpy(cmdline_procname, cmdline, BUFFER_LEN); + } else { + long int slash_pos = slash_ptr - tmpstr; + strncpy(cmdline_procname, cmdline + slash_pos + 1, BUFFER_LEN - slash_pos); + cmdline_procname[BUFFER_LEN - slash_pos] = 0; + } + + /* Extract cpu times from data in /proc filesystem */ + lparen = strchr(line, '('); + rparen = strrchr(line, ')'); + if (!lparen || !rparen || rparen < lparen) return; // this should not happen + + rc = MIN((unsigned)(rparen - lparen - 1), sizeof(procname) - 1); + strncpy(procname, lparen + 1, rc); + procname[rc] = '\0'; + strncpy(basename, procname, strlen(procname) + 1); + + if (strlen(procname) < strlen(cmdline_procname)) + strncpy(procname, cmdline_procname, strlen(cmdline_procname) + 1); + + rc = sscanf(rparen + 1, + "%3s %*s %*s %*s %*s %*s %*s %*s %*s %*s %*s %lu " + "%lu %*s %*s %*s %d %*s %*s %*s %llu %llu", + state, &process->user_time, &process->kernel_time, &nice_val, + &process->vsize, &process->rss); + if (rc < 6) { + NORM_ERR("scaning data for %s failed, got only %d fields", procname, rc); + return; + } + + if (state[0] == 'R') ++info.run_procs; + + free_and_zero(process->name); + free_and_zero(process->basename); + process->name = strndup(procname, text_buffer_size.get(*::state)); + process->basename = strndup(basename, text_buffer_size.get(*::state)); + process->rss *= getpagesize(); + + process->total_cpu_time = process->user_time + process->kernel_time; + if (process->previous_user_time == ULONG_MAX) { + process->previous_user_time = process->user_time; + } + if (process->previous_kernel_time == ULONG_MAX) { + process->previous_kernel_time = process->kernel_time; + } + + /* strangely, the values aren't monotonous */ + if (process->previous_user_time > process->user_time) + process->previous_user_time = process->user_time; + + if (process->previous_kernel_time > process->kernel_time) + process->previous_kernel_time = process->kernel_time; + + /* store the difference of the user_time */ + user_time = process->user_time - process->previous_user_time; + kernel_time = process->kernel_time - process->previous_kernel_time; + + /* backup the process->user_time for next time around */ + process->previous_user_time = process->user_time; + process->previous_kernel_time = process->kernel_time; + + /* store only the difference of the user_time here... */ + process->user_time = user_time; + process->kernel_time = kernel_time; + } + +#ifdef BUILD_IOSTATS +#define PROCFS_TEMPLATE_IO "/proc/%d/io" + static void process_parse_io(struct process *process) { + static const char *read_bytes_str = "read_bytes:"; + static const char *write_bytes_str = "write_bytes:"; + + char line[BUFFER_LEN] = {0}, filename[BUFFER_LEN]; + int ps; + int rc; + char *pos, *endpos; + unsigned long long read_bytes, write_bytes; + + snprintf(filename, sizeof(filename), PROCFS_TEMPLATE_IO, process->pid); + + ps = open(filename, O_RDONLY); + if (ps < 0) { + /* The process must have finished in the last few jiffies! + * Or, the kernel doesn't support I/O accounting. + */ + return; + } + + rc = read(ps, line, BUFFER_LEN - 1); + close(ps); + if (rc < 0) { return; } + + pos = strstr(line, read_bytes_str); + if (pos == nullptr) { + /* these should not happen (unless the format of the file changes) */ + return; + } + pos += strlen(read_bytes_str); + process->read_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + pos = strstr(line, write_bytes_str); + if (pos == nullptr) { return; } + pos += strlen(write_bytes_str); + process->write_bytes = strtoull(pos, &endpos, 10); + if (endpos == pos) { return; } + + if (process->previous_read_bytes == ULLONG_MAX) { + process->previous_read_bytes = process->read_bytes; + } + if (process->previous_write_bytes == ULLONG_MAX) { + process->previous_write_bytes = process->write_bytes; + } + + /* store the difference of the byte counts */ + read_bytes = process->read_bytes - process->previous_read_bytes; + write_bytes = process->write_bytes - process->previous_write_bytes; + + /* backup the counts for next time around */ + process->previous_read_bytes = process->read_bytes; + process->previous_write_bytes = process->write_bytes; + + /* store only the difference here... */ + process->read_bytes = read_bytes; + process->write_bytes = write_bytes; + } +#endif /* BUILD_IOSTATS */ + + /****************************************** + * Get process structure for process pid * + ******************************************/ + + /* This function seems to hog all of the CPU time. + * I can't figure out why - it doesn't do much. */ + static void calculate_stats(struct process *process) { + /* compute each process cpu usage by reading /proc//stat */ + process_parse_stat(process); + +#ifdef BUILD_IOSTATS + process_parse_io(process); +#endif /* BUILD_IOSTATS */ + + /* + * Check name against the exclusion list + */ + /* if (process->counted && exclusion_expression && + * !regexec(exclusion_expression, process->name, 0, 0, 0)) + * process->counted = 0; */ + } + + /****************************************** + * Update process table * + ******************************************/ + + static void update_process_table(void) { + DIR *dir; + struct dirent *entry; + + if (!(dir = opendir("/proc"))) { return; } + + info.run_procs = 0; + + /* Get list of processes from /proc directory */ + while ((entry = readdir(dir))) { + pid_t pid; + + if (sscanf(entry->d_name, "%d", &pid) > 0) { + /* compute each process cpu usage */ + calculate_stats(get_process(pid)); + } + } + + closedir(dir); + } + + void get_top_info(void) { + unsigned long long total = 0; + + total = calc_cpu_total(); /* calculate the total of the processor */ + update_process_table(); /* update the table with process list */ + calc_cpu_each(total); /* and then the percentage for each task */ +#ifdef BUILD_IOSTATS + calc_io_each(); /* percentage of I/O for each task */ +#endif /* BUILD_IOSTATS */ + }