Update copyright stuff, fix conky.conf weirdness.
[monky] / src / freebsd.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) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
10  *      (see AUTHORS)
11  * All rights reserved.
12  *
13  * This program is free software: you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation, either version 3 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  *
25  */
26
27 #include <sys/dkstat.h>
28 #include <sys/param.h>
29 #include <sys/resource.h>
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/sysctl.h>
33 #include <sys/time.h>
34 #include <sys/types.h>
35 #include <sys/vmmeter.h>
36 #include <sys/user.h>
37
38 #include <net/if.h>
39 #include <net/if_mib.h>
40 #include <net/if_media.h>
41 #include <net/if_var.h>
42
43 #include <devstat.h>
44 #include <ifaddrs.h>
45 #include <limits.h>
46 #include <unistd.h>
47
48 #include <dev/wi/if_wavelan_ieee.h>
49 #include <dev/acpica/acpiio.h>
50
51 #include "conky.h"
52 #include "freebsd.h"
53 #include "logging.h"
54 #include "top.h"
55 #include "diskio.h"
56
57 #define GETSYSCTL(name, var)    getsysctl(name, &(var), sizeof(var))
58 #define KELVTOC(x)                              ((x - 2732) / 10.0)
59 #define MAXSHOWDEVS                             16
60
61 #if 0
62 #define FREEBSD_DEBUG
63 #endif
64
65 inline void proc_find_top(struct process **cpu, struct process **mem);
66
67 static short cpu_setup = 0;
68 static struct diskio_stat stats = {
69         .next = NULL,
70         .current = 0,
71         .current_read = 0,
72         .current_write = 0,
73         .last = UINT_MAX,
74         .last_read = UINT_MAX,
75         .last_write = UINT_MAX,
76 };
77
78 static int getsysctl(char *name, void *ptr, size_t len)
79 {
80         size_t nlen = len;
81
82         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
83                 return -1;
84         }
85
86         if (nlen != len && errno == ENOMEM) {
87                 return -1;
88         }
89
90         return 0;
91 }
92
93 struct ifmibdata *data = NULL;
94 size_t len = 0;
95
96 static int swapmode(unsigned long *retavail, unsigned long *retfree)
97 {
98         int n;
99         unsigned long pagesize = getpagesize();
100         struct kvm_swap swapary[1];
101
102         *retavail = 0;
103         *retfree = 0;
104
105 #define CONVERT(v)      ((quad_t)(v) * (pagesize / 1024))
106
107         n = kvm_getswapinfo(kd, swapary, 1, 0);
108         if (n < 0 || swapary[0].ksw_total == 0) {
109                 return 0;
110         }
111
112         *retavail = CONVERT(swapary[0].ksw_total);
113         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
114
115         n = (int) ((double) swapary[0].ksw_used * 100.0 /
116                 (double) swapary[0].ksw_total);
117
118         return n;
119 }
120
121 void prepare_update()
122 {
123 }
124
125 void update_uptime()
126 {
127         int mib[2] = { CTL_KERN, KERN_BOOTTIME };
128         struct timeval boottime;
129         time_t now;
130         size_t size = sizeof(boottime);
131
132         if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
133                         && (boottime.tv_sec != 0)) {
134                 time(&now);
135                 info.uptime = now - boottime.tv_sec;
136         } else {
137                 fprintf(stderr, "Could not get uptime\n");
138                 info.uptime = 0;
139         }
140 }
141
142 int check_mount(char *s)
143 {
144         struct statfs *mntbuf;
145         int i, mntsize;
146
147         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
148         for (i = mntsize - 1; i >= 0; i--) {
149                 if (strcmp(mntbuf[i].f_mntonname, s) == 0) {
150                         return 1;
151                 }
152         }
153
154         return 0;
155 }
156
157 void update_meminfo()
158 {
159         u_int total_pages, inactive_pages, free_pages;
160         unsigned long swap_avail, swap_free;
161
162         int pagesize = getpagesize();
163
164         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages)) {
165                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_page_count\"\n");
166         }
167
168         if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages)) {
169                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_free_count\"\n");
170         }
171
172         if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages)) {
173                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"\n");
174         }
175
176         info.memmax = total_pages * (pagesize >> 10);
177         info.mem = (total_pages - free_pages - inactive_pages) * (pagesize >> 10);
178         info.memeasyfree = info.memfree = info.memmax - info.mem;
179
180         if ((swapmode(&swap_avail, &swap_free)) >= 0) {
181                 info.swapmax = swap_avail;
182                 info.swap = (swap_avail - swap_free);
183         } else {
184                 info.swapmax = 0;
185                 info.swap = 0;
186         }
187 }
188
189 void update_net_stats()
190 {
191         struct net_stat *ns;
192         double delta;
193         long long r, t, last_recv, last_trans;
194         struct ifaddrs *ifap, *ifa;
195         struct if_data *ifd;
196
197         /* get delta */
198         delta = current_update_time - last_update_time;
199         if (delta <= 0.0001) {
200                 return;
201         }
202
203         if (getifaddrs(&ifap) < 0) {
204                 return;
205         }
206
207         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
208                 ns = get_net_stat((const char *) ifa->ifa_name);
209
210                 if (ifa->ifa_flags & IFF_UP) {
211                         struct ifaddrs *iftmp;
212
213                         ns->up = 1;
214                         last_recv = ns->recv;
215                         last_trans = ns->trans;
216
217                         if (ifa->ifa_addr->sa_family != AF_LINK) {
218                                 continue;
219                         }
220
221                         for (iftmp = ifa->ifa_next;
222                                         iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
223                                         iftmp = iftmp->ifa_next) {
224                                 if (iftmp->ifa_addr->sa_family == AF_INET) {
225                                         memcpy(&(ns->addr), iftmp->ifa_addr,
226                                                 iftmp->ifa_addr->sa_len);
227                                 }
228                         }
229
230                         ifd = (struct if_data *) ifa->ifa_data;
231                         r = ifd->ifi_ibytes;
232                         t = ifd->ifi_obytes;
233
234                         if (r < ns->last_read_recv) {
235                                 ns->recv += ((long long) 4294967295U - ns->last_read_recv) + r;
236                         } else {
237                                 ns->recv += (r - ns->last_read_recv);
238                         }
239
240                         ns->last_read_recv = r;
241
242                         if (t < ns->last_read_trans) {
243                                 ns->trans += ((long long) 4294967295U -
244                                         ns->last_read_trans) + t;
245                         } else {
246                                 ns->trans += (t - ns->last_read_trans);
247                         }
248
249                         ns->last_read_trans = t;
250
251                         /* calculate speeds */
252                         ns->recv_speed = (ns->recv - last_recv) / delta;
253                         ns->trans_speed = (ns->trans - last_trans) / delta;
254                 } else {
255                         ns->up = 0;
256                 }
257         }
258
259         freeifaddrs(ifap);
260 }
261
262 void update_total_processes()
263 {
264         int n_processes;
265
266         kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
267
268         info.procs = n_processes;
269 }
270
271 void update_running_processes()
272 {
273         struct kinfo_proc *p;
274         int n_processes;
275         int i, cnt = 0;
276
277         p = kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
278         for (i = 0; i < n_processes; i++) {
279 #if (__FreeBSD__ < 5) && (__FreeBSD_kernel__ < 5)
280                 if (p[i].kp_proc.p_stat == SRUN) {
281 #else
282                 if (p[i].ki_stat == SRUN) {
283 #endif
284                         cnt++;
285                 }
286         }
287
288         info.run_procs = cnt;
289 }
290
291 struct cpu_load_struct {
292         unsigned long load[5];
293 };
294
295 struct cpu_load_struct fresh = { {0, 0, 0, 0, 0} };
296 long cpu_used, oldtotal, oldused;
297
298 void get_cpu_count()
299 {
300         /* int cpu_count = 0; */
301
302         /* XXX: FreeBSD doesn't allow to get per CPU load stats on SMP machines.
303          * It's possible to get a CPU count, but as we fulfill only
304          * info.cpu_usage[0], it's better to report there's only one CPU.
305          * It should fix some bugs (e.g. cpugraph) */
306 #if 0
307         if (GETSYSCTL("hw.ncpu", cpu_count) == 0) {
308                 info.cpu_count = cpu_count;
309         }
310 #endif
311         info.cpu_count = 1;
312
313         info.cpu_usage = malloc(info.cpu_count * sizeof(float));
314         if (info.cpu_usage == NULL) {
315                 CRIT_ERR("malloc");
316         }
317 }
318
319 /* XXX: SMP support */
320 void update_cpu_usage()
321 {
322         long used, total;
323         long cp_time[CPUSTATES];
324         size_t len = sizeof(cp_time);
325
326         /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
327         if ((cpu_setup == 0) || (!info.cpu_usage)) {
328                 get_cpu_count();
329                 cpu_setup = 1;
330         }
331
332         if (sysctlbyname("kern.cp_time", &cp_time, &len, NULL, 0) < 0) {
333                 fprintf(stderr, "Cannot get kern.cp_time");
334         }
335
336         fresh.load[0] = cp_time[CP_USER];
337         fresh.load[1] = cp_time[CP_NICE];
338         fresh.load[2] = cp_time[CP_SYS];
339         fresh.load[3] = cp_time[CP_IDLE];
340         fresh.load[4] = cp_time[CP_IDLE];
341
342         used = fresh.load[0] + fresh.load[1] + fresh.load[2];
343         total = fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3];
344
345         if ((total - oldtotal) != 0) {
346                 info.cpu_usage[0] = ((double) (used - oldused)) /
347                         (double) (total - oldtotal);
348         } else {
349                 info.cpu_usage[0] = 0;
350         }
351
352         oldused = used;
353         oldtotal = total;
354 }
355
356 void update_load_average()
357 {
358         double v[3];
359
360         getloadavg(v, 3);
361
362         info.loadavg[0] = (double) v[0];
363         info.loadavg[1] = (double) v[1];
364         info.loadavg[2] = (double) v[2];
365 }
366
367 double get_acpi_temperature(int fd)
368 {
369         int temp;
370
371         if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
372                 fprintf(stderr,
373                         "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
374                 return 0.0;
375         }
376
377         return KELVTOC(temp);
378 }
379
380 static void get_battery_stats(int *battime, int *batcapacity, int *batstate, int *ac) {
381         if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) {
382                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.time\"\n");
383         }
384         if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) {
385                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.life\"\n");
386         }
387         if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) {
388                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.state\"\n");
389         }
390         if (ac && GETSYSCTL("hw.acpi.acline", *ac)) {
391                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
392         }
393 }
394
395 void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item)
396 {
397         int battime, batcapacity, batstate, ac;
398         char battery_status[64];
399         char battery_time[64];
400
401         get_battery_stats(&battime, &batcapacity, &batstate, &ac);
402
403         if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
404                 fprintf(stderr, "Unknown battery state %d!\n", batstate);
405         else if (batstate != 1 && ac == 0)
406                 fprintf(stderr, "Battery charging while not on AC!\n");
407         else if (batstate == 1 && ac == 1)
408                 fprintf(stderr, "Battery discharing while on AC!\n");
409
410         switch (item) {
411                 case BATTERY_TIME:
412                         if (batstate == 1 && battime != -1)
413                                 snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
414                         break;
415                 case BATTERY_STATUS:
416                         if (batstate == 1) // Discharging
417                                 snprintf(buf, n, "remaining %d%%", batcapacity);
418                         else
419                                 snprintf(buf, n, batstate == 2 ? "charging (%d%%)" :
420                                                 (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
421                                                 batcapacity);
422                         break;
423                 default:
424                         fprintf(stderr, "Unknown requested battery stat %d\n", item);
425         }
426 }
427
428 static int check_bat(const char *bat)
429 {
430         int batnum, numbatts;
431         char *endptr;
432         if (GETSYSCTL("hw.acpi.battery.units", numbatts)) {
433                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n");
434                 return -1;
435         }
436         if (numbatts <= 0) {
437                 fprintf(stderr, "No battery unit detected\n");
438                 return -1;
439         }
440         if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 ||
441                         bat == endptr || batnum > numbatts) {
442                 fprintf(stderr, "Wrong battery unit requested\n", bat);
443                 return -1;
444         }
445         return batnum;
446 }
447
448 int get_battery_perct(const char *bat)
449 {
450         union acpi_battery_ioctl_arg battio;
451         int batnum, numbatts, acpifd;
452         int designcap, lastfulcap, batperct;
453
454         if ((battio.unit = batnum = check_bat(bat)) < 0)
455                 return 0;
456         if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) {
457                 fprintf(stderr, "Can't open ACPI device\n");
458                 return 0;
459         }
460         if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) {
461                 fprintf(stderr, "Unable to get info for battery unit %d\n", batnum);
462                 return 0;
463         }
464         close(acpifd);
465         designcap = battio.bif.dcap;
466         lastfulcap = battio.bif.lfcap;
467         batperct = (designcap > 0 && lastfulcap > 0) ?
468                 (int) (((float) lastfulcap / designcap) * 100) : 0;
469         return batperct > 100 ? 100 : batperct;
470 }
471
472 int get_battery_perct_bar(const char *bar)
473 {
474         int batperct = get_battery_perct(bar);
475         return (int)(batperct * 2.56 - 1);
476 }
477
478 int open_acpi_temperature(const char *name)
479 {
480         /* Not applicable for FreeBSD. */
481         return 0;
482 }
483
484 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size)
485 {
486         int state;
487
488         if (!p_client_buffer || client_buffer_size <= 0) {
489                 return;
490         }
491
492         if (GETSYSCTL("hw.acpi.acline", state)) {
493                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
494                 return;
495         }
496
497         if (state) {
498                 strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
499         } else {
500                 strncpy(p_client_buffer, "Running on battery", client_buffer_size);
501         }
502 }
503
504 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
505 {
506         /* not implemented */
507         if (p_client_buffer && client_buffer_size > 0) {
508                 memset(p_client_buffer, 0, client_buffer_size);
509         }
510 }
511
512 void get_adt746x_cpu(char *p_client_buffer, size_t client_buffer_size)
513 {
514         /* not implemented */
515         if (p_client_buffer && client_buffer_size > 0) {
516                 memset(p_client_buffer, 0, client_buffer_size);
517         }
518 }
519
520 void get_adt746x_fan(char *p_client_buffer, size_t client_buffer_size)
521 {
522         /* not implemented */
523         if (p_client_buffer && client_buffer_size > 0) {
524                 memset(p_client_buffer, 0, client_buffer_size);
525         }
526 }
527
528 /* rdtsc() and get_freq_dynamic() copied from linux.c */
529
530 #if  defined(__i386) || defined(__x86_64)
531 __inline__ unsigned long long int rdtsc()
532 {
533         unsigned long long int x;
534
535         __asm__ volatile(".byte 0x0f, 0x31":"=A" (x));
536         return x;
537 }
538 #endif
539
540 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
541 void get_freq_dynamic(char *p_client_buffer, size_t client_buffer_size,
542                 const char *p_format, int divisor)
543 {
544 #if  defined(__i386) || defined(__x86_64)
545         struct timezone tz;
546         struct timeval tvstart, tvstop;
547         unsigned long long cycles[2];   /* gotta be 64 bit */
548         unsigned int microseconds;      /* total time taken */
549
550         memset(&tz, 0, sizeof(tz));
551
552         /* get this function in cached memory */
553         gettimeofday(&tvstart, &tz);
554         cycles[0] = rdtsc();
555         gettimeofday(&tvstart, &tz);
556
557         /* we don't trust that this is any specific length of time */
558         usleep(100);
559         cycles[1] = rdtsc();
560         gettimeofday(&tvstop, &tz);
561         microseconds = ((tvstop.tv_sec - tvstart.tv_sec) * 1000000) +
562                 (tvstop.tv_usec - tvstart.tv_usec);
563
564         snprintf(p_client_buffer, client_buffer_size, p_format,
565                 (float) ((cycles[1] - cycles[0]) / microseconds) / divisor);
566 #else
567         get_freq(p_client_buffer, client_buffer_size, p_format, divisor, 1);
568 #endif
569 }
570
571 /* void */
572 char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format,
573                 int divisor, unsigned int cpu)
574 {
575         int freq;
576         char *freq_sysctl;
577
578         freq_sysctl = (char *) calloc(16, sizeof(char));
579         if (freq_sysctl == NULL) {
580                 exit(-1);
581         }
582
583         snprintf(freq_sysctl, 16, "dev.cpu.%d.freq", (cpu - 1));
584
585         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
586                         || divisor <= 0) {
587                 return 0;
588         }
589
590         if (GETSYSCTL(freq_sysctl, freq) == 0) {
591                 snprintf(p_client_buffer, client_buffer_size, p_format,
592                         (float) freq / divisor);
593         } else {
594                 snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
595         }
596
597         free(freq_sysctl);
598         return 1;
599 }
600
601 void update_top()
602 {
603         proc_find_top(info.cpu, info.memu);
604 }
605
606 #if 0
607 void update_wifi_stats()
608 {
609         struct ifreq ifr;               /* interface stats */
610         struct wi_req wireq;
611         struct net_stat *ns;
612         struct ifaddrs *ifap, *ifa;
613         struct ifmediareq ifmr;
614         int s;
615
616         /* Get iface table */
617         if (getifaddrs(&ifap) < 0) {
618                 return;
619         }
620
621         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
622                 ns = get_net_stat((const char *) ifa->ifa_name);
623
624                 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
625
626                 /* Get media type */
627                 bzero(&ifmr, sizeof(ifmr));
628                 strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
629                 if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
630                         close(s);
631                         return;
632                 }
633
634                 /* We can monitor only wireless interfaces
635                  * which are not in hostap mode */
636                 if ((ifmr.ifm_active & IFM_IEEE80211)
637                                 && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
638                         /* Get wi status */
639                         bzero(&ifr, sizeof(ifr));
640                         strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
641                         wireq.wi_type = WI_RID_COMMS_QUALITY;
642                         wireq.wi_len = WI_MAX_DATALEN;
643                         ifr.ifr_data = (void *) &wireq;
644
645                         if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) {
646                                 perror("ioctl (getting wi status)");
647                                 exit(1);
648                         }
649
650                         /* wi_val[0] = quality
651                          * wi_val[1] = signal
652                          * wi_val[2] = noise */
653                         ns->linkstatus = (int) wireq.wi_val[1];
654                 }
655 cleanup:
656                 close(s);
657         }
658 }
659 #endif
660
661 void update_diskio()
662 {
663         int devs_count, num_selected, num_selections;
664         struct device_selection *dev_select = NULL;
665         long select_generation;
666         int dn;
667         static struct statinfo statinfo_cur;
668         struct diskio_stat *cur;
669
670         bzero(&statinfo_cur, sizeof(statinfo_cur));
671         statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
672         stats.current = stats.current_read = stats.current_write = 0;
673
674         if (devstat_getdevs(NULL, &statinfo_cur) < 0)
675                 return;
676
677         devs_count = statinfo_cur.dinfo->numdevs;
678         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
679                         &select_generation, statinfo_cur.dinfo->generation,
680                         statinfo_cur.dinfo->devices, devs_count, NULL, 0, NULL, 0,
681                         DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
682                 for (dn = 0; dn < devs_count; ++dn) {
683                         int di;
684                         struct devstat *dev;
685
686                         di = dev_select[dn].position;
687                         dev = &statinfo_cur.dinfo->devices[di];
688
689                         for (cur = stats.next; cur; cur = cur->next) {
690                                 if (cur->dev && !strcmp(dev_select[dn].device_name, cur->dev)) {
691                                         cur->current = (dev->bytes[DEVSTAT_READ] +
692                                                         dev->bytes[DEVSTAT_WRITE] - cur->last) / 1024;
693                                         cur->current_read = (dev->bytes[DEVSTAT_READ] -
694                                                         cur->last_read) / 1024;
695                                         cur->current_write = (dev->bytes[DEVSTAT_WRITE] -
696                                                         cur->last_write) / 1024;
697                                         if (dev->bytes[DEVSTAT_READ] + dev->bytes[DEVSTAT_WRITE] <
698                                                         cur->last) {
699                                                 cur->current = 0;
700                                         }
701                                         if (dev->bytes[DEVSTAT_READ] < cur->last_read) {
702                                                 cur->current_read = 0;
703                                                 cur->current = cur->current_write;
704                                         }
705                                         if (dev->bytes[DEVSTAT_WRITE] < cur->last_write) {
706                                                 cur->current_write = 0;
707                                                 cur->current = cur->current_read;
708                                         }
709                                         cur->last = dev->bytes[DEVSTAT_READ] +
710                                                 dev->bytes[DEVSTAT_WRITE];
711                                         cur->last_read = dev->bytes[DEVSTAT_READ];
712                                         cur->last_write = dev->bytes[DEVSTAT_WRITE];
713                                 }
714                         }
715                 }
716
717                 free(dev_select);
718         }
719
720         free(statinfo_cur.dinfo);
721 }
722
723 void clear_diskio_stats()
724 {
725         struct diskio_stat *cur;
726         while (stats.next) {
727                 cur = stats.next;
728                 stats.next = stats.next->next;
729                 free(cur);
730         }
731 }
732
733 struct diskio_stat *prepare_diskio_stat(const char *s)
734 {
735         struct diskio_stat *new = 0;
736         struct stat sb;
737         int found = 0;
738         char device[text_buffer_size], fbuf[text_buffer_size];
739         static int rep = 0;
740         /* lookup existing or get new */
741         struct diskio_stat *cur = &stats;
742
743         if (!s)
744                 return cur;
745
746         while (cur->next) {
747                 cur = cur->next;
748                 if (!strcmp(cur->dev, s))
749                         return cur;
750         }
751
752         /* new dev */
753         if (!(cur->next = calloc(1, sizeof(struct diskio_stat)))) {
754                 ERR("out of memory allocating new disk stats struct");
755                 return NULL;
756         }
757         cur = cur->next;
758         cur->last = cur->last_read = cur->last_write = UINT_MAX;
759         if (strncmp(s, "/dev/", 5) == 0) {
760                 // supplied a /dev/device arg, so cut off the /dev part
761                 cur->dev = strndup(s + 5, text_buffer_size);
762         } else {
763                 cur->dev = strndup(s, text_buffer_size);
764         }
765         /*
766          * check that device actually exists
767          */
768         snprintf(device, text_buffer_size, "/dev/%s", new->dev);
769
770         if (stat(device, &sb)) {
771                 ERR("diskio device '%s' does not exist", s);
772                 return 0;
773         }
774         return cur;
775 }
776
777 /* While topless is obviously better, top is also not bad. */
778
779 int comparecpu(const void *a, const void *b)
780 {
781         if (((struct process *)a)->amount > ((struct process *)b)->amount) {
782                 return -1;
783         } else if (((struct process *)a)->amount < ((struct process *)b)->amount) {
784                 return 1;
785         } else {
786                 return 0;
787         }
788 }
789
790 int comparemem(const void *a, const void *b)
791 {
792         if (((struct process *)a)->totalmem > ((struct process *)b)->totalmem) {
793                 return -1;
794         } else if (((struct process *)a)->totalmem < ((struct process *)b)->totalmem) {
795                 return 1;
796         } else {
797                 return 0;
798         }
799 }
800
801 inline void proc_find_top(struct process **cpu, struct process **mem)
802 {
803         struct kinfo_proc *p;
804         int n_processes;
805         int i, j = 0;
806         struct process *processes;
807
808         int total_pages;
809
810         /* we get total pages count again to be sure it is up to date */
811         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0) {
812                 CRIT_ERR("Cannot read sysctl \"vm.stats.vm.v_page_count\"");
813         }
814
815         p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
816         processes = malloc(n_processes * sizeof(struct process));
817
818         for (i = 0; i < n_processes; i++) {
819                 if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != NULL) {
820                         processes[j].pid = p[i].ki_pid;
821                         processes[j].name = strndup(p[i].ki_comm, text_buffer_size);
822                         processes[j].amount = 100.0 * p[i].ki_pctcpu / FSCALE;
823                         processes[j].totalmem = (float) (p[i].ki_rssize /
824                                 (float) total_pages) * 100.0;
825                         processes[j].vsize = p[i].ki_size;
826                         processes[j].rss = (p[i].ki_rssize * getpagesize());
827                         j++;
828                 }
829         }
830
831         qsort(processes, j - 1, sizeof(struct process), comparemem);
832         for (i = 0; i < 10 && i < n_processes; i++) {
833                 struct process *tmp, *ttmp;
834
835                 tmp = malloc(sizeof(struct process));
836                 tmp->pid = processes[i].pid;
837                 tmp->amount = processes[i].amount;
838                 tmp->totalmem = processes[i].totalmem;
839                 tmp->name = strndup(processes[i].name, text_buffer_size);
840                 tmp->rss = processes[i].rss;
841                 tmp->vsize = processes[i].vsize;
842
843                 ttmp = mem[i];
844                 mem[i] = tmp;
845                 if (ttmp != NULL) {
846                         free(ttmp->name);
847                         free(ttmp);
848                 }
849         }
850
851         qsort(processes, j - 1, sizeof(struct process), comparecpu);
852         for (i = 0; i < 10 && i < n_processes; i++) {
853                 struct process *tmp, *ttmp;
854
855                 tmp = malloc(sizeof(struct process));
856                 tmp->pid = processes[i].pid;
857                 tmp->amount = processes[i].amount;
858                 tmp->totalmem = processes[i].totalmem;
859                 tmp->name = strndup(processes[i].name, text_buffer_size);
860                 tmp->rss = processes[i].rss;
861                 tmp->vsize = processes[i].vsize;
862
863                 ttmp = cpu[i];
864                 cpu[i] = tmp;
865                 if (ttmp != NULL) {
866                         free(ttmp->name);
867                         free(ttmp);
868                 }
869         }
870
871 #if defined(FREEBSD_DEBUG)
872         printf("=====\nmem\n");
873         for (i = 0; i < 10; i++) {
874                 printf("%d: %s(%d) %.2f %ld %ld\n", i, mem[i]->name,
875                                 mem[i]->pid, mem[i]->totalmem, mem[i]->vsize, mem[i]->rss);
876         }
877 #endif
878
879         for (i = 0; i < j; i++) {
880                 free(processes[i].name);
881         }
882         free(processes);
883 }
884
885 #if     defined(i386) || defined(__i386__)
886 #define APMDEV          "/dev/apm"
887 #define APM_UNKNOWN     255
888
889 int apm_getinfo(int fd, apm_info_t aip)
890 {
891         if (ioctl(fd, APMIO_GETINFO, aip) == -1) {
892                 return -1;
893         }
894
895         return 0;
896 }
897
898 char *get_apm_adapter()
899 {
900         int fd;
901         struct apm_info info;
902         char *out;
903
904         out = (char *) calloc(16, sizeof(char));
905
906         fd = open(APMDEV, O_RDONLY);
907         if (fd < 0) {
908                 strncpy(out, "ERR", 16);
909                 return out;
910         }
911
912         if (apm_getinfo(fd, &info) != 0) {
913                 close(fd);
914                 strncpy(out, "ERR", 16);
915                 return out;
916         }
917         close(fd);
918
919         switch (info.ai_acline) {
920                 case 0:
921                         strncpy(out, "off-line", 16);
922                         return out;
923                         break;
924                 case 1:
925                         if (info.ai_batt_stat == 3) {
926                                 strncpy(out, "charging", 16);
927                                 return out;
928                         } else {
929                                 strncpy(out, "on-line", 16);
930                                 return out;
931                         }
932                         break;
933                 default:
934                         strncpy(out, "unknown", 16);
935                         return out;
936                         break;
937         }
938 }
939
940 char *get_apm_battery_life()
941 {
942         int fd;
943         u_int batt_life;
944         struct apm_info info;
945         char *out;
946
947         out = (char *) calloc(16, sizeof(char));
948
949         fd = open(APMDEV, O_RDONLY);
950         if (fd < 0) {
951                 strncpy(out, "ERR", 16);
952                 return out;
953         }
954
955         if (apm_getinfo(fd, &info) != 0) {
956                 close(fd);
957                 strncpy(out, "ERR", 16);
958                 return out;
959         }
960         close(fd);
961
962         batt_life = info.ai_batt_life;
963         if (batt_life == APM_UNKNOWN) {
964                 strncpy(out, "unknown", 16);
965         } else if (batt_life <= 100) {
966                 snprintf(out, 16, "%d%%", batt_life);
967                 return out;
968         } else {
969                 strncpy(out, "ERR", 16);
970         }
971
972         return out;
973 }
974
975 char *get_apm_battery_time()
976 {
977         int fd;
978         int batt_time;
979         int h, m, s;
980         struct apm_info info;
981         char *out;
982
983         out = (char *) calloc(16, sizeof(char));
984
985         fd = open(APMDEV, O_RDONLY);
986         if (fd < 0) {
987                 strncpy(out, "ERR", 16);
988                 return out;
989         }
990
991         if (apm_getinfo(fd, &info) != 0) {
992                 close(fd);
993                 strncpy(out, "ERR", 16);
994                 return out;
995         }
996         close(fd);
997
998         batt_time = info.ai_batt_time;
999
1000         if (batt_time == -1) {
1001                 strncpy(out, "unknown", 16);
1002         } else {
1003                 h = batt_time;
1004                 s = h % 60;
1005                 h /= 60;
1006                 m = h % 60;
1007                 h /= 60;
1008                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
1009         }
1010
1011         return out;
1012 }
1013
1014 #endif
1015
1016 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
1017 {
1018         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
1019         if (0 == strncmp("charging", buffer, 8)) {
1020                 buffer[0] = 'C';
1021                 memmove(buffer + 1, buffer + 8, n - 8);
1022         } else if (0 == strncmp("discharging", buffer, 11)) {
1023                 buffer[0] = 'D';
1024                 memmove(buffer + 1, buffer + 11, n - 11);
1025         } else if (0 == strncmp("absent/on AC", buffer, 12)) {
1026                 buffer[0] = 'A';
1027                 memmove(buffer + 1, buffer + 12, n - 12);
1028         }
1029 }
1030
1031 void update_entropy(void)
1032 {
1033         /* Not applicable for FreeBSD as it uses the yarrow prng. */
1034 }
1035
1036 /* empty stub so conky links */
1037 void free_all_processes(void)
1038 {
1039 }