Bugfix: memory and thread-deleting problems
[monky] / src / linux.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  * vim: ts=4 sw=4 noet ai cindent syntax=c
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
12  * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
13  * Copyright (c) 2007 Toni Spets
14  * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
15  *      (see AUTHORS)
16  * All rights reserved.
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  * You should have received a copy of the GNU General Public License
28  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
29  *
30  */
31
32 #include "conky.h"
33 #include "logging.h"
34 #include "common.h"
35 #include "linux.h"
36 #include "net_stat.h"
37 #include "diskio.h"
38 #include "temphelper.h"
39 #include <dirent.h>
40 #include <ctype.h>
41 #include <errno.h>
42 #include <limits.h>
43 #include <sys/types.h>
44 #include <sys/sysinfo.h>
45 #include <sys/stat.h>
46 #ifndef HAVE_CLOCK_GETTIME
47 #include <sys/time.h>
48 #endif
49 #include <fcntl.h>
50 #include <unistd.h>
51 // #include <assert.h>
52 #include <time.h>
53 #include "top.h"
54
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <linux/sockios.h>
59 #include <net/if.h>
60 #include <arpa/inet.h>
61 #ifdef _NET_IF_H
62 #define _LINUX_IF_H
63 #endif
64 #include <linux/route.h>
65 #include <math.h>
66 #include <pthread.h>
67
68 /* The following ifdefs were adapted from gkrellm */
69 #include <linux/major.h>
70
71 #if !defined(MD_MAJOR)
72 #define MD_MAJOR 9
73 #endif
74
75 #if !defined(LVM_BLK_MAJOR)
76 #define LVM_BLK_MAJOR 58
77 #endif
78
79 #if !defined(NBD_MAJOR)
80 #define NBD_MAJOR 43
81 #endif
82
83 #ifdef HAVE_IWLIB
84 #include <iwlib.h>
85 #endif
86
87 struct sysfs {
88         int fd;
89         int arg;
90         char devtype[256];
91         char type[64];
92         float factor, offset;
93 };
94
95 #define SHORTSTAT_TEMPL "%*s %llu %llu %llu"
96 #define LONGSTAT_TEMPL "%*s %llu %llu %llu "
97
98 /* This flag tells the linux routines to use the /proc system where possible,
99  * even if other api's are available, e.g. sysinfo() or getloadavg().
100  * the reason for this is to allow for /proc-based distributed monitoring.
101  * using a flag in this manner creates less confusing code. */
102 static int prefer_proc = 0;
103
104 void prepare_update(void)
105 {
106 }
107
108 int update_uptime(void)
109 {
110 #ifdef HAVE_SYSINFO
111         if (!prefer_proc) {
112                 struct sysinfo s_info;
113
114                 sysinfo(&s_info);
115                 info.uptime = (double) s_info.uptime;
116         } else
117 #endif
118         {
119                 static int rep = 0;
120                 FILE *fp;
121
122                 if (!(fp = open_file("/proc/uptime", &rep))) {
123                         info.uptime = 0.0;
124                         return 0;
125                 }
126                 fscanf(fp, "%lf", &info.uptime);
127                 fclose(fp);
128         }
129         return 0;
130 }
131
132 int check_mount(char *s)
133 {
134         int ret = 0;
135         FILE *mtab = fopen("/etc/mtab", "r");
136
137         if (mtab) {
138                 char buf1[256], buf2[128];
139
140                 while (fgets(buf1, 256, mtab)) {
141                         sscanf(buf1, "%*s %128s", buf2);
142                         if (!strcmp(s, buf2)) {
143                                 ret = 1;
144                                 break;
145                         }
146                 }
147                 fclose(mtab);
148         } else {
149                 NORM_ERR("Could not open mtab");
150         }
151         return ret;
152 }
153
154 /* these things are also in sysinfo except Buffers:
155  * (that's why I'm reading them from proc) */
156
157 int update_meminfo(void)
158 {
159         FILE *meminfo_fp;
160         static int rep = 0;
161
162         /* unsigned int a; */
163         char buf[256];
164
165         info.mem = info.memmax = info.swap = info.swapfree = info.swapmax = info.bufmem =
166                 info.buffers = info.cached = info.memfree = info.memeasyfree = 0;
167
168         if (!(meminfo_fp = open_file("/proc/meminfo", &rep))) {
169                 return 0;
170         }
171
172         while (!feof(meminfo_fp)) {
173                 if (fgets(buf, 255, meminfo_fp) == NULL) {
174                         break;
175                 }
176
177                 if (strncmp(buf, "MemTotal:", 9) == 0) {
178                         sscanf(buf, "%*s %llu", &info.memmax);
179                 } else if (strncmp(buf, "MemFree:", 8) == 0) {
180                         sscanf(buf, "%*s %llu", &info.memfree);
181                 } else if (strncmp(buf, "SwapTotal:", 10) == 0) {
182                         sscanf(buf, "%*s %llu", &info.swapmax);
183                 } else if (strncmp(buf, "SwapFree:", 9) == 0) {
184                         sscanf(buf, "%*s %llu", &info.swapfree);
185                 } else if (strncmp(buf, "Buffers:", 8) == 0) {
186                         sscanf(buf, "%*s %llu", &info.buffers);
187                 } else if (strncmp(buf, "Cached:", 7) == 0) {
188                         sscanf(buf, "%*s %llu", &info.cached);
189                 }
190         }
191
192         info.mem = info.memmax - info.memfree;
193         info.memeasyfree = info.memfree;
194         info.swap = info.swapmax - info.swapfree;
195
196         info.bufmem = info.cached + info.buffers;
197
198         fclose(meminfo_fp);
199         return 0;
200 }
201
202 int get_laptop_mode(void)
203 {
204         FILE *fp;
205         int val = -1;
206
207         if ((fp = fopen("/proc/sys/vm/laptop_mode", "r")) != NULL)
208                 fscanf(fp, "%d\n", &val);
209         fclose(fp);
210         return val;
211 }
212
213 /* my system says:
214  * # cat /sys/block/sda/queue/scheduler
215  * noop [anticipatory] cfq
216  */
217 char *get_ioscheduler(char *disk)
218 {
219         FILE *fp;
220         char buf[128];
221
222         if (!disk)
223                 return strndup("n/a", text_buffer_size);
224
225         snprintf(buf, 127, "/sys/block/%s/queue/scheduler", disk);
226         if ((fp = fopen(buf, "r")) == NULL) {
227                 return strndup("n/a", text_buffer_size);
228         }
229         while (!feof(fp)) {
230                 fscanf(fp, "%127s", buf);
231                 if (buf[0] == '[') {
232                         buf[strlen(buf) - 1] = '\0';
233                         fclose(fp);
234                         return strndup(buf + 1, text_buffer_size);
235                 }
236         }
237         fclose(fp);
238         return strndup("n/a", text_buffer_size);
239 }
240
241 static struct {
242         char *iface;
243         char *ip;
244         int count;
245 } gw_info;
246
247 #define COND_FREE(x) if(x) free(x); x = 0
248 #define SAVE_SET_STRING(x, y) \
249         if (x && strcmp((char *)x, (char *)y)) { \
250                 free(x); \
251                 x = strndup("multiple", text_buffer_size); \
252         } else if (!x) { \
253                 x = strndup(y, text_buffer_size); \
254         }
255
256 void update_gateway_info_failure(const char *reason)
257 {
258         if(reason != NULL) {
259                 perror(reason);
260         }
261         //2 pointers to 1 location causes a crash when we try to free them both
262         gw_info.iface = strndup("failed", text_buffer_size);
263         gw_info.ip = strndup("failed", text_buffer_size);
264 }
265
266
267 /* Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT */
268 #define RT_ENTRY_FORMAT "%63s %lx %lx %x %*d %*d %*d %lx %*d %*d %*d\n"
269
270 int update_gateway_info(void)
271 {
272         FILE *fp;
273         struct in_addr ina;
274         char iface[64];
275         unsigned long dest, gate, mask;
276         unsigned int flags;
277
278         COND_FREE(gw_info.iface);
279         COND_FREE(gw_info.ip);
280         gw_info.count = 0;
281
282         if ((fp = fopen("/proc/net/route", "r")) == NULL) {
283                 update_gateway_info_failure("fopen()");
284                 return 0;
285         }
286
287         /* skip over the table header line, which is always present */
288         fscanf(fp, "%*[^\n]\n");
289
290         while (!feof(fp)) {
291                 if(fscanf(fp, RT_ENTRY_FORMAT,
292                           iface, &dest, &gate, &flags, &mask) != 5) {
293                         update_gateway_info_failure("fscanf()");
294                         break;
295                 }
296                 if (!(dest || mask) && ((flags & RTF_GATEWAY) || !gate) ) {
297                         gw_info.count++;
298                         SAVE_SET_STRING(gw_info.iface, iface)
299                         ina.s_addr = gate;
300                         SAVE_SET_STRING(gw_info.ip, inet_ntoa(ina))
301                 }
302         }
303         fclose(fp);
304         return 0;
305 }
306
307 void free_gateway_info(void)
308 {
309         if (gw_info.iface)
310                 free(gw_info.iface);
311         if (gw_info.ip)
312                 free(gw_info.ip);
313         memset(&gw_info, 0, sizeof(gw_info));
314 }
315
316 int gateway_exists(void)
317 {
318         return !!gw_info.count;
319 }
320
321 void print_gateway_iface(char *p, int p_max_size)
322 {
323         snprintf(p, p_max_size, "%s", gw_info.iface);
324 }
325
326 void print_gateway_ip(char *p, int p_max_size)
327 {
328         snprintf(p, p_max_size, "%s", gw_info.ip);
329 }
330
331 int update_net_stats(void)
332 {
333         FILE *net_dev_fp;
334         static int rep = 0;
335         static char first = 1;
336
337         // FIXME: arbitrary size chosen to keep code simple.
338         int i, i2;
339         unsigned int curtmp1, curtmp2;
340         unsigned int k;
341         struct ifconf conf;
342         char buf[256];
343         double delta;
344
345 #ifdef HAVE_IWLIB
346         // wireless info variables
347         int skfd, has_bitrate = 0;
348         struct wireless_info *winfo;
349         struct iwreq wrq;
350 #endif
351
352         /* get delta */
353         delta = current_update_time - last_update_time;
354         if (delta <= 0.0001) {
355                 return 0;
356         }
357
358         /* open file and ignore first two lines */
359         if (!(net_dev_fp = open_file("/proc/net/dev", &rep))) {
360                 clear_net_stats();
361                 return 0;
362         }
363
364         fgets(buf, 255, net_dev_fp);    /* garbage */
365         fgets(buf, 255, net_dev_fp);    /* garbage (field names) */
366
367         /* read each interface */
368         for (i2 = 0; i2 < MAX_NET_INTERFACES; i2++) {
369                 struct net_stat *ns;
370                 char *s, *p;
371                 char temp_addr[18];
372                 long long r, t, last_recv, last_trans;
373
374                 if (fgets(buf, 255, net_dev_fp) == NULL) {
375                         break;
376                 }
377                 p = buf;
378                 while (isspace((int) *p)) {
379                         p++;
380                 }
381
382                 s = p;
383
384                 while (*p && *p != ':') {
385                         p++;
386                 }
387                 if (*p == '\0') {
388                         continue;
389                 }
390                 *p = '\0';
391                 p++;
392
393                 ns = get_net_stat(s, NULL, NULL);
394                 ns->up = 1;
395                 memset(&(ns->addr.sa_data), 0, 14);
396
397                 memset(ns->addrs, 0, 17 * MAX_NET_INTERFACES + 1); /* Up to 17 chars per ip, max MAX_NET_INTERFACES interfaces. Nasty memory usage... */
398
399                 last_recv = ns->recv;
400                 last_trans = ns->trans;
401
402                 /* bytes packets errs drop fifo frame compressed multicast|bytes ... */
403                 sscanf(p, "%lld  %*d     %*d  %*d  %*d  %*d   %*d        %*d       %lld",
404                         &r, &t);
405
406                 /* if recv or trans is less than last time, an overflow happened */
407                 if (r < ns->last_read_recv) {
408                         last_recv = 0;
409                 } else {
410                         ns->recv += (r - ns->last_read_recv);
411                 }
412                 ns->last_read_recv = r;
413
414                 if (t < ns->last_read_trans) {
415                         last_trans = 0;
416                 } else {
417                         ns->trans += (t - ns->last_read_trans);
418                 }
419                 ns->last_read_trans = t;
420
421                 /*** ip addr patch ***/
422                 i = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
423
424                 conf.ifc_buf = malloc(sizeof(struct ifreq) * MAX_NET_INTERFACES);
425                 conf.ifc_len = sizeof(struct ifreq) * MAX_NET_INTERFACES;
426                 memset(conf.ifc_buf, 0, conf.ifc_len);
427
428                 ioctl((long) i, SIOCGIFCONF, &conf);
429
430                 for (k = 0; k < conf.ifc_len / sizeof(struct ifreq); k++) {
431                         struct net_stat *ns2;
432
433                         if (!(((struct ifreq *) conf.ifc_buf) + k))
434                                 break;
435
436                         ns2 = get_net_stat(
437                                         ((struct ifreq *) conf.ifc_buf)[k].ifr_ifrn.ifrn_name, NULL, NULL);
438                         ns2->addr = ((struct ifreq *) conf.ifc_buf)[k].ifr_ifru.ifru_addr;
439                         sprintf(temp_addr, "%u.%u.%u.%u, ",
440                                         ns2->addr.sa_data[2] & 255,
441                                         ns2->addr.sa_data[3] & 255,
442                                         ns2->addr.sa_data[4] & 255,
443                                         ns2->addr.sa_data[5] & 255);
444                         if(NULL == strstr(ns2->addrs, temp_addr))
445                                 strncpy(ns2->addrs + strlen(ns2->addrs), temp_addr, 17);
446                 }
447
448                 close((long) i);
449
450                 free(conf.ifc_buf);
451
452                 /*** end ip addr patch ***/
453
454                 if (!first) {
455                         /* calculate speeds */
456                         ns->net_rec[0] = (ns->recv - last_recv) / delta;
457                         ns->net_trans[0] = (ns->trans - last_trans) / delta;
458                 }
459
460                 curtmp1 = 0;
461                 curtmp2 = 0;
462                 // get an average
463 #ifdef HAVE_OPENMP
464 #pragma omp parallel for reduction(+:curtmp1, curtmp2) schedule(dynamic,10)
465 #endif /* HAVE_OPENMP */
466                 for (i = 0; i < info.net_avg_samples; i++) {
467                         curtmp1 = curtmp1 + ns->net_rec[i];
468                         curtmp2 = curtmp2 + ns->net_trans[i];
469                 }
470                 ns->recv_speed = curtmp1 / (double) info.net_avg_samples;
471                 ns->trans_speed = curtmp2 / (double) info.net_avg_samples;
472                 if (info.net_avg_samples > 1) {
473 #ifdef HAVE_OPENMP
474 #pragma omp parallel for schedule(dynamic,10)
475 #endif /* HAVE_OPENMP */
476                         for (i = info.net_avg_samples; i > 1; i--) {
477                                 ns->net_rec[i - 1] = ns->net_rec[i - 2];
478                                 ns->net_trans[i - 1] = ns->net_trans[i - 2];
479                         }
480                 }
481
482 #ifdef HAVE_IWLIB
483                 /* update wireless info */
484                 winfo = malloc(sizeof(struct wireless_info));
485                 memset(winfo, 0, sizeof(struct wireless_info));
486
487                 skfd = iw_sockets_open();
488                 if (iw_get_basic_config(skfd, s, &(winfo->b)) > -1) {
489
490                         // set present winfo variables
491                         if (iw_get_stats(skfd, s, &(winfo->stats),
492                                         &winfo->range, winfo->has_range) >= 0) {
493                                 winfo->has_stats = 1;
494                         }
495                         if (iw_get_range_info(skfd, s, &(winfo->range)) >= 0) {
496                                 winfo->has_range = 1;
497                         }
498                         if (iw_get_ext(skfd, s, SIOCGIWAP, &wrq) >= 0) {
499                                 winfo->has_ap_addr = 1;
500                                 memcpy(&(winfo->ap_addr), &(wrq.u.ap_addr), sizeof(sockaddr));
501                         }
502
503                         // get bitrate
504                         if (iw_get_ext(skfd, s, SIOCGIWRATE, &wrq) >= 0) {
505                                 memcpy(&(winfo->bitrate), &(wrq.u.bitrate), sizeof(iwparam));
506                                 iw_print_bitrate(ns->bitrate, 16, winfo->bitrate.value);
507                                 has_bitrate = 1;
508                         }
509
510                         // get link quality
511                         if (winfo->has_range && winfo->has_stats
512                                         && ((winfo->stats.qual.level != 0)
513                                         || (winfo->stats.qual.updated & IW_QUAL_DBM))) {
514                                 if (!(winfo->stats.qual.updated & IW_QUAL_QUAL_INVALID)) {
515                                         ns->link_qual = winfo->stats.qual.qual;
516                                         ns->link_qual_max = winfo->range.max_qual.qual;
517                                 }
518                         }
519
520                         // get ap mac
521                         if (winfo->has_ap_addr) {
522                                 iw_sawap_ntop(&winfo->ap_addr, ns->ap);
523                         }
524
525                         // get essid
526                         if (winfo->b.has_essid) {
527                                 if (winfo->b.essid_on) {
528                                         snprintf(ns->essid, 32, "%s", winfo->b.essid);
529                                 } else {
530                                         snprintf(ns->essid, 32, "off/any");
531                                 }
532                         }
533
534                         snprintf(ns->mode, 16, "%s", iw_operation_mode[winfo->b.mode]);
535                 }
536                 iw_sockets_close(skfd);
537                 free(winfo);
538 #endif
539         }
540         first = 0;
541
542         fclose(net_dev_fp);
543         return 0;
544 }
545
546 int result;
547
548 int update_total_processes(void)
549 {
550         DIR *dir;
551         struct dirent *entry;
552         int ignore1;
553         char ignore2;
554
555         info.procs = 0;
556         if (!(dir = opendir("/proc"))) {
557                 return 0;
558         }
559         while ((entry = readdir(dir))) {
560                 if (!entry) {
561                         /* Problem reading list of processes */
562                         closedir(dir);
563                         info.procs = 0;
564                         return 0;
565                 }
566                 if (sscanf(entry->d_name, "%d%c", &ignore1, &ignore2) == 1) {
567                         info.procs++;
568                 }
569         }
570         closedir(dir);
571         return 0;
572 }
573
574 int update_threads(void)
575 {
576 #ifdef HAVE_SYSINFO
577         if (!prefer_proc) {
578                 struct sysinfo s_info;
579
580                 sysinfo(&s_info);
581                 info.threads = s_info.procs;
582         } else
583 #endif
584         {
585                 static int rep = 0;
586                 FILE *fp;
587
588                 if (!(fp = open_file("/proc/loadavg", &rep))) {
589                         info.threads = 0;
590                         return 0;
591                 }
592                 fscanf(fp, "%*f %*f %*f %*d/%hu", &info.threads);
593                 fclose(fp);
594         }
595         return 0;
596 }
597
598 #define CPU_SAMPLE_COUNT 15
599 struct cpu_info {
600         unsigned long long cpu_user;
601         unsigned long long cpu_system;
602         unsigned long long cpu_nice;
603         unsigned long long cpu_idle;
604         unsigned long long cpu_iowait;
605         unsigned long long cpu_irq;
606         unsigned long long cpu_softirq;
607         unsigned long long cpu_steal;
608         unsigned long long cpu_total;
609         unsigned long long cpu_active_total;
610         unsigned long long cpu_last_total;
611         unsigned long long cpu_last_active_total;
612         double cpu_val[CPU_SAMPLE_COUNT];
613 };
614 static short cpu_setup = 0;
615
616 /* Determine if this kernel gives us "extended" statistics information in
617  * /proc/stat.
618  * Kernels around 2.5 and earlier only reported user, system, nice, and
619  * idle values in proc stat.
620  * Kernels around 2.6 and greater report these PLUS iowait, irq, softirq,
621  * and steal */
622 void determine_longstat(char *buf)
623 {
624         unsigned long long iowait = 0;
625
626         KFLAG_SETOFF(KFLAG_IS_LONGSTAT);
627         /* scanf will either return -1 or 1 because there is only 1 assignment */
628         if (sscanf(buf, "%*s %*d %*d %*d %*d %llu", &iowait) > 0) {
629                 KFLAG_SETON(KFLAG_IS_LONGSTAT);
630         }
631 }
632
633 void get_cpu_count(void)
634 {
635         FILE *stat_fp;
636         static int rep = 0;
637         char buf[256];
638
639         if (info.cpu_usage) {
640                 return;
641         }
642
643         if (!(stat_fp = open_file("/proc/stat", &rep))) {
644                 return;
645         }
646
647         info.cpu_count = 0;
648
649         while (!feof(stat_fp)) {
650                 if (fgets(buf, 255, stat_fp) == NULL) {
651                         break;
652                 }
653
654                 if (strncmp(buf, "cpu", 3) == 0 && isdigit(buf[3])) {
655                         if (info.cpu_count == 0) {
656                                 determine_longstat(buf);
657                         }
658                         info.cpu_count++;
659                 }
660         }
661         info.cpu_usage = malloc((info.cpu_count + 1) * sizeof(float));
662
663         fclose(stat_fp);
664 }
665
666 #define TMPL_LONGSTAT "%*s %llu %llu %llu %llu %llu %llu %llu %llu"
667 #define TMPL_SHORTSTAT "%*s %llu %llu %llu %llu"
668
669 int update_stat(void)
670 {
671         FILE *stat_fp;
672         static int rep = 0;
673         static struct cpu_info *cpu = NULL;
674         char buf[256];
675         int i;
676         unsigned int idx;
677         double curtmp;
678         const char *stat_template = NULL;
679         unsigned int malloc_cpu_size = 0;
680         extern void* global_cpu;
681
682         static pthread_mutex_t last_stat_update_mutex = PTHREAD_MUTEX_INITIALIZER;
683         static double last_stat_update = 0.0;
684
685         /* since we use wrappers for this function, the update machinery
686          * can't eliminate double invocations of this function. Check for
687          * them here, otherwise cpu_usage counters are freaking out. */
688         pthread_mutex_lock(&last_stat_update_mutex);
689         if (last_stat_update == current_update_time) {
690                 pthread_mutex_unlock(&last_stat_update_mutex);
691                 return 0;
692         }
693         last_stat_update = current_update_time;
694         pthread_mutex_unlock(&last_stat_update_mutex);
695
696         /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
697         if (!cpu_setup || !info.cpu_usage) {
698                 get_cpu_count();
699                 cpu_setup = 1;
700         }
701
702         if (!stat_template) {
703                 stat_template =
704                         KFLAG_ISSET(KFLAG_IS_LONGSTAT) ? TMPL_LONGSTAT : TMPL_SHORTSTAT;
705         }
706
707         if (!global_cpu) {
708                 malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
709                 cpu = malloc(malloc_cpu_size);
710                 memset(cpu, 0, malloc_cpu_size);
711                 global_cpu = cpu;
712         }
713
714         if (!(stat_fp = open_file("/proc/stat", &rep))) {
715                 info.run_threads = 0;
716                 if (info.cpu_usage) {
717                         memset(info.cpu_usage, 0, info.cpu_count * sizeof(float));
718                 }
719                 return 0;
720         }
721
722         idx = 0;
723         while (!feof(stat_fp)) {
724                 if (fgets(buf, 255, stat_fp) == NULL) {
725                         break;
726                 }
727
728                 if (strncmp(buf, "procs_running ", 14) == 0) {
729                         sscanf(buf, "%*s %hu", &info.run_threads);
730                 } else if (strncmp(buf, "cpu", 3) == 0) {
731                         double delta;
732                         if (isdigit(buf[3])) {
733                                 idx = atoi(&buf[3]) + 1;
734                         } else {
735                                 idx = 0;
736                         }
737                         sscanf(buf, stat_template, &(cpu[idx].cpu_user),
738                                 &(cpu[idx].cpu_nice), &(cpu[idx].cpu_system),
739                                 &(cpu[idx].cpu_idle), &(cpu[idx].cpu_iowait),
740                                 &(cpu[idx].cpu_irq), &(cpu[idx].cpu_softirq),
741                                 &(cpu[idx].cpu_steal));
742
743                         cpu[idx].cpu_total = cpu[idx].cpu_user + cpu[idx].cpu_nice +
744                                 cpu[idx].cpu_system + cpu[idx].cpu_idle +
745                                 cpu[idx].cpu_iowait + cpu[idx].cpu_irq +
746                                 cpu[idx].cpu_softirq + cpu[idx].cpu_steal;
747
748                         cpu[idx].cpu_active_total = cpu[idx].cpu_total -
749                                 (cpu[idx].cpu_idle + cpu[idx].cpu_iowait);
750
751                         delta = current_update_time - last_update_time;
752
753                         if (delta <= 0.001) {
754                                 break;
755                         }
756
757                         cpu[idx].cpu_val[0] = (cpu[idx].cpu_active_total -
758                                 cpu[idx].cpu_last_active_total) /
759                                 (float) (cpu[idx].cpu_total - cpu[idx].cpu_last_total);
760                         curtmp = 0;
761 #ifdef HAVE_OPENMP
762 #pragma omp parallel for reduction(+:curtmp) schedule(dynamic,10)
763 #endif /* HAVE_OPENMP */
764                         for (i = 0; i < info.cpu_avg_samples; i++) {
765                                 curtmp = curtmp + cpu[idx].cpu_val[i];
766                         }
767                         /* TESTING -- I've removed this, because I don't think it is right.
768                          * You shouldn't divide by the cpu count here ...
769                          * removing for testing */
770                         /* if (idx == 0) {
771                                 info.cpu_usage[idx] = curtmp / info.cpu_avg_samples /
772                                         info.cpu_count;
773                         } else {
774                                 info.cpu_usage[idx] = curtmp / info.cpu_avg_samples;
775                         } */
776                         /* TESTING -- this line replaces the prev. "suspect" if/else */
777                         info.cpu_usage[idx] = curtmp / info.cpu_avg_samples;
778
779                         cpu[idx].cpu_last_total = cpu[idx].cpu_total;
780                         cpu[idx].cpu_last_active_total = cpu[idx].cpu_active_total;
781 #ifdef HAVE_OPENMP
782 #pragma omp parallel for schedule(dynamic,10)
783 #endif /* HAVE_OPENMP */
784                         for (i = info.cpu_avg_samples - 1; i > 0; i--) {
785                                 cpu[idx].cpu_val[i] = cpu[idx].cpu_val[i - 1];
786                         }
787                 }
788         }
789         fclose(stat_fp);
790         return 0;
791 }
792
793 int update_running_processes(void)
794 {
795         update_stat();
796         return 0;
797 }
798
799 int update_cpu_usage(void)
800 {
801         update_stat();
802         return 0;
803 }
804
805 int update_load_average(void)
806 {
807 #ifdef HAVE_GETLOADAVG
808         if (!prefer_proc) {
809                 double v[3];
810
811                 getloadavg(v, 3);
812                 info.loadavg[0] = (float) v[0];
813                 info.loadavg[1] = (float) v[1];
814                 info.loadavg[2] = (float) v[2];
815         } else
816 #endif
817         {
818                 static int rep = 0;
819                 FILE *fp;
820
821                 if (!(fp = open_file("/proc/loadavg", &rep))) {
822                         info.loadavg[0] = info.loadavg[1] = info.loadavg[2] = 0.0;
823                         return 0;
824                 }
825                 fscanf(fp, "%f %f %f", &info.loadavg[0], &info.loadavg[1],
826                         &info.loadavg[2]);
827                 fclose(fp);
828         }
829         return 0;
830 }
831
832 /***********************************************************/
833 /***********************************************************/
834 /***********************************************************/
835
836 static int no_dots(const struct dirent *d)
837 {
838         if (d->d_name[0] == '.') {
839                 return 0;
840         }
841         return 1;
842 }
843
844 static int get_first_file_in_a_directory(const char *dir, char *s, int *rep)
845 {
846         struct dirent **namelist;
847         int i, n;
848
849         n = scandir(dir, &namelist, no_dots, alphasort);
850         if (n < 0) {
851                 if (!rep || !*rep) {
852                         NORM_ERR("scandir for %s: %s", dir, strerror(errno));
853                         if (rep) {
854                                 *rep = 1;
855                         }
856                 }
857                 return 0;
858         } else {
859                 if (n == 0) {
860                         return 0;
861                 }
862
863                 strncpy(s, namelist[0]->d_name, 255);
864                 s[255] = '\0';
865
866 #ifdef HAVE_OPENMP
867 #pragma omp parallel for schedule(dynamic,10)
868 #endif /* HAVE_OPENMP */
869                 for (i = 0; i < n; i++) {
870                         free(namelist[i]);
871                 }
872                 free(namelist);
873
874                 return 1;
875         }
876 }
877
878 static int open_sysfs_sensor(const char *dir, const char *dev, const char *type, int n,
879                 int *divisor, char *devtype)
880 {
881         char path[256];
882         char buf[256];
883         int fd;
884         int divfd;
885
886         memset(buf, 0, sizeof(buf));
887
888         /* if device is NULL or *, get first */
889         if (dev == NULL || strcmp(dev, "*") == 0) {
890                 static int rep = 0;
891
892                 if (!get_first_file_in_a_directory(dir, buf, &rep)) {
893                         return -1;
894                 }
895                 dev = buf;
896         }
897
898         if (strcmp(dir, "/sys/class/hwmon/") == 0) {
899                 if (*buf) {
900                         /* buf holds result from get_first_file_in_a_directory() above,
901                          * e.g. "hwmon0" -- append "/device" */
902                         strcat(buf, "/device");
903                 } else {
904                         /* dev holds device number N as a string,
905                          * e.g. "0", -- convert to "hwmon0/device" */
906                         sprintf(buf, "hwmon%s/device", dev);
907                         dev = buf;
908                 }
909         }
910
911         /* change vol to in, tempf to temp */
912         if (strcmp(type, "vol") == 0) {
913                 type = "in";
914         } else if (strcmp(type, "tempf") == 0) {
915                 type = "temp";
916         }
917
918         /* construct path */
919         snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
920
921         /* first, attempt to open file in /device */
922         fd = open(path, O_RDONLY);
923         if (fd < 0) {
924
925                 /* if it fails, strip the /device from dev and attempt again */
926                 buf[strlen(buf) - 7] = 0;
927                 snprintf(path, 255, "%s%s/%s%d_input", dir, dev, type, n);
928                 fd = open(path, O_RDONLY);
929                 if (fd < 0) {
930                         CRIT_ERR(NULL, NULL, "can't open '%s': %s\nplease check your device or remove this "
931                                          "var from "PACKAGE_NAME, path, strerror(errno));
932                 }
933         }
934
935         strncpy(devtype, path, 255);
936
937         if (strcmp(type, "in") == 0 || strcmp(type, "temp") == 0
938                         || strcmp(type, "tempf") == 0) {
939                 *divisor = 1;
940         } else {
941                 *divisor = 0;
942         }
943         /* fan does not use *_div as a read divisor */
944         if (strcmp("fan", type) == 0) {
945                 return fd;
946         }
947
948         /* test if *_div file exist, open it and use it as divisor */
949         if (strcmp(type, "tempf") == 0) {
950                 snprintf(path, 255, "%s%s/%s%d_div", dir, "one", "two", n);
951         } else {
952                 snprintf(path, 255, "%s%s/%s%d_div", dir, dev, type, n);
953         }
954
955         divfd = open(path, O_RDONLY);
956         if (divfd > 0) {
957                 /* read integer */
958                 char divbuf[64];
959                 int divn;
960
961                 divn = read(divfd, divbuf, 63);
962                 /* should read until n == 0 but I doubt that kernel will give these
963                  * in multiple pieces. :) */
964                 if (divn < 0) {
965                         NORM_ERR("open_sysfs_sensor(): can't read from sysfs");
966                 } else {
967                         divbuf[divn] = '\0';
968                         *divisor = atoi(divbuf);
969                 }
970                 close(divfd);
971         }
972
973         return fd;
974 }
975
976 static double get_sysfs_info(int *fd, int divisor, char *devtype, char *type)
977 {
978         int val = 0;
979
980         if (*fd <= 0) {
981                 return 0;
982         }
983
984         lseek(*fd, 0, SEEK_SET);
985
986         /* read integer */
987         {
988                 char buf[64];
989                 int n;
990                 n = read(*fd, buf, 63);
991                 /* should read until n == 0 but I doubt that kernel will give these
992                  * in multiple pieces. :) */
993                 if (n < 0) {
994                         NORM_ERR("get_sysfs_info(): read from %s failed\n", devtype);
995                 } else {
996                         buf[n] = '\0';
997                         val = atoi(buf);
998                 }
999         }
1000
1001         close(*fd);
1002         /* open file */
1003         *fd = open(devtype, O_RDONLY);
1004         if (*fd < 0) {
1005                 NORM_ERR("can't open '%s': %s", devtype, strerror(errno));
1006         }
1007
1008         /* My dirty hack for computing CPU value
1009          * Filedil, from forums.gentoo.org */
1010         /* if (strstr(devtype, "temp1_input") != NULL) {
1011                 return -15.096 + 1.4893 * (val / 1000.0);
1012         } */
1013
1014         /* divide voltage and temperature by 1000 */
1015         /* or if any other divisor is given, use that */
1016         if (strcmp(type, "tempf") == 0) {
1017                 if (divisor > 1) {
1018                         return ((val / divisor + 40) * 9.0 / 5) - 40;
1019                 } else if (divisor) {
1020                         return ((val / 1000.0 + 40) * 9.0 / 5) - 40;
1021                 } else {
1022                         return ((val + 40) * 9.0 / 5) - 40;
1023                 }
1024         } else {
1025                 if (divisor > 1) {
1026                         return val / divisor;
1027                 } else if (divisor) {
1028                         return val / 1000.0;
1029                 } else {
1030                         return val;
1031                 }
1032         }
1033 }
1034
1035 #define HWMON_RESET() {\
1036                 buf1[0] = 0; \
1037                 factor = 1.0; \
1038                 offset = 0.0; }
1039
1040 static void parse_sysfs_sensor(struct text_object *obj, const char *arg, const char *path, const char *type)
1041 {
1042         char buf1[64], buf2[64];
1043         float factor, offset;
1044         int n, found = 0;
1045         struct sysfs *sf;
1046
1047         if (sscanf(arg, "%63s %d %f %f", buf2, &n, &factor, &offset) == 4) found = 1; else HWMON_RESET();
1048         if (!found && sscanf(arg, "%63s %63s %d %f %f", buf1, buf2, &n, &factor, &offset) == 5) found = 1; else if (!found) HWMON_RESET();
1049         if (!found && sscanf(arg, "%63s %63s %d", buf1, buf2, &n) == 3) found = 1; else if (!found) HWMON_RESET();
1050         if (!found && sscanf(arg, "%63s %d", buf2, &n) == 2) found = 1; else if (!found) HWMON_RESET();
1051
1052         if (!found) {
1053                 NORM_ERR("i2c failed to parse arguments");
1054                 obj->type = OBJ_text;
1055                 return;
1056         }
1057         DBGP("parsed %s args: '%s' '%s' %d %f %f\n", type, buf1, buf2, n, factor, offset);
1058         sf = malloc(sizeof(struct sysfs));
1059         memset(sf, 0, sizeof(struct sysfs));
1060         sf->fd = open_sysfs_sensor(path, (*buf1) ? buf1 : 0, buf2, n,
1061                         &sf->arg, sf->devtype);
1062         strncpy(sf->type, buf2, 63);
1063         sf->factor = factor;
1064         sf->offset = offset;
1065         obj->data.opaque = sf;
1066 }
1067
1068 #define PARSER_GENERATOR(name, path)                                \
1069 void parse_##name##_sensor(struct text_object *obj, const char *arg) \
1070 {                                                                   \
1071         parse_sysfs_sensor(obj, arg, path, #name);           \
1072 }
1073
1074 PARSER_GENERATOR(i2c, "/sys/bus/i2c/devices/")
1075 PARSER_GENERATOR(hwmon, "/sys/class/hwmon/")
1076 PARSER_GENERATOR(platform, "/sys/bus/platform/devices/")
1077
1078 void print_sysfs_sensor(struct text_object *obj, char *p, int p_max_size)
1079 {
1080         double r;
1081         struct sysfs *sf = obj->data.opaque;
1082
1083         if (!sf)
1084                 return;
1085
1086         r = get_sysfs_info(&sf->fd, sf->arg,
1087                         sf->devtype, sf->type);
1088
1089         r = r * sf->factor + sf->offset;
1090
1091         if (!strncmp(sf->type, "temp", 4)) {
1092                 temp_print(p, p_max_size, r, TEMP_CELSIUS);
1093         } else if (r >= 100.0 || r == 0) {
1094                 snprintf(p, p_max_size, "%d", (int) r);
1095         } else {
1096                 snprintf(p, p_max_size, "%.1f", r);
1097         }
1098 }
1099
1100 void free_sysfs_sensor(struct text_object *obj)
1101 {
1102         struct sysfs *sf = obj->data.opaque;
1103
1104         if (!sf)
1105                 return;
1106
1107         close(sf->fd);
1108         free(obj->data.opaque);
1109         obj->data.opaque = NULL;
1110 }
1111
1112 #define CPUFREQ_PREFIX "/sys/devices/system/cpu"
1113 #define CPUFREQ_POSTFIX "cpufreq/scaling_cur_freq"
1114
1115 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
1116 char get_freq(char *p_client_buffer, size_t client_buffer_size,
1117                 const char *p_format, int divisor, unsigned int cpu)
1118 {
1119         FILE *f;
1120         static int rep = 0;
1121         char frequency[32];
1122         char s[256];
1123         double freq = 0;
1124
1125         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
1126                         || divisor <= 0) {
1127                 return 0;
1128         }
1129
1130         if (!prefer_proc) {
1131                 char current_freq_file[128];
1132
1133                 snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu - 1,
1134                         CPUFREQ_POSTFIX);
1135                 f = fopen(current_freq_file, "r");
1136                 if (f) {
1137                         /* if there's a cpufreq /sys node, read the current frequency from
1138                          * this node and divide by 1000 to get Mhz. */
1139                         if (fgets(s, sizeof(s), f)) {
1140                                 s[strlen(s) - 1] = '\0';
1141                                 freq = strtod(s, NULL);
1142                         }
1143                         fclose(f);
1144                         snprintf(p_client_buffer, client_buffer_size, p_format,
1145                                 (freq / 1000) / divisor);
1146                         return 1;
1147                 }
1148         }
1149
1150         // open the CPU information file
1151         f = open_file("/proc/cpuinfo", &rep);
1152         if (!f) {
1153                 perror(PACKAGE_NAME": Failed to access '/proc/cpuinfo' at get_freq()");
1154                 return 0;
1155         }
1156
1157         // read the file
1158         while (fgets(s, sizeof(s), f) != NULL) {
1159
1160 #if defined(__i386) || defined(__x86_64)
1161                 // and search for the cpu mhz
1162                 if (strncmp(s, "cpu MHz", 7) == 0 && cpu == 0) {
1163 #else
1164 #if defined(__alpha)
1165                 // different on alpha
1166                 if (strncmp(s, "cycle frequency [Hz]", 20) == 0 && cpu == 0) {
1167 #else
1168                 // this is different on ppc for some reason
1169                 if (strncmp(s, "clock", 5) == 0 && cpu == 0) {
1170 #endif // defined(__alpha)
1171 #endif // defined(__i386) || defined(__x86_64)
1172
1173                         // copy just the number
1174                         strcpy(frequency, strchr(s, ':') + 2);
1175 #if defined(__alpha)
1176                         // strip " est.\n"
1177                         frequency[strlen(frequency) - 6] = '\0';
1178                         // kernel reports in Hz
1179                         freq = strtod(frequency, NULL) / 1000000;
1180 #else
1181                         // strip \n
1182                         frequency[strlen(frequency) - 1] = '\0';
1183                         freq = strtod(frequency, NULL);
1184 #endif
1185                         break;
1186                 }
1187                 if (strncmp(s, "processor", 9) == 0) {
1188                         cpu--;
1189                         continue;
1190                 }
1191         }
1192
1193         fclose(f);
1194         snprintf(p_client_buffer, client_buffer_size, p_format,
1195                 (float) freq / divisor);
1196         return 1;
1197 }
1198
1199 #define CPUFREQ_VOLTAGE "cpufreq/scaling_voltages"
1200
1201 /* /sys/devices/system/cpu/cpu0/cpufreq/scaling_voltages looks something
1202  * like this:
1203 # frequency voltage
1204 1800000 1340
1205 1600000 1292
1206 1400000 1100
1207 1200000 988
1208 1000000 1116
1209 800000 1004
1210 600000 988
1211  * Peter Tarjan (ptarjan@citromail.hu) */
1212
1213 /* return cpu voltage in mV (use divisor=1) or V (use divisor=1000) */
1214 static char get_voltage(char *p_client_buffer, size_t client_buffer_size,
1215                 const char *p_format, int divisor, unsigned int cpu)
1216 {
1217         FILE *f;
1218         char s[256];
1219         int freq = 0;
1220         int voltage = 0;
1221         char current_freq_file[128];
1222         int freq_comp = 0;
1223
1224         /* build the voltage file name */
1225         cpu--;
1226         snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
1227                 CPUFREQ_POSTFIX);
1228
1229         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
1230                         || divisor <= 0) {
1231                 return 0;
1232         }
1233
1234         /* read the current cpu frequency from the /sys node */
1235         f = fopen(current_freq_file, "r");
1236         if (f) {
1237                 if (fgets(s, sizeof(s), f)) {
1238                         s[strlen(s) - 1] = '\0';
1239                         freq = strtod(s, NULL);
1240                 }
1241                 fclose(f);
1242         } else {
1243                 fprintf(stderr, PACKAGE_NAME": Failed to access '%s' at ", current_freq_file);
1244                 perror("get_voltage()");
1245                 if (f) {
1246                         fclose(f);
1247                 }
1248                 return 0;
1249         }
1250
1251         snprintf(current_freq_file, 127, "%s/cpu%d/%s", CPUFREQ_PREFIX, cpu,
1252                 CPUFREQ_VOLTAGE);
1253
1254         /* use the current cpu frequency to find the corresponding voltage */
1255         f = fopen(current_freq_file, "r");
1256
1257         if (f) {
1258                 while (!feof(f)) {
1259                         char line[256];
1260
1261                         if (fgets(line, 255, f) == NULL) {
1262                                 break;
1263                         }
1264                         sscanf(line, "%d %d", &freq_comp, &voltage);
1265                         if (freq_comp == freq) {
1266                                 break;
1267                         }
1268                 }
1269                 fclose(f);
1270         } else {
1271                 fprintf(stderr, PACKAGE_NAME": Failed to access '%s' at ", current_freq_file);
1272                 perror("get_voltage()");
1273                 if (f) {
1274                         fclose(f);
1275                 }
1276                 return 0;
1277         }
1278         snprintf(p_client_buffer, client_buffer_size, p_format,
1279                 (float) voltage / divisor);
1280         return 1;
1281 }
1282
1283 void print_voltage_mv(struct text_object *obj, char *p, int p_max_size)
1284 {
1285         static int ok = 1;
1286         if (ok) {
1287                 ok = get_voltage(p, p_max_size, "%.0f", 1, obj->data.i);
1288         }
1289 }
1290
1291 void print_voltage_v(struct text_object *obj, char *p, int p_max_size)
1292 {
1293         static int ok = 1;
1294         if (ok) {
1295                 ok = get_voltage(p, p_max_size, "%'.3f", 1000, obj->data.i);
1296         }
1297 }
1298
1299 #define ACPI_FAN_DIR "/proc/acpi/fan/"
1300
1301 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
1302 {
1303         static int rep = 0;
1304         char buf[256];
1305         char buf2[256];
1306         FILE *fp;
1307
1308         if (!p_client_buffer || client_buffer_size <= 0) {
1309                 return;
1310         }
1311
1312         /* yeah, slow... :/ */
1313         if (!get_first_file_in_a_directory(ACPI_FAN_DIR, buf, &rep)) {
1314                 snprintf(p_client_buffer, client_buffer_size, "no fans?");
1315                 return;
1316         }
1317
1318         snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_FAN_DIR, buf);
1319
1320         fp = open_file(buf2, &rep);
1321         if (!fp) {
1322                 snprintf(p_client_buffer, client_buffer_size,
1323                         "can't open fan's state file");
1324                 return;
1325         }
1326         memset(buf, 0, sizeof(buf));
1327         fscanf(fp, "%*s %99s", buf);
1328         fclose(fp);
1329
1330         snprintf(p_client_buffer, client_buffer_size, "%s", buf);
1331 }
1332
1333 #define SYSFS_AC_ADAPTER_DIR "/sys/class/power_supply"
1334 #define ACPI_AC_ADAPTER_DIR "/proc/acpi/ac_adapter/"
1335 /* Linux 2.6.25 onwards ac adapter info is in
1336    /sys/class/power_supply/AC/
1337    On my system I get the following.
1338      /sys/class/power_supply/AC/uevent:
1339      PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:01/PNP0C09:00/ACPI0003:00
1340      PHYSDEVBUS=acpi
1341      PHYSDEVDRIVER=ac
1342      POWER_SUPPLY_NAME=AC
1343      POWER_SUPPLY_TYPE=Mains
1344      POWER_SUPPLY_ONLINE=1
1345
1346    Update: it seems the folder name is hardware-dependent. We add an aditional adapter
1347    argument, specifying the folder name.
1348
1349    Update: on some systems it's /sys/class/power_supply/ADP1 instead of /sys/class/power_supply/AC
1350 */
1351
1352 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, const char *adapter)
1353 {
1354         static int rep = 0;
1355
1356         char buf[256];
1357         char buf2[256];
1358         struct stat sb;
1359         FILE *fp;
1360
1361         if (!p_client_buffer || client_buffer_size <= 0) {
1362                 return;
1363         }
1364
1365         if(adapter)
1366                 snprintf(buf2, sizeof(buf2), "%s/%s/uevent", SYSFS_AC_ADAPTER_DIR, adapter);
1367         else{
1368                 snprintf(buf2, sizeof(buf2), "%s/AC/uevent", SYSFS_AC_ADAPTER_DIR);
1369                 if(stat(buf2, &sb) == -1) snprintf(buf2, sizeof(buf2), "%s/ADP1/uevent", SYSFS_AC_ADAPTER_DIR);
1370         }
1371         if(stat(buf2, &sb) == 0) fp = open_file(buf2, &rep); else fp = 0;
1372         if (fp) {
1373                 /* sysfs processing */
1374                 while (!feof(fp)) {
1375                         if (fgets(buf, sizeof(buf), fp) == NULL)
1376                                 break;
1377
1378                         if (strncmp(buf, "POWER_SUPPLY_ONLINE=", 20) == 0) {
1379                                 int online = 0;
1380                                 sscanf(buf, "POWER_SUPPLY_ONLINE=%d", &online);
1381                                 snprintf(p_client_buffer, client_buffer_size,
1382                                          "%s-line", (online ? "on" : "off"));
1383                                 break;
1384                         }
1385                 }
1386                 fclose(fp);
1387         } else {
1388                 /* yeah, slow... :/ */
1389                 if (!get_first_file_in_a_directory(ACPI_AC_ADAPTER_DIR, buf, &rep)) {
1390                         snprintf(p_client_buffer, client_buffer_size, "no ac_adapters?");
1391                         return;
1392                 }
1393
1394                 snprintf(buf2, sizeof(buf2), "%s%s/state", ACPI_AC_ADAPTER_DIR, buf);
1395
1396                 fp = open_file(buf2, &rep);
1397                 if (!fp) {
1398                         snprintf(p_client_buffer, client_buffer_size,
1399                                  "No ac adapter found.... where is it?");
1400                         return;
1401                 }
1402                 memset(buf, 0, sizeof(buf));
1403                 fscanf(fp, "%*s %99s", buf);
1404                 fclose(fp);
1405
1406                 snprintf(p_client_buffer, client_buffer_size, "%s", buf);
1407         }
1408 }
1409
1410 /*
1411 /proc/acpi/thermal_zone/THRM/cooling_mode
1412 cooling mode:            active
1413 /proc/acpi/thermal_zone/THRM/polling_frequency
1414 <polling disabled>
1415 /proc/acpi/thermal_zone/THRM/state
1416 state:                   ok
1417 /proc/acpi/thermal_zone/THRM/temperature
1418 temperature:             45 C
1419 /proc/acpi/thermal_zone/THRM/trip_points
1420 critical (S5):           73 C
1421 passive:                 73 C: tc1=4 tc2=3 tsp=40 devices=0xcdf6e6c0
1422 */
1423
1424 #define ACPI_THERMAL_DIR "/proc/acpi/thermal_zone/"
1425 #define ACPI_THERMAL_FORMAT "/proc/acpi/thermal_zone/%s/temperature"
1426
1427 int open_acpi_temperature(const char *name)
1428 {
1429         char path[256];
1430         char buf[256];
1431         int fd;
1432
1433         if (name == NULL || strcmp(name, "*") == 0) {
1434                 static int rep = 0;
1435
1436                 if (!get_first_file_in_a_directory(ACPI_THERMAL_DIR, buf, &rep)) {
1437                         return -1;
1438                 }
1439                 name = buf;
1440         }
1441
1442         snprintf(path, 255, ACPI_THERMAL_FORMAT, name);
1443
1444         fd = open(path, O_RDONLY);
1445         if (fd < 0) {
1446                 NORM_ERR("can't open '%s': %s", path, strerror(errno));
1447         }
1448
1449         return fd;
1450 }
1451
1452 static double last_acpi_temp;
1453 static double last_acpi_temp_time;
1454
1455 double get_acpi_temperature(int fd)
1456 {
1457         if (fd <= 0) {
1458                 return 0;
1459         }
1460
1461         /* don't update acpi temperature too often */
1462         if (current_update_time - last_acpi_temp_time < 11.32) {
1463                 return last_acpi_temp;
1464         }
1465         last_acpi_temp_time = current_update_time;
1466
1467         /* seek to beginning */
1468         lseek(fd, 0, SEEK_SET);
1469
1470         /* read */
1471         {
1472                 char buf[256];
1473                 int n;
1474
1475                 n = read(fd, buf, 255);
1476                 if (n < 0) {
1477                         NORM_ERR("can't read fd %d: %s", fd, strerror(errno));
1478                 } else {
1479                         buf[n] = '\0';
1480                         sscanf(buf, "temperature: %lf", &last_acpi_temp);
1481                 }
1482         }
1483
1484         return last_acpi_temp;
1485 }
1486
1487 /*
1488 hipo@lepakko hipo $ cat /proc/acpi/battery/BAT1/info
1489 present:                 yes
1490 design capacity:         4400 mAh
1491 last full capacity:      4064 mAh
1492 battery technology:      rechargeable
1493 design voltage:          14800 mV
1494 design capacity warning: 300 mAh
1495 design capacity low:     200 mAh
1496 capacity granularity 1:  32 mAh
1497 capacity granularity 2:  32 mAh
1498 model number:            02KT
1499 serial number:           16922
1500 battery type:            LION
1501 OEM info:                SANYO
1502 */
1503
1504 /*
1505 hipo@lepakko conky $ cat /proc/acpi/battery/BAT1/state
1506 present:                 yes
1507 capacity state:          ok
1508 charging state:          unknown
1509 present rate:            0 mA
1510 remaining capacity:      4064 mAh
1511 present voltage:         16608 mV
1512 */
1513
1514 /*
1515 2213<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm
1516 2213<@jupet�kellari��> 1.16 1.2 0x03 0x01 0xff 0x10 -1% -1 ?
1517 2213<@jupet�kellari��> (-1 ollee ei akkua kiinni, koska akku on p�yd�ll�)
1518 2214<@jupet�kellari��> jupet@lagi-unstable:~$ cat /proc/apm
1519 2214<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 98% -1 ?
1520
1521 2238<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 100% -1 ? ilman verkkovirtaa
1522 2239<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x00 0x01 99% -1 ? verkkovirralla
1523
1524 2240<@jupet�kellari��> 1.16 1.2 0x03 0x01 0x03 0x09 100% -1 ? verkkovirralla ja monitori p��ll�
1525 2241<@jupet�kellari��> 1.16 1.2 0x03 0x00 0x00 0x01 99% -1 ? monitori p��ll� mutta ilman verkkovirtaa
1526 */
1527
1528 /* Kapil Hari Paranjape <kapil@imsc.res.in>
1529   Linux 2.6.24 onwards battery info is in
1530   /sys/class/power_supply/BAT0/
1531   On my system I get the following.
1532         /sys/class/power_supply/BAT0/uevent:
1533         PHYSDEVPATH=/devices/LNXSYSTM:00/device:00/PNP0A03:00/device:01/PNP0C09:00/PNP0C0A:00
1534         PHYSDEVBUS=acpi
1535         PHYSDEVDRIVER=battery
1536         POWER_SUPPLY_NAME=BAT0
1537         POWER_SUPPLY_TYPE=Battery
1538         POWER_SUPPLY_STATUS=Discharging
1539         POWER_SUPPLY_PRESENT=1
1540         POWER_SUPPLY_TECHNOLOGY=Li-ion
1541         POWER_SUPPLY_VOLTAGE_MIN_DESIGN=10800000
1542         POWER_SUPPLY_VOLTAGE_NOW=10780000
1543         POWER_SUPPLY_CURRENT_NOW=13970000
1544         POWER_SUPPLY_ENERGY_FULL_DESIGN=47510000
1545         POWER_SUPPLY_ENERGY_FULL=27370000
1546         POWER_SUPPLY_ENERGY_NOW=11810000
1547         POWER_SUPPLY_MODEL_NAME=IBM-92P1060
1548         POWER_SUPPLY_MANUFACTURER=Panasonic
1549   On some systems POWER_SUPPLY_ENERGY_* is replaced by POWER_SUPPLY_CHARGE_*
1550 */
1551
1552 #define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply"
1553 #define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery"
1554 #define APM_PATH "/proc/apm"
1555 #define MAX_BATTERY_COUNT 4
1556
1557 static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1558 static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1559 static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1560
1561 static int batteries_initialized = 0;
1562 static char batteries[MAX_BATTERY_COUNT][32];
1563
1564 static int acpi_last_full[MAX_BATTERY_COUNT];
1565 static int acpi_design_capacity[MAX_BATTERY_COUNT];
1566
1567 /* e.g. "charging 75%" */
1568 static char last_battery_str[MAX_BATTERY_COUNT][64];
1569 /* e.g. "3h 15m" */
1570 static char last_battery_time_str[MAX_BATTERY_COUNT][64];
1571
1572 static double last_battery_time[MAX_BATTERY_COUNT];
1573
1574 static int last_battery_perct[MAX_BATTERY_COUNT];
1575 static double last_battery_perct_time[MAX_BATTERY_COUNT];
1576
1577 void init_batteries(void)
1578 {
1579         int idx;
1580
1581         if (batteries_initialized) {
1582                 return;
1583         }
1584 #ifdef HAVE_OPENMP
1585 #pragma omp parallel for schedule(dynamic,10)
1586 #endif /* HAVE_OPENMP */
1587         for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1588                 batteries[idx][0] = '\0';
1589         }
1590         batteries_initialized = 1;
1591 }
1592
1593 int get_battery_idx(const char *bat)
1594 {
1595         int idx;
1596
1597         for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1598                 if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) {
1599                         break;
1600                 }
1601         }
1602
1603         /* if not found, enter a new entry */
1604         if (!strlen(batteries[idx])) {
1605                 snprintf(batteries[idx], 31, "%s", bat);
1606         }
1607
1608         return idx;
1609 }
1610
1611 void set_return_value(char *buffer, unsigned int n, int item, int idx);
1612
1613 void get_battery_stuff(char *buffer, unsigned int n, const char *bat, int item)
1614 {
1615         static int idx, rep = 0, rep1 = 0, rep2 = 0;
1616         char acpi_path[128];
1617         char sysfs_path[128];
1618
1619         snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
1620         snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
1621
1622         init_batteries();
1623
1624         idx = get_battery_idx(bat);
1625
1626         /* don't update battery too often */
1627         if (current_update_time - last_battery_time[idx] < 29.5) {
1628                 set_return_value(buffer, n, item, idx);
1629                 return;
1630         }
1631
1632         last_battery_time[idx] = current_update_time;
1633
1634         memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx]));
1635         memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx]));
1636
1637         /* first try SYSFS if that fails try ACPI */
1638
1639         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1640                 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
1641         }
1642
1643         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1644                 acpi_bat_fp[idx] = open_file(acpi_path, &rep1);
1645         }
1646
1647         if (sysfs_bat_fp[idx] != NULL) {
1648                 /* SYSFS */
1649                 int present_rate = -1;
1650                 int remaining_capacity = -1;
1651                 char charging_state[64];
1652                 char present[4];
1653
1654                 strcpy(charging_state, "unknown");
1655
1656                 while (!feof(sysfs_bat_fp[idx])) {
1657                         char buf[256];
1658                         if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
1659                                 break;
1660
1661                         /* let's just hope units are ok */
1662                         if (strncmp (buf, "POWER_SUPPLY_PRESENT=1", 22) == 0)
1663                                 strcpy(present, "yes");
1664                         else if (strncmp (buf, "POWER_SUPPLY_PRESENT=0", 22) == 0)
1665                                 strcpy(present, "no");
1666                         else if (strncmp (buf, "POWER_SUPPLY_STATUS=", 20) == 0)
1667                                 sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state);
1668                         /* present_rate is not the same as the
1669                         current flowing now but it is the same value
1670                         which was used in the past. so we continue
1671                         the tradition! */
1672                         else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0)
1673                                 sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate);
1674                         else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0)
1675                                 sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
1676                         else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0)
1677                                 sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]);
1678                         else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0)
1679                                 sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
1680                         else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0)
1681                                 sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]);
1682                 }
1683
1684                 fclose(sysfs_bat_fp[idx]);
1685                 sysfs_bat_fp[idx] = NULL;
1686
1687                 /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
1688                 if (remaining_capacity > acpi_last_full[idx])
1689                         acpi_last_full[idx] = remaining_capacity;  /* normalize to 100% */
1690
1691                 /* not present */
1692                 if (strcmp(present, "No") == 0) {
1693                         strncpy(last_battery_str[idx], "not present", 64);
1694                 }
1695                 /* charging */
1696                 else if (strcmp(charging_state, "Charging") == 0) {
1697                         if (acpi_last_full[idx] != 0 && present_rate > 0) {
1698                                 /* e.g. charging 75% */
1699                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %i%%",
1700                                         (int) (((float) remaining_capacity / acpi_last_full[idx]) * 100 ));
1701                                 /* e.g. 2h 37m */
1702                                 format_seconds(last_battery_time_str[idx], sizeof(last_battery_time_str[idx])-1,
1703                                               (long) (((float)(acpi_last_full[idx] - remaining_capacity) / present_rate) * 3600));
1704                         } else if (acpi_last_full[idx] != 0 && present_rate <= 0) {
1705                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %d%%",
1706                                         (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1707                                 snprintf(last_battery_time_str[idx],
1708                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1709                         } else {
1710                                 strncpy(last_battery_str[idx], "charging", sizeof(last_battery_str[idx])-1);
1711                                 snprintf(last_battery_time_str[idx],
1712                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1713                         }
1714                 }
1715                 /* discharging */
1716                 else if (strncmp(charging_state, "Discharging", 64) == 0) {
1717                         if (present_rate > 0) {
1718                                 /* e.g. discharging 35% */
1719                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "discharging %i%%",
1720                                         (int) (((float) remaining_capacity / acpi_last_full[idx]) * 100 ));
1721                                 /* e.g. 1h 12m */
1722                                 format_seconds(last_battery_time_str[idx], sizeof(last_battery_time_str[idx])-1,
1723                                               (long) (((float) remaining_capacity / present_rate) * 3600));
1724                         } else if (present_rate == 0) { /* Thanks to Nexox for this one */
1725                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "full");
1726                                 snprintf(last_battery_time_str[idx],
1727                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1728                         } else {
1729                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1,
1730                                         "discharging %d%%",
1731                                         (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1732                                 snprintf(last_battery_time_str[idx],
1733                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1734                         }
1735                 }
1736                 /* charged */
1737                 /* thanks to Lukas Zapletal <lzap@seznam.cz> */
1738                 else if (strncmp(charging_state, "Charged", 64) == 0 || strncmp(charging_state, "Full", 64) == 0) {
1739                                 /* Below happens with the second battery on my X40,
1740                                  * when the second one is empty and the first one
1741                                  * being charged. */
1742                                 if (remaining_capacity == 0)
1743                                         strcpy(last_battery_str[idx], "empty");
1744                                 else
1745                                         strcpy(last_battery_str[idx], "charged");
1746                 }
1747                 /* unknown, probably full / AC */
1748                 else {
1749                         if (acpi_last_full[idx] != 0
1750                             && remaining_capacity != acpi_last_full[idx])
1751                                 snprintf(last_battery_str[idx], 64, "unknown %d%%",
1752                                         (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1753                         else
1754                                 strncpy(last_battery_str[idx], "AC", 64);
1755                 }
1756         } else if (acpi_bat_fp[idx] != NULL) {
1757                 /* ACPI */
1758                 int present_rate = -1;
1759                 int remaining_capacity = -1;
1760                 char charging_state[64];
1761                 char present[4];
1762
1763                 /* read last full capacity if it's zero */
1764                 if (acpi_last_full[idx] == 0) {
1765                         static int rep3 = 0;
1766                         char path[128];
1767                         FILE *fp;
1768
1769                         snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
1770                         fp = open_file(path, &rep3);
1771                         if (fp != NULL) {
1772                                 while (!feof(fp)) {
1773                                         char b[256];
1774
1775                                         if (fgets(b, 256, fp) == NULL) {
1776                                                 break;
1777                                         }
1778                                         if (sscanf(b, "last full capacity: %d",
1779                                                                 &acpi_last_full[idx]) != 0) {
1780                                                 break;
1781                                         }
1782                                 }
1783
1784                                 fclose(fp);
1785                         }
1786                 }
1787
1788                 fseek(acpi_bat_fp[idx], 0, SEEK_SET);
1789
1790                 strcpy(charging_state, "unknown");
1791
1792                 while (!feof(acpi_bat_fp[idx])) {
1793                         char buf[256];
1794
1795                         if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
1796                                 break;
1797                         }
1798
1799                         /* let's just hope units are ok */
1800                         if (strncmp(buf, "present:", 8) == 0) {
1801                                 sscanf(buf, "present: %4s", present);
1802                         } else if (strncmp(buf, "charging state:", 15) == 0) {
1803                                 sscanf(buf, "charging state: %63s", charging_state);
1804                         } else if (strncmp(buf, "present rate:", 13) == 0) {
1805                                 sscanf(buf, "present rate: %d", &present_rate);
1806                         } else if (strncmp(buf, "remaining capacity:", 19) == 0) {
1807                                 sscanf(buf, "remaining capacity: %d", &remaining_capacity);
1808                         }
1809                 }
1810                 /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
1811                 if (remaining_capacity > acpi_last_full[idx]) {
1812                         /* normalize to 100% */
1813                         acpi_last_full[idx] = remaining_capacity;
1814                 }
1815
1816                 /* not present */
1817                 if (strcmp(present, "no") == 0) {
1818                         strncpy(last_battery_str[idx], "not present", 64);
1819                         /* charging */
1820                 } else if (strcmp(charging_state, "charging") == 0) {
1821                         if (acpi_last_full[idx] != 0 && present_rate > 0) {
1822                                 /* e.g. charging 75% */
1823                                 snprintf(last_battery_str[idx],
1824                                                 sizeof(last_battery_str[idx]) - 1, "charging %i%%",
1825                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1826                                 /* e.g. 2h 37m */
1827                                 format_seconds(last_battery_time_str[idx],
1828                                                 sizeof(last_battery_time_str[idx]) - 1,
1829                                                 (long) (((acpi_last_full[idx] - remaining_capacity) *
1830                                                                 3600) / present_rate));
1831                         } else if (acpi_last_full[idx] != 0 && present_rate <= 0) {
1832                                 snprintf(last_battery_str[idx],
1833                                                 sizeof(last_battery_str[idx]) - 1, "charging %d%%",
1834                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1835                                 snprintf(last_battery_time_str[idx],
1836                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1837                         } else {
1838                                 strncpy(last_battery_str[idx], "charging",
1839                                                 sizeof(last_battery_str[idx]) - 1);
1840                                 snprintf(last_battery_time_str[idx],
1841                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1842                         }
1843                         /* discharging */
1844                 } else if (strncmp(charging_state, "discharging", 64) == 0) {
1845                         if (present_rate > 0) {
1846                                 /* e.g. discharging 35% */
1847                                 snprintf(last_battery_str[idx],
1848                                                 sizeof(last_battery_str[idx]) - 1, "discharging %i%%",
1849                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1850                                 /* e.g. 1h 12m */
1851                                 format_seconds(last_battery_time_str[idx],
1852                                                 sizeof(last_battery_time_str[idx]) - 1,
1853                                                 (long) ((remaining_capacity * 3600) / present_rate));
1854                         } else if (present_rate == 0) { /* Thanks to Nexox for this one */
1855                                 snprintf(last_battery_str[idx],
1856                                                 sizeof(last_battery_str[idx]) - 1, "full");
1857                                 snprintf(last_battery_time_str[idx],
1858                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1859                         } else {
1860                                 snprintf(last_battery_str[idx],
1861                                                 sizeof(last_battery_str[idx]) - 1, "discharging %d%%",
1862                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1863                                 snprintf(last_battery_time_str[idx],
1864                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1865                         }
1866                         /* charged */
1867                 } else if (strncmp(charging_state, "charged", 64) == 0) {
1868                         /* thanks to Lukas Zapletal <lzap@seznam.cz> */
1869                         /* Below happens with the second battery on my X40,
1870                          * when the second one is empty and the first one being charged. */
1871                         if (remaining_capacity == 0) {
1872                                 strcpy(last_battery_str[idx], "empty");
1873                         } else {
1874                                 strcpy(last_battery_str[idx], "charged");
1875                         }
1876                         /* unknown, probably full / AC */
1877                 } else {
1878                         if (strncmp(charging_state, "Full", 64) == 0) {
1879                                 strncpy(last_battery_str[idx], "full", 64);
1880                         } else if (acpi_last_full[idx] != 0
1881                                         && remaining_capacity != acpi_last_full[idx]) {
1882                                 snprintf(last_battery_str[idx], 64, "unknown %d%%",
1883                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1884                         } else {
1885                                 strncpy(last_battery_str[idx], "AC", 64);
1886                         }
1887                 }
1888                 fclose(acpi_bat_fp[idx]);
1889                 acpi_bat_fp[idx] = NULL;
1890         } else {
1891                 /* APM */
1892                 if (apm_bat_fp[idx] == NULL) {
1893                         apm_bat_fp[idx] = open_file(APM_PATH, &rep2);
1894                 }
1895
1896                 if (apm_bat_fp[idx] != NULL) {
1897                         unsigned int ac, status, flag;
1898                         int life;
1899
1900                         fscanf(apm_bat_fp[idx], "%*s %*s %*x %x   %x       %x     %d%%",
1901                                 &ac, &status, &flag, &life);
1902
1903                         if (life == -1) {
1904                                 /* could check now that there is ac */
1905                                 snprintf(last_battery_str[idx], 64, "AC");
1906
1907                         /* could check that status == 3 here? */
1908                         } else if (ac && life != 100) {
1909                                 snprintf(last_battery_str[idx], 64, "charging %d%%", life);
1910                         } else {
1911                                 snprintf(last_battery_str[idx], 64, "%d%%", life);
1912                         }
1913
1914                         /* it seemed to buffer it so file must be closed (or could use
1915                          * syscalls directly but I don't feel like coding it now) */
1916                         fclose(apm_bat_fp[idx]);
1917                         apm_bat_fp[idx] = NULL;
1918                 }
1919         }
1920         set_return_value(buffer, n, item, idx);
1921 }
1922
1923 void set_return_value(char *buffer, unsigned int n, int item, int idx)
1924 {
1925         switch (item) {
1926                 case BATTERY_STATUS:
1927                         snprintf(buffer, n, "%s", last_battery_str[idx]);
1928                         break;
1929                 case BATTERY_TIME:
1930                         snprintf(buffer, n, "%s", last_battery_time_str[idx]);
1931                         break;
1932                 default:
1933                         break;
1934         }
1935 }
1936
1937 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
1938 {
1939         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
1940         if (0 == strncmp("charging", buffer, 8)) {
1941                 buffer[0] = 'C';
1942                 memmove(buffer + 1, buffer + 8, n - 8);
1943         } else if (0 == strncmp("discharging", buffer, 11)) {
1944                 buffer[0] = 'D';
1945                 memmove(buffer + 1, buffer + 11, n - 11);
1946         } else if (0 == strncmp("charged", buffer, 7)) {
1947                 buffer[0] = 'F';
1948                 memmove(buffer + 1, buffer + 7, n - 7);
1949         } else if (0 == strncmp("not present", buffer, 11)) {
1950                 buffer[0] = 'N';
1951                 memmove(buffer + 1, buffer + 11, n - 11);
1952         } else if (0 == strncmp("empty", buffer, 5)) {
1953                 buffer[0] = 'E';
1954                 memmove(buffer + 1, buffer + 5, n - 5);
1955         } else if (0 != strncmp("AC", buffer, 2)) {
1956                 buffer[0] = 'U';
1957                 memmove(buffer + 1, buffer + 11, n - 11);
1958         }
1959 }
1960
1961 int get_battery_perct(const char *bat)
1962 {
1963         static int rep = 0;
1964         int idx;
1965         char acpi_path[128];
1966         char sysfs_path[128];
1967         int remaining_capacity = -1;
1968
1969         snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
1970         snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
1971
1972         init_batteries();
1973
1974         idx = get_battery_idx(bat);
1975
1976         /* don't update battery too often */
1977         if (current_update_time - last_battery_perct_time[idx] < 30) {
1978                 return last_battery_perct[idx];
1979         }
1980         last_battery_perct_time[idx] = current_update_time;
1981
1982         /* Only check for SYSFS or ACPI */
1983
1984         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1985                 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
1986                 rep = 0;
1987         }
1988
1989         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1990                 acpi_bat_fp[idx] = open_file(acpi_path, &rep);
1991         }
1992
1993         if (sysfs_bat_fp[idx] != NULL) {
1994                 /* SYSFS */
1995                 while (!feof(sysfs_bat_fp[idx])) {
1996                         char buf[256];
1997                         if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
1998                                 break;
1999
2000                         if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) {
2001                                 sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
2002                         } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=",25) == 0) {
2003                                 sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]);
2004                         } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) {
2005                                 sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
2006                         } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=",25) == 0) {
2007                                 sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]);
2008                         }
2009                 }
2010
2011                 fclose(sysfs_bat_fp[idx]);
2012                 sysfs_bat_fp[idx] = NULL;
2013
2014         } else if (acpi_bat_fp[idx] != NULL) {
2015                 /* ACPI */
2016                 /* read last full capacity if it's zero */
2017                 if (acpi_design_capacity[idx] == 0) {
2018                         static int rep2;
2019                         char path[128];
2020                         FILE *fp;
2021
2022                         snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
2023                         fp = open_file(path, &rep2);
2024                         if (fp != NULL) {
2025                                 while (!feof(fp)) {
2026                                         char b[256];
2027
2028                                         if (fgets(b, 256, fp) == NULL) {
2029                                                 break;
2030                                         }
2031                                         if (sscanf(b, "last full capacity: %d",
2032                                                                 &acpi_design_capacity[idx]) != 0) {
2033                                                 break;
2034                                         }
2035                                 }
2036                                 fclose(fp);
2037                         }
2038                 }
2039
2040                 fseek(acpi_bat_fp[idx], 0, SEEK_SET);
2041
2042                 while (!feof(acpi_bat_fp[idx])) {
2043                         char buf[256];
2044
2045                         if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
2046                                 break;
2047                         }
2048
2049                         if (buf[0] == 'r') {
2050                                 sscanf(buf, "remaining capacity: %d", &remaining_capacity);
2051                         }
2052                 }
2053         }
2054         if (remaining_capacity < 0) {
2055                 return 0;
2056         }
2057         /* compute the battery percentage */
2058         last_battery_perct[idx] =
2059                 (int) (((float) remaining_capacity / acpi_design_capacity[idx]) * 100);
2060         if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100;
2061         return last_battery_perct[idx];
2062 }
2063
2064 int get_battery_perct_bar(const char *bar)
2065 {
2066         int idx;
2067
2068         get_battery_perct(bar);
2069         idx = get_battery_idx(bar);
2070         return (int) (last_battery_perct[idx] * 2.56 - 1);
2071 }
2072
2073 /* On Apple powerbook and ibook:
2074 $ cat /proc/pmu/battery_0
2075 flags      : 00000013
2076 charge     : 3623
2077 max_charge : 3720
2078 current    : 388
2079 voltage    : 16787
2080 time rem.  : 900
2081 $ cat /proc/pmu/info
2082 PMU driver version     : 2
2083 PMU firmware version   : 0c
2084 AC Power               : 1
2085 Battery count          : 1
2086 */
2087
2088 /* defines as in <linux/pmu.h> */
2089 #define PMU_BATT_PRESENT                0x00000001
2090 #define PMU_BATT_CHARGING               0x00000002
2091
2092 static FILE *pmu_battery_fp;
2093 static FILE *pmu_info_fp;
2094 static char pb_battery_info[3][32];
2095 static double pb_battery_info_update;
2096
2097 #define PMU_PATH "/proc/pmu"
2098 void get_powerbook_batt_info(char *buffer, size_t n, int i)
2099 {
2100         static int rep = 0;
2101         const char *batt_path = PMU_PATH "/battery_0";
2102         const char *info_path = PMU_PATH "/info";
2103         unsigned int flags;
2104         int charge, max_charge, ac = -1;
2105         long timeval = -1;
2106
2107         /* don't update battery too often */
2108         if (current_update_time - pb_battery_info_update < 29.5) {
2109                 snprintf(buffer, n, "%s", pb_battery_info[i]);
2110                 return;
2111         }
2112         pb_battery_info_update = current_update_time;
2113
2114         if (pmu_battery_fp == NULL) {
2115                 pmu_battery_fp = open_file(batt_path, &rep);
2116                 if (pmu_battery_fp == NULL) {
2117                         return;
2118                 }
2119         }
2120
2121         if (pmu_battery_fp != NULL) {
2122                 rewind(pmu_battery_fp);
2123                 while (!feof(pmu_battery_fp)) {
2124                         char buf[32];
2125
2126                         if (fgets(buf, sizeof(buf), pmu_battery_fp) == NULL) {
2127                                 break;
2128                         }
2129
2130                         if (buf[0] == 'f') {
2131                                 sscanf(buf, "flags      : %8x", &flags);
2132                         } else if (buf[0] == 'c' && buf[1] == 'h') {
2133                                 sscanf(buf, "charge     : %d", &charge);
2134                         } else if (buf[0] == 'm') {
2135                                 sscanf(buf, "max_charge : %d", &max_charge);
2136                         } else if (buf[0] == 't') {
2137                                 sscanf(buf, "time rem.  : %ld", &timeval);
2138                         }
2139                 }
2140         }
2141         if (pmu_info_fp == NULL) {
2142                 pmu_info_fp = open_file(info_path, &rep);
2143                 if (pmu_info_fp == NULL) {
2144                         return;
2145                 }
2146         }
2147
2148         if (pmu_info_fp != NULL) {
2149                 rewind(pmu_info_fp);
2150                 while (!feof(pmu_info_fp)) {
2151                         char buf[32];
2152
2153                         if (fgets(buf, sizeof(buf), pmu_info_fp) == NULL) {
2154                                 break;
2155                         }
2156                         if (buf[0] == 'A') {
2157                                 sscanf(buf, "AC Power               : %d", &ac);
2158                         }
2159                 }
2160         }
2161         /* update status string */
2162         if ((ac && !(flags & PMU_BATT_PRESENT))) {
2163                 strncpy(pb_battery_info[PB_BATT_STATUS], "AC", sizeof(pb_battery_info[PB_BATT_STATUS]));
2164         } else if (ac && (flags & PMU_BATT_PRESENT)
2165                         && !(flags & PMU_BATT_CHARGING)) {
2166                 strncpy(pb_battery_info[PB_BATT_STATUS], "charged", sizeof(pb_battery_info[PB_BATT_STATUS]));
2167         } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) {
2168                 strncpy(pb_battery_info[PB_BATT_STATUS], "charging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2169         } else {
2170                 strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2171         }
2172
2173         /* update percentage string */
2174         if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT)
2175                         && !(flags & PMU_BATT_CHARGING)) {
2176                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2177                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "100%%");
2178         } else if (timeval == 0) {
2179                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2180                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "unknown");
2181         } else {
2182                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2183                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%",
2184                         (charge * 100) / max_charge);
2185         }
2186
2187         /* update time string */
2188         if (timeval == 0) {                     /* fully charged or battery not present */
2189                 snprintf(pb_battery_info[PB_BATT_TIME],
2190                         sizeof(pb_battery_info[PB_BATT_TIME]), "unknown");
2191         } else if (timeval < 60 * 60) { /* don't show secs */
2192                 format_seconds_short(pb_battery_info[PB_BATT_TIME],
2193                         sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2194         } else {
2195                 format_seconds(pb_battery_info[PB_BATT_TIME],
2196                         sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2197         }
2198
2199         snprintf(buffer, n, "%s", pb_battery_info[i]);
2200 }
2201
2202 int update_top(void)
2203 {
2204         process_find_top(info.cpu, info.memu, info.time
2205 #ifdef IOSTATS
2206                 , info.io
2207 #endif
2208                 );
2209         info.first_process = get_first_process();
2210         return 0;
2211 }
2212
2213 #define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail"
2214
2215 int get_entropy_avail(unsigned int *val)
2216 {
2217         static int rep = 0;
2218         FILE *fp;
2219
2220         if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep)))
2221                 return 1;
2222
2223         if (fscanf(fp, "%u", val) != 1)
2224                 return 1;
2225
2226         fclose(fp);
2227         return 0;
2228 }
2229
2230 #define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize"
2231
2232 int get_entropy_poolsize(unsigned int *val)
2233 {
2234         static int rep = 0;
2235         FILE *fp;
2236
2237         if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep)))
2238                 return 1;
2239
2240         if (fscanf(fp, "%u", val) != 1)
2241                 return 1;
2242
2243         fclose(fp);
2244         return 0;
2245 }
2246
2247 const char *get_disk_protect_queue(const char *disk)
2248 {
2249         FILE *fp;
2250         char path[128];
2251         int state;
2252
2253         snprintf(path, 127, "/sys/block/%s/device/unload_heads", disk);
2254         if (access(path, F_OK)) {
2255                 snprintf(path, 127, "/sys/block/%s/queue/protect", disk);
2256         }
2257         if ((fp = fopen(path, "r")) == NULL)
2258                 return "n/a   ";
2259         if (fscanf(fp, "%d\n", &state) != 1) {
2260                 fclose(fp);
2261                 return "failed";
2262         }
2263         fclose(fp);
2264         return (state > 0) ? "frozen" : "free  ";
2265 }
2266
2267 typedef struct DEV_LIST_TYPE
2268 {
2269         char *dev_name;
2270         int memoized;
2271         struct DEV_LIST_TYPE *next;
2272
2273 } DEV_LIST, *DEV_LIST_PTR;
2274
2275 /* Same as sf #2942117 but memoized using a linked list */
2276 int is_disk(char *dev)
2277 {
2278         char syspath[PATH_MAX];
2279         char *slash;
2280         static DEV_LIST_PTR dev_head = NULL;
2281         DEV_LIST_PTR dev_cur, dev_last;
2282
2283         dev_cur = dev_head;
2284
2285         while (dev_cur) {
2286                 if (strcmp(dev_cur->dev_name, dev) == 0)
2287                         return dev_cur->memoized;
2288                 dev_last = dev_cur;
2289                 dev_cur  = dev_cur->next;
2290         }
2291
2292         dev_cur = (DEV_LIST_PTR)malloc(sizeof(DEV_LIST));
2293         dev_cur->dev_name = (char *)malloc((strlen(dev)+1)*sizeof(char));
2294         strcpy(dev_cur->dev_name,dev);
2295         dev_cur->next = NULL;
2296
2297         while ((slash = strchr(dev, '/')))
2298                 *slash = '!';
2299         snprintf(syspath, sizeof(syspath), "/sys/block/%s", dev);
2300         dev_cur->memoized = !(access(syspath, F_OK));
2301
2302         if (dev_head)
2303                 dev_last->next = dev_cur;
2304         else
2305                 dev_head = dev_cur;
2306
2307         return dev_cur->memoized;
2308 }
2309
2310 int update_diskio(void)
2311 {
2312         FILE *fp;
2313         static int rep = 0;
2314         char buf[512], devbuf[64];
2315         unsigned int major, minor;
2316         int col_count = 0;
2317         struct diskio_stat *cur;
2318         unsigned int reads, writes;
2319         unsigned int total_reads = 0, total_writes = 0;
2320
2321         stats.current = 0;
2322         stats.current_read = 0;
2323         stats.current_write = 0;
2324
2325         if (!(fp = open_file("/proc/diskstats", &rep))) {
2326                 return 0;
2327         }
2328
2329         /* read reads and writes from all disks (minor = 0), including cd-roms
2330          * and floppies, and sum them up */
2331         while (fgets(buf, 512, fp)) {
2332                 col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major,
2333                         &minor, devbuf, &reads, &writes);
2334                 /* ignore subdevices (they have only 3 matching entries in their line)
2335                  * and virtual devices (LVM, network block devices, RAM disks, Loopback)
2336                  *
2337                  * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */
2338                 if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR
2339                                 && major != RAMDISK_MAJOR && major != LOOP_MAJOR) {
2340                         /* check needed for kernel >= 2.6.31, see sf #2942117 */
2341                         if (is_disk(devbuf)) {
2342                                 total_reads += reads;
2343                                 total_writes += writes;
2344                         }
2345                 } else {
2346                         col_count = sscanf(buf, "%u %u %s %*u %u %*u %u",
2347                                 &major, &minor, devbuf, &reads, &writes);
2348                         if (col_count != 5) {
2349                                 continue;
2350                         }
2351                 }
2352                 cur = stats.next;
2353                 while (cur && strcmp(devbuf, cur->dev))
2354                         cur = cur->next;
2355
2356                 if (cur)
2357                         update_diskio_values(cur, reads, writes);
2358         }
2359         update_diskio_values(&stats, total_reads, total_writes);
2360         fclose(fp);
2361         return 0;
2362 }