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