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