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