3c0c1e9a6dcd964a12aaad1eb00b55bf19fe6388
[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 /*on n900 with power kernel: (non power kernel could use "hal-device bme" and do something else)
1553 /sys/class/power_supply/bq27200-0/uevent
1554 PHYSDEVPATH=/class/i2c-adapter/i2c-2/2-0055
1555 PHYSDEVBUS=i2c
1556 PHYSDEVDRIVER=bq27200-battery
1557 POWER_SUPPLY_NAME=bq27200-0
1558 POWER_SUPPLY_TYPE=Battery
1559 POWER_SUPPLY_PRESENT=1                                                                                                  << this is always 1, it means the battery is inserted
1560 POWER_SUPPLY_VOLTAGE_NOW=4039                                                                           << this keeps updating during charging
1561 POWER_SUPPLY_CURRENT_NOW=1960                   << this goes negative when charging!
1562 POWER_SUPPLY_CAPACITY=98                                                                                                << supposed to be the %, but it stops updating when charging until it hits 100%
1563 POWER_SUPPLY_TEMP=39                                                                                                            << only temperature sensor in n900 :(
1564 */
1565
1566 #define SYSFS_BATTERY_BASE_PATH "/sys/class/power_supply"
1567 #define ACPI_BATTERY_BASE_PATH "/proc/acpi/battery" //not for n900
1568 #define APM_PATH "/proc/apm"  //not for n900
1569 #define MAX_BATTERY_COUNT 4 //more like 1
1570
1571 static FILE *sysfs_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1572 static FILE *acpi_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1573 static FILE *apm_bat_fp[MAX_BATTERY_COUNT] = { NULL, NULL, NULL, NULL };
1574
1575 static int batteries_initialized = 0;
1576 static char batteries[MAX_BATTERY_COUNT][32];
1577
1578 static int acpi_last_full[MAX_BATTERY_COUNT];
1579 static int acpi_design_capacity[MAX_BATTERY_COUNT];
1580
1581 /* e.g. "charging 75%" */
1582 static char last_battery_str[MAX_BATTERY_COUNT][64];
1583 /* e.g. "3h 15m" */
1584 static char last_battery_time_str[MAX_BATTERY_COUNT][64];
1585
1586 static double last_battery_time[MAX_BATTERY_COUNT];
1587
1588 static int last_battery_perct[MAX_BATTERY_COUNT];
1589 static double last_battery_perct_time[MAX_BATTERY_COUNT];
1590
1591 void init_batteries(void)
1592 {
1593         int idx;
1594
1595         if (batteries_initialized) {
1596                 return;
1597         }
1598 #ifdef HAVE_OPENMP
1599 #pragma omp parallel for schedule(dynamic,10)
1600 #endif /* HAVE_OPENMP */
1601         for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1602                 batteries[idx][0] = '\0';
1603         }
1604         batteries_initialized = 1;
1605 }
1606
1607 int get_battery_idx(const char *bat)
1608 {
1609         int idx;
1610
1611         for (idx = 0; idx < MAX_BATTERY_COUNT; idx++) {
1612                 if (!strlen(batteries[idx]) || !strcmp(batteries[idx], bat)) {
1613                         break;
1614                 }
1615         }
1616
1617         /* if not found, enter a new entry */
1618         if (!strlen(batteries[idx])) {
1619                 snprintf(batteries[idx], 31, "%s", bat);
1620         }
1621
1622         return idx;
1623 }
1624
1625 void set_return_value(char *buffer, unsigned int n, int item, int idx);
1626
1627 void get_battery_stuff(char *buffer, unsigned int n, const char *bat, int item)
1628 {
1629         static int idx, rep = 0, rep1 = 0, rep2 = 0;
1630         char acpi_path[128];
1631         char sysfs_path[128];
1632
1633         snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
1634         snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
1635
1636         init_batteries();
1637
1638         idx = get_battery_idx(bat);
1639
1640         /* don't update battery too often */
1641         if (current_update_time - last_battery_time[idx] < 29.5) {
1642                 set_return_value(buffer, n, item, idx);
1643                 return;
1644         }
1645
1646         last_battery_time[idx] = current_update_time;
1647
1648         memset(last_battery_str[idx], 0, sizeof(last_battery_str[idx]));
1649         memset(last_battery_time_str[idx], 0, sizeof(last_battery_time_str[idx]));
1650
1651         /* first try SYSFS if that fails try ACPI */
1652
1653         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1654                 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
1655         }
1656
1657         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
1658                 acpi_bat_fp[idx] = open_file(acpi_path, &rep1);
1659         }
1660
1661         if (sysfs_bat_fp[idx] != NULL) {
1662                 /* SYSFS */
1663                 int present_rate = -9999; //we will put "current now" into this. negative when charging!
1664                 int remaining_capacity = -1; //in %
1665                 char charging_state[64];//can't get this without hal bme
1666                 int voltage = -1;
1667                 //int capacity = -1;
1668                 int temp = 9999;
1669                 char present[4];
1670                 strcpy(present, "no");
1671                 strcpy(charging_state, "unknown");
1672
1673                 while (!feof(sysfs_bat_fp[idx])) {
1674                         char buf[256];
1675                         if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
1676                                 break;
1677
1678                         /* let's just hope units are ok */
1679                         if (strncmp (buf, "POWER_SUPPLY_PRESENT=1", 22) == 0)
1680                                 strcpy(present, "yes");//n900 always yes
1681                         else if (strncmp(buf, "POWER_SUPPLY_VOLTAGE_NOW=", 25) == 0)
1682                                 sscanf(buf, "POWER_SUPPLY_VOLTAGE_NOW=%d", &voltage);
1683 //              else if (strncmp (buf, "POWER_SUPPLY_STATUS=", 20) == 0)
1684 //                      sscanf(buf, "POWER_SUPPLY_STATUS=%63s", charging_state);
1685                         else if (strncmp(buf, "POWER_SUPPLY_CURRENT_NOW=", 25) == 0)
1686                                 sscanf(buf, "POWER_SUPPLY_CURRENT_NOW=%d", &present_rate);
1687                         else if (strncmp(buf, "POWER_SUPPLY_CAPACITY=", 22) == 0)
1688                                 sscanf(buf, "POWER_SUPPLY_CAPACITY=%d", &remaining_capacity);
1689                         else if (strncmp(buf, "POWER_SUPPLY_TEMP=", 18) == 0)
1690                                 sscanf(buf, "POWER_SUPPLY_TEMP=%d", &temp);
1691 //                      else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0)
1692 //                              sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
1693 //                      else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=", 25) == 0)
1694 //                              sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_last_full[idx]);
1695 //                      else if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0)
1696 //                              sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
1697 //                      else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=", 25) == 0)
1698 //                              sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_last_full[idx]);
1699                 }
1700
1701                 fclose(sysfs_bat_fp[idx]);
1702                 sysfs_bat_fp[idx] = NULL;
1703
1704                 /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
1705                 //lance notes, we don't care
1706 //              if (remaining_capacity > acpi_last_full[idx])
1707 //                      acpi_last_full[idx] = remaining_capacity;  /* normalize to 100% */
1708
1709                 /* not present */
1710                 //not possible
1711 //              if (strcmp(present, "no") == 0) {
1712 //                      strncpy(last_battery_str[idx], "not present", 64);
1713 //              }
1714                 /* charging */
1715                 if (present_rate <= 0) {//if charging
1716                                 /* e.g. charging 75% */
1717                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %i%%",
1718                                         (int) (((float) remaining_capacity / 100) ));
1719                                 snprintf(last_battery_time_str[idx],
1720                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1721                                 /* e.g. 2h 37m */
1722 //                              format_seconds(last_battery_time_str[idx], sizeof(last_battery_time_str[idx])-1,
1723 //                                            (long) (((float)(acpi_last_full[idx] - remaining_capacity) / present_rate) * 3600));
1724                 }
1725
1726 //              else if (acpi_last_full[idx] != 0 && present_rate <= 0) {//supposed to be guessing the time to fully charge, won't work though.
1727 //                      snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "charging %d%%",
1728 //                              (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1729 //                      snprintf(last_battery_time_str[idx],
1730 //                              sizeof(last_battery_time_str[idx]) - 1, "unknown");
1731 //              } else {
1732 //                              strncpy(last_battery_str[idx], "charging", sizeof(last_battery_str[idx])-1);
1733 //                              snprintf(last_battery_time_str[idx],
1734 //                                      sizeof(last_battery_time_str[idx]) - 1, "unknown");
1735 //                      }
1736 //              }
1737                 /* discharging */
1738                 else if (present_rate > 0) {
1739                           
1740                                 /* e.g. discharging 35% */
1741                                 snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1, "discharging %i%%",
1742                                         (int) (((float) remaining_capacity / 100)   ));
1743
1744                                 snprintf(last_battery_time_str[idx],
1745                                         sizeof(last_battery_time_str[idx]) - 1, "unknown");
1746                                         /* e.g. 1h 12m */
1747 //                              format_seconds(last_battery_time_str[idx], sizeof(last_battery_time_str[idx])-1,
1748 //                                            (long) (((float) remaining_capacity / present_rate) * 3600));             
1749 //                       else {
1750 //                              snprintf(last_battery_str[idx], sizeof(last_battery_str[idx])-1,
1751 //                                      "discharging %d%%",
1752 //                                      (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1753 //                              snprintf(last_battery_time_str[idx],
1754 //                                      sizeof(last_battery_time_str[idx]) - 1, "unknown");
1755 //                      }
1756                 }
1757                 /* charged */
1758                 /* thanks to Lukas Zapletal <lzap@seznam.cz> */
1759                 
1760                  if (remaining_capacity == 100)
1761                                 strcpy(last_battery_str[idx], "charged");
1762                                         
1763 //              else if (strncmp(charging_state, "Charged", 64) == 0 || strncmp(charging_state, "Full", 64) == 0) {
1764 //                              /* Below happens with the second battery on my X40,
1765 //                               * when the second one is empty and the first one
1766 //                               * being charged. */
1767 //                              if (remaining_capacity == 0)
1768 //                                      strcpy(last_battery_str[idx], "empty");
1769 //                              else
1770 //                                      strcpy(last_battery_str[idx], "charged");
1771 //              }
1772                 /* unknown, probably full / AC */
1773 //              else {
1774 //                      if (acpi_last_full[idx] != 0
1775 //                          && remaining_capacity != acpi_last_full[idx])
1776 //                              snprintf(last_battery_str[idx], 64, "unknown %d%%",
1777 //                                      (int) (((float)remaining_capacity / acpi_last_full[idx]) * 100));
1778 //                      else
1779 //                              strncpy(last_battery_str[idx], "AC", 64);
1780 //              }
1781         } else if (acpi_bat_fp[idx] != NULL) {//skipped on n900
1782                 /* ACPI */
1783                 int present_rate = -1;
1784                 int remaining_capacity = -1;
1785                 char charging_state[64];
1786                 char present[4];
1787
1788                 /* read last full capacity if it's zero */
1789                 if (acpi_last_full[idx] == 0) {
1790                         static int rep3 = 0;
1791                         char path[128];
1792                         FILE *fp;
1793
1794                         snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
1795                         fp = open_file(path, &rep3);
1796                         if (fp != NULL) {
1797                                 while (!feof(fp)) {
1798                                         char b[256];
1799
1800                                         if (fgets(b, 256, fp) == NULL) {
1801                                                 break;
1802                                         }
1803                                         if (sscanf(b, "last full capacity: %d",
1804                                                                 &acpi_last_full[idx]) != 0) {
1805                                                 break;
1806                                         }
1807                                 }
1808
1809                                 fclose(fp);
1810                         }
1811                 }
1812
1813                 fseek(acpi_bat_fp[idx], 0, SEEK_SET);
1814
1815                 strcpy(charging_state, "unknown");
1816
1817                 while (!feof(acpi_bat_fp[idx])) {
1818                         char buf[256];
1819
1820                         if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
1821                                 break;
1822                         }
1823
1824                         /* let's just hope units are ok */
1825                         if (strncmp(buf, "present:", 8) == 0) {
1826                                 sscanf(buf, "present: %4s", present);
1827                         } else if (strncmp(buf, "charging state:", 15) == 0) {
1828                                 sscanf(buf, "charging state: %63s", charging_state);
1829                         } else if (strncmp(buf, "present rate:", 13) == 0) {
1830                                 sscanf(buf, "present rate: %d", &present_rate);
1831                         } else if (strncmp(buf, "remaining capacity:", 19) == 0) {
1832                                 sscanf(buf, "remaining capacity: %d", &remaining_capacity);
1833                         }
1834                 }
1835                 /* Hellf[i]re notes that remaining capacity can exceed acpi_last_full */
1836                 if (remaining_capacity > acpi_last_full[idx]) {
1837                         /* normalize to 100% */
1838                         acpi_last_full[idx] = remaining_capacity;
1839                 }
1840
1841                 /* not present */
1842                 if (strcmp(present, "no") == 0) {
1843                         strncpy(last_battery_str[idx], "not present", 64);
1844                         /* charging */
1845                 } else if (strcmp(charging_state, "charging") == 0) {
1846                         if (acpi_last_full[idx] != 0 && present_rate > 0) {
1847                                 /* e.g. charging 75% */
1848                                 snprintf(last_battery_str[idx],
1849                                                 sizeof(last_battery_str[idx]) - 1, "charging %i%%",
1850                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1851                                 /* e.g. 2h 37m */
1852                                 format_seconds(last_battery_time_str[idx],
1853                                                 sizeof(last_battery_time_str[idx]) - 1,
1854                                                 (long) (((acpi_last_full[idx] - remaining_capacity) *
1855                                                                 3600) / present_rate));
1856                         } else if (acpi_last_full[idx] != 0 && present_rate <= 0) {
1857                                 snprintf(last_battery_str[idx],
1858                                                 sizeof(last_battery_str[idx]) - 1, "charging %d%%",
1859                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1860                                 snprintf(last_battery_time_str[idx],
1861                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1862                         } else {
1863                                 strncpy(last_battery_str[idx], "charging",
1864                                                 sizeof(last_battery_str[idx]) - 1);
1865                                 snprintf(last_battery_time_str[idx],
1866                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1867                         }
1868                         /* discharging */
1869                 } else if (strncmp(charging_state, "discharging", 64) == 0) {
1870                         if (present_rate > 0) {
1871                                 /* e.g. discharging 35% */
1872                                 snprintf(last_battery_str[idx],
1873                                                 sizeof(last_battery_str[idx]) - 1, "discharging %i%%",
1874                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1875                                 /* e.g. 1h 12m */
1876                                 format_seconds(last_battery_time_str[idx],
1877                                                 sizeof(last_battery_time_str[idx]) - 1,
1878                                                 (long) ((remaining_capacity * 3600) / present_rate));
1879                         } else if (present_rate == 0) { /* Thanks to Nexox for this one */
1880                                 snprintf(last_battery_str[idx],
1881                                                 sizeof(last_battery_str[idx]) - 1, "full");
1882                                 snprintf(last_battery_time_str[idx],
1883                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1884                         } else {
1885                                 snprintf(last_battery_str[idx],
1886                                                 sizeof(last_battery_str[idx]) - 1, "discharging %d%%",
1887                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1888                                 snprintf(last_battery_time_str[idx],
1889                                                 sizeof(last_battery_time_str[idx]) - 1, "unknown");
1890                         }
1891                         /* charged */
1892                 } else if (strncmp(charging_state, "charged", 64) == 0) {
1893                         /* thanks to Lukas Zapletal <lzap@seznam.cz> */
1894                         /* Below happens with the second battery on my X40,
1895                          * when the second one is empty and the first one being charged. */
1896                         if (remaining_capacity == 0) {
1897                                 strcpy(last_battery_str[idx], "empty");
1898                         } else {
1899                                 strcpy(last_battery_str[idx], "charged");
1900                         }
1901                         /* unknown, probably full / AC */
1902                 } else {
1903                         if (strncmp(charging_state, "Full", 64) == 0) {
1904                                 strncpy(last_battery_str[idx], "full", 64);
1905                         } else if (acpi_last_full[idx] != 0
1906                                         && remaining_capacity != acpi_last_full[idx]) {
1907                                 snprintf(last_battery_str[idx], 64, "unknown %d%%",
1908                                                 (int) ((remaining_capacity * 100) / acpi_last_full[idx]));
1909                         } else {
1910                                 strncpy(last_battery_str[idx], "AC", 64);
1911                         }
1912                 }
1913                 fclose(acpi_bat_fp[idx]);
1914                 acpi_bat_fp[idx] = NULL;
1915         } else {//also skipped on n900
1916                 /* APM */
1917                 if (apm_bat_fp[idx] == NULL) {
1918                         apm_bat_fp[idx] = open_file(APM_PATH, &rep2);
1919                 }
1920
1921                 if (apm_bat_fp[idx] != NULL) {
1922                         unsigned int ac, status, flag;
1923                         int life;
1924
1925                         fscanf(apm_bat_fp[idx], "%*s %*s %*x %x   %x       %x     %d%%",
1926                                 &ac, &status, &flag, &life);
1927
1928                         if (life == -1) {
1929                                 /* could check now that there is ac */
1930                                 snprintf(last_battery_str[idx], 64, "AC");
1931
1932                         /* could check that status == 3 here? */
1933                         } else if (ac && life != 100) {
1934                                 snprintf(last_battery_str[idx], 64, "charging %d%%", life);
1935                         } else {
1936                                 snprintf(last_battery_str[idx], 64, "%d%%", life);
1937                         }
1938
1939                         /* it seemed to buffer it so file must be closed (or could use
1940                          * syscalls directly but I don't feel like coding it now) */
1941                         fclose(apm_bat_fp[idx]);
1942                         apm_bat_fp[idx] = NULL;
1943                 }
1944         }
1945         set_return_value(buffer, n, item, idx);
1946 }
1947
1948 void set_return_value(char *buffer, unsigned int n, int item, int idx)
1949 {
1950         switch (item) {
1951                 case BATTERY_STATUS:
1952                         snprintf(buffer, n, "%s", last_battery_str[idx]);
1953                         break;
1954                 case BATTERY_TIME:
1955                         snprintf(buffer, n, "%s", last_battery_time_str[idx]);
1956                         break;
1957                 default:
1958                         break;
1959         }
1960 }
1961
1962 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
1963 {
1964         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
1965         if (0 == strncmp("charging", buffer, 8)) {
1966                 buffer[0] = 'C';
1967                 memmove(buffer + 1, buffer + 8, n - 8);
1968         } else if (0 == strncmp("discharging", buffer, 11)) {
1969                 buffer[0] = 'D';
1970                 memmove(buffer + 1, buffer + 11, n - 11);
1971         } else if (0 == strncmp("charged", buffer, 7)) {
1972                 buffer[0] = 'F';
1973                 memmove(buffer + 1, buffer + 7, n - 7);
1974         } else if (0 == strncmp("not present", buffer, 11)) {
1975                 buffer[0] = 'N';
1976                 memmove(buffer + 1, buffer + 11, n - 11);
1977         } else if (0 == strncmp("empty", buffer, 5)) {
1978                 buffer[0] = 'E';
1979                 memmove(buffer + 1, buffer + 5, n - 5);
1980         } else if (0 != strncmp("AC", buffer, 2)) {
1981                 buffer[0] = 'U';
1982                 memmove(buffer + 1, buffer + 11, n - 11);
1983         }
1984 }
1985
1986 int get_battery_perct(const char *bat)
1987 {
1988         static int rep = 0;
1989         int idx;
1990         char acpi_path[128];
1991         char sysfs_path[128];
1992         int remaining_capacity = -1;
1993
1994         snprintf(acpi_path, 127, ACPI_BATTERY_BASE_PATH "/%s/state", bat);
1995         snprintf(sysfs_path, 127, SYSFS_BATTERY_BASE_PATH "/%s/uevent", bat);
1996
1997         init_batteries();
1998
1999         idx = get_battery_idx(bat);
2000
2001         /* don't update battery too often */
2002         if (current_update_time - last_battery_perct_time[idx] < 30) {
2003                 return last_battery_perct[idx];
2004         }
2005         last_battery_perct_time[idx] = current_update_time;
2006
2007         /* Only check for SYSFS or ACPI */
2008
2009         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
2010                 sysfs_bat_fp[idx] = open_file(sysfs_path, &rep);
2011                 rep = 0;
2012         }
2013
2014         if (sysfs_bat_fp[idx] == NULL && acpi_bat_fp[idx] == NULL && apm_bat_fp[idx] == NULL) {
2015                 acpi_bat_fp[idx] = open_file(acpi_path, &rep);
2016         }
2017
2018         if (sysfs_bat_fp[idx] != NULL) {
2019                 /* SYSFS */
2020                 while (!feof(sysfs_bat_fp[idx])) {
2021                         char buf[256];
2022                         if (fgets(buf, 256, sysfs_bat_fp[idx]) == NULL)
2023                                 break;
2024                         if (strncmp(buf, "POWER_SUPPLY_CAPACITY=", 22) == 0) {
2025                                 sscanf(buf, "POWER_SUPPLY_CAPACITY=%d", &remaining_capacity);
2026                                 
2027 //                      if (strncmp(buf, "POWER_SUPPLY_CHARGE_NOW=", 24) == 0) {
2028 //                              sscanf(buf, "POWER_SUPPLY_CHARGE_NOW=%d", &remaining_capacity);
2029 //                      } else if (strncmp(buf, "POWER_SUPPLY_CHARGE_FULL=",25) == 0) {
2030 //                              sscanf(buf, "POWER_SUPPLY_CHARGE_FULL=%d", &acpi_design_capacity[idx]);
2031 //                      } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_NOW=", 24) == 0) {
2032 //                              sscanf(buf, "POWER_SUPPLY_ENERGY_NOW=%d", &remaining_capacity);
2033 //                      } else if (strncmp(buf, "POWER_SUPPLY_ENERGY_FULL=",25) == 0) {
2034 //                              sscanf(buf, "POWER_SUPPLY_ENERGY_FULL=%d", &acpi_design_capacity[idx]);
2035 //                      }
2036                         }
2037                 }
2038                 fclose(sysfs_bat_fp[idx]);
2039                 sysfs_bat_fp[idx] = NULL;
2040
2041         } else if (acpi_bat_fp[idx] != NULL) {
2042                 /* ACPI */
2043                 /* read last full capacity if it's zero */
2044                 if (acpi_design_capacity[idx] == 0) {
2045                         static int rep2;
2046                         char path[128];
2047                         FILE *fp;
2048
2049                         snprintf(path, 127, ACPI_BATTERY_BASE_PATH "/%s/info", bat);
2050                         fp = open_file(path, &rep2);
2051                         if (fp != NULL) {
2052                                 while (!feof(fp)) {
2053                                         char b[256];
2054
2055                                         if (fgets(b, 256, fp) == NULL) {
2056                                                 break;
2057                                         }
2058                                         if (sscanf(b, "last full capacity: %d",
2059                                                                 &acpi_design_capacity[idx]) != 0) {
2060                                                 break;
2061                                         }
2062                                 }
2063                                 fclose(fp);
2064                         }
2065                 }
2066
2067                 fseek(acpi_bat_fp[idx], 0, SEEK_SET);
2068
2069                 while (!feof(acpi_bat_fp[idx])) {
2070                         char buf[256];
2071
2072                         if (fgets(buf, 256, acpi_bat_fp[idx]) == NULL) {
2073                                 break;
2074                         }
2075
2076                         if (buf[0] == 'r') {
2077                                 sscanf(buf, "remaining capacity: %d", &remaining_capacity);
2078                         }
2079                 }
2080         }
2081         if (remaining_capacity < 0) {
2082                 return 0;
2083         }
2084         /* compute the battery percentage */
2085         last_battery_perct[idx] = 
2086                 remaining_capacity;
2087                 //(int) (((float) remaining_capacity / acpi_design_capacity[idx]) * 100);
2088         //if (last_battery_perct[idx] > 100) last_battery_perct[idx] = 100;
2089         return last_battery_perct[idx];
2090 }
2091
2092 int get_battery_perct_bar(const char *bar)
2093 {
2094         int idx;
2095
2096         get_battery_perct(bar);
2097         idx = get_battery_idx(bar);
2098         return (int) (last_battery_perct[idx] * 2.56 - 1);
2099 }
2100
2101 /* On Apple powerbook and ibook:
2102 $ cat /proc/pmu/battery_0
2103 flags      : 00000013
2104 charge     : 3623
2105 max_charge : 3720
2106 current    : 388
2107 voltage    : 16787
2108 time rem.  : 900
2109 $ cat /proc/pmu/info
2110 PMU driver version     : 2
2111 PMU firmware version   : 0c
2112 AC Power               : 1
2113 Battery count          : 1
2114 */
2115
2116 /* defines as in <linux/pmu.h> */
2117 #define PMU_BATT_PRESENT                0x00000001
2118 #define PMU_BATT_CHARGING               0x00000002
2119
2120 static FILE *pmu_battery_fp;
2121 static FILE *pmu_info_fp;
2122 static char pb_battery_info[3][32];
2123 static double pb_battery_info_update;
2124
2125 #define PMU_PATH "/proc/pmu"
2126 void get_powerbook_batt_info(char *buffer, size_t n, int i)
2127 {
2128         static int rep = 0;
2129         const char *batt_path = PMU_PATH "/battery_0";
2130         const char *info_path = PMU_PATH "/info";
2131         unsigned int flags;
2132         int charge, max_charge, ac = -1;
2133         long timeval = -1;
2134
2135         /* don't update battery too often */
2136         if (current_update_time - pb_battery_info_update < 29.5) {
2137                 snprintf(buffer, n, "%s", pb_battery_info[i]);
2138                 return;
2139         }
2140         pb_battery_info_update = current_update_time;
2141
2142         if (pmu_battery_fp == NULL) {
2143                 pmu_battery_fp = open_file(batt_path, &rep);
2144                 if (pmu_battery_fp == NULL) {
2145                         return;
2146                 }
2147         }
2148
2149         if (pmu_battery_fp != NULL) {
2150                 rewind(pmu_battery_fp);
2151                 while (!feof(pmu_battery_fp)) {
2152                         char buf[32];
2153
2154                         if (fgets(buf, sizeof(buf), pmu_battery_fp) == NULL) {
2155                                 break;
2156                         }
2157
2158                         if (buf[0] == 'f') {
2159                                 sscanf(buf, "flags      : %8x", &flags);
2160                         } else if (buf[0] == 'c' && buf[1] == 'h') {
2161                                 sscanf(buf, "charge     : %d", &charge);
2162                         } else if (buf[0] == 'm') {
2163                                 sscanf(buf, "max_charge : %d", &max_charge);
2164                         } else if (buf[0] == 't') {
2165                                 sscanf(buf, "time rem.  : %ld", &timeval);
2166                         }
2167                 }
2168         }
2169         if (pmu_info_fp == NULL) {
2170                 pmu_info_fp = open_file(info_path, &rep);
2171                 if (pmu_info_fp == NULL) {
2172                         return;
2173                 }
2174         }
2175
2176         if (pmu_info_fp != NULL) {
2177                 rewind(pmu_info_fp);
2178                 while (!feof(pmu_info_fp)) {
2179                         char buf[32];
2180
2181                         if (fgets(buf, sizeof(buf), pmu_info_fp) == NULL) {
2182                                 break;
2183                         }
2184                         if (buf[0] == 'A') {
2185                                 sscanf(buf, "AC Power               : %d", &ac);
2186                         }
2187                 }
2188         }
2189         /* update status string */
2190         if ((ac && !(flags & PMU_BATT_PRESENT))) {
2191                 strncpy(pb_battery_info[PB_BATT_STATUS], "AC", sizeof(pb_battery_info[PB_BATT_STATUS]));
2192         } else if (ac && (flags & PMU_BATT_PRESENT)
2193                         && !(flags & PMU_BATT_CHARGING)) {
2194                 strncpy(pb_battery_info[PB_BATT_STATUS], "charged", sizeof(pb_battery_info[PB_BATT_STATUS]));
2195         } else if ((flags & PMU_BATT_PRESENT) && (flags & PMU_BATT_CHARGING)) {
2196                 strncpy(pb_battery_info[PB_BATT_STATUS], "charging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2197         } else {
2198                 strncpy(pb_battery_info[PB_BATT_STATUS], "discharging", sizeof(pb_battery_info[PB_BATT_STATUS]));
2199         }
2200
2201         /* update percentage string */
2202         if (timeval == 0 && ac && (flags & PMU_BATT_PRESENT)
2203                         && !(flags & PMU_BATT_CHARGING)) {
2204                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2205                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "100%%");
2206         } else if (timeval == 0) {
2207                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2208                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "unknown");
2209         } else {
2210                 snprintf(pb_battery_info[PB_BATT_PERCENT],
2211                         sizeof(pb_battery_info[PB_BATT_PERCENT]), "%d%%",
2212                         (charge * 100) / max_charge);
2213         }
2214
2215         /* update time string */
2216         if (timeval == 0) {                     /* fully charged or battery not present */
2217                 snprintf(pb_battery_info[PB_BATT_TIME],
2218                         sizeof(pb_battery_info[PB_BATT_TIME]), "unknown");
2219         } else if (timeval < 60 * 60) { /* don't show secs */
2220                 format_seconds_short(pb_battery_info[PB_BATT_TIME],
2221                         sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2222         } else {
2223                 format_seconds(pb_battery_info[PB_BATT_TIME],
2224                         sizeof(pb_battery_info[PB_BATT_TIME]), timeval);
2225         }
2226
2227         snprintf(buffer, n, "%s", pb_battery_info[i]);
2228 }
2229
2230 int update_top(void)
2231 {
2232         process_find_top(info.cpu, info.memu, info.time
2233 #ifdef IOSTATS
2234                 , info.io
2235 #endif
2236                 );
2237         info.first_process = get_first_process();
2238         return 0;
2239 }
2240
2241 #define ENTROPY_AVAIL_PATH "/proc/sys/kernel/random/entropy_avail"
2242
2243 int get_entropy_avail(unsigned int *val)
2244 {
2245         static int rep = 0;
2246         FILE *fp;
2247
2248         if (!(fp = open_file(ENTROPY_AVAIL_PATH, &rep)))
2249                 return 1;
2250
2251         if (fscanf(fp, "%u", val) != 1)
2252                 return 1;
2253
2254         fclose(fp);
2255         return 0;
2256 }
2257
2258 #define ENTROPY_POOLSIZE_PATH "/proc/sys/kernel/random/poolsize"
2259
2260 int get_entropy_poolsize(unsigned int *val)
2261 {
2262         static int rep = 0;
2263         FILE *fp;
2264
2265         if (!(fp = open_file(ENTROPY_POOLSIZE_PATH, &rep)))
2266                 return 1;
2267
2268         if (fscanf(fp, "%u", val) != 1)
2269                 return 1;
2270
2271         fclose(fp);
2272         return 0;
2273 }
2274
2275 const char *get_disk_protect_queue(const char *disk)
2276 {
2277         FILE *fp;
2278         char path[128];
2279         int state;
2280
2281         snprintf(path, 127, "/sys/block/%s/device/unload_heads", disk);
2282         if (access(path, F_OK)) {
2283                 snprintf(path, 127, "/sys/block/%s/queue/protect", disk);
2284         }
2285         if ((fp = fopen(path, "r")) == NULL)
2286                 return "n/a   ";
2287         if (fscanf(fp, "%d\n", &state) != 1) {
2288                 fclose(fp);
2289                 return "failed";
2290         }
2291         fclose(fp);
2292         return (state > 0) ? "frozen" : "free  ";
2293 }
2294
2295 typedef struct DEV_LIST_TYPE
2296 {
2297         char *dev_name;
2298         int memoized;
2299         struct DEV_LIST_TYPE *next;
2300
2301 } DEV_LIST, *DEV_LIST_PTR;
2302
2303 /* Same as sf #2942117 but memoized using a linked list */
2304 int is_disk(char *dev)
2305 {
2306         char syspath[PATH_MAX];
2307         char *slash;
2308         static DEV_LIST_PTR dev_head = NULL;
2309         DEV_LIST_PTR dev_cur, dev_last;
2310
2311         dev_cur = dev_head;
2312
2313         while (dev_cur) {
2314                 if (strcmp(dev_cur->dev_name, dev) == 0)
2315                         return dev_cur->memoized;
2316                 dev_last = dev_cur;
2317                 dev_cur  = dev_cur->next;
2318         }
2319
2320         dev_cur = (DEV_LIST_PTR)malloc(sizeof(DEV_LIST));
2321         dev_cur->dev_name = (char *)malloc((strlen(dev)+1)*sizeof(char));
2322         strcpy(dev_cur->dev_name,dev);
2323         dev_cur->next = NULL;
2324
2325         while ((slash = strchr(dev, '/')))
2326                 *slash = '!';
2327         snprintf(syspath, sizeof(syspath), "/sys/block/%s", dev);
2328         dev_cur->memoized = !(access(syspath, F_OK));
2329
2330         if (dev_head)
2331                 dev_last->next = dev_cur;
2332         else
2333                 dev_head = dev_cur;
2334
2335         return dev_cur->memoized;
2336 }
2337
2338 int update_diskio(void)
2339 {
2340         FILE *fp;
2341         static int rep = 0;
2342         char buf[512], devbuf[64];
2343         unsigned int major, minor;
2344         int col_count = 0;
2345         struct diskio_stat *cur;
2346         unsigned int reads, writes;
2347         unsigned int total_reads = 0, total_writes = 0;
2348
2349         stats.current = 0;
2350         stats.current_read = 0;
2351         stats.current_write = 0;
2352
2353         if (!(fp = open_file("/proc/diskstats", &rep))) {
2354                 return 0;
2355         }
2356
2357         /* read reads and writes from all disks (minor = 0), including cd-roms
2358          * and floppies, and sum them up */
2359         while (fgets(buf, 512, fp)) {
2360                 col_count = sscanf(buf, "%u %u %s %*u %*u %u %*u %*u %*u %u", &major,
2361                         &minor, devbuf, &reads, &writes);
2362                 /* ignore subdevices (they have only 3 matching entries in their line)
2363                  * and virtual devices (LVM, network block devices, RAM disks, Loopback)
2364                  *
2365                  * XXX: ignore devices which are part of a SW RAID (MD_MAJOR) */
2366                 if (col_count == 5 && major != LVM_BLK_MAJOR && major != NBD_MAJOR
2367                                 && major != RAMDISK_MAJOR && major != LOOP_MAJOR) {
2368                         /* check needed for kernel >= 2.6.31, see sf #2942117 */
2369                         if (is_disk(devbuf)) {
2370                                 total_reads += reads;
2371                                 total_writes += writes;
2372                         }
2373                 } else {
2374                         col_count = sscanf(buf, "%u %u %s %*u %u %*u %u",
2375                                 &major, &minor, devbuf, &reads, &writes);
2376                         if (col_count != 5) {
2377                                 continue;
2378                         }
2379                 }
2380                 cur = stats.next;
2381                 while (cur && strcmp(devbuf, cur->dev))
2382                         cur = cur->next;
2383
2384                 if (cur)
2385                         update_diskio_values(cur, reads, writes);
2386         }
2387         update_diskio_values(&stats, total_reads, total_writes);
2388         fclose(fp);
2389         return 0;
2390 }