Remove unused variables and rearrange includes.
[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/ioctl.h>
28 #include <sys/dkstat.h>
29 #include <sys/param.h>
30 #include <sys/resource.h>
31 #include <sys/socket.h>
32 #include <sys/stat.h>
33 #include <sys/sysctl.h>
34 #include <sys/time.h>
35 #include <sys/types.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
399         get_battery_stats(&battime, &batcapacity, &batstate, &ac);
400
401         if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
402                 fprintf(stderr, "Unknown battery state %d!\n", batstate);
403         else if (batstate != 1 && ac == 0)
404                 fprintf(stderr, "Battery charging while not on AC!\n");
405         else if (batstate == 1 && ac == 1)
406                 fprintf(stderr, "Battery discharing while on AC!\n");
407
408         switch (item) {
409                 case BATTERY_TIME:
410                         if (batstate == 1 && battime != -1)
411                                 snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
412                         break;
413                 case BATTERY_STATUS:
414                         if (batstate == 1) // Discharging
415                                 snprintf(buf, n, "remaining %d%%", batcapacity);
416                         else
417                                 snprintf(buf, n, batstate == 2 ? "charging (%d%%)" :
418                                                 (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
419                                                 batcapacity);
420                         break;
421                 default:
422                         fprintf(stderr, "Unknown requested battery stat %d\n", item);
423         }
424 }
425
426 static int check_bat(const char *bat)
427 {
428         int batnum, numbatts;
429         char *endptr;
430         if (GETSYSCTL("hw.acpi.battery.units", numbatts)) {
431                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n");
432                 return -1;
433         }
434         if (numbatts <= 0) {
435                 fprintf(stderr, "No battery unit detected\n");
436                 return -1;
437         }
438         if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 ||
439                         bat == endptr || batnum > numbatts) {
440                 fprintf(stderr, "Wrong battery unit %s requested\n", bat ? bat : "");
441                 return -1;
442         }
443         return batnum;
444 }
445
446 int get_battery_perct(const char *bat)
447 {
448         union acpi_battery_ioctl_arg battio;
449         int batnum, acpifd;
450         int designcap, lastfulcap, batperct;
451
452         if ((battio.unit = batnum = check_bat(bat)) < 0)
453                 return 0;
454         if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) {
455                 fprintf(stderr, "Can't open ACPI device\n");
456                 return 0;
457         }
458         if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) {
459                 fprintf(stderr, "Unable to get info for battery unit %d\n", batnum);
460                 return 0;
461         }
462         close(acpifd);
463         designcap = battio.bif.dcap;
464         lastfulcap = battio.bif.lfcap;
465         batperct = (designcap > 0 && lastfulcap > 0) ?
466                 (int) (((float) lastfulcap / designcap) * 100) : 0;
467         return batperct > 100 ? 100 : batperct;
468 }
469
470 int get_battery_perct_bar(const char *bar)
471 {
472         int batperct = get_battery_perct(bar);
473         return (int)(batperct * 2.56 - 1);
474 }
475
476 int open_acpi_temperature(const char *name)
477 {
478         /* Not applicable for FreeBSD. */
479         return 0;
480 }
481
482 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size)
483 {
484         int state;
485
486         if (!p_client_buffer || client_buffer_size <= 0) {
487                 return;
488         }
489
490         if (GETSYSCTL("hw.acpi.acline", state)) {
491                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
492                 return;
493         }
494
495         if (state) {
496                 strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
497         } else {
498                 strncpy(p_client_buffer, "Running on battery", client_buffer_size);
499         }
500 }
501
502 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
503 {
504         /* not implemented */
505         if (p_client_buffer && client_buffer_size > 0) {
506                 memset(p_client_buffer, 0, client_buffer_size);
507         }
508 }
509
510 void get_adt746x_cpu(char *p_client_buffer, size_t client_buffer_size)
511 {
512         /* not implemented */
513         if (p_client_buffer && client_buffer_size > 0) {
514                 memset(p_client_buffer, 0, client_buffer_size);
515         }
516 }
517
518 void get_adt746x_fan(char *p_client_buffer, size_t client_buffer_size)
519 {
520         /* not implemented */
521         if (p_client_buffer && client_buffer_size > 0) {
522                 memset(p_client_buffer, 0, client_buffer_size);
523         }
524 }
525
526 /* rdtsc() and get_freq_dynamic() copied from linux.c */
527
528 #if  defined(__i386) || defined(__x86_64)
529 __inline__ unsigned long long int rdtsc()
530 {
531         unsigned long long int x;
532
533         __asm__ volatile(".byte 0x0f, 0x31":"=A" (x));
534         return x;
535 }
536 #endif
537
538 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
539 void get_freq_dynamic(char *p_client_buffer, size_t client_buffer_size,
540                 const char *p_format, int divisor)
541 {
542 #if  defined(__i386) || defined(__x86_64)
543         struct timezone tz;
544         struct timeval tvstart, tvstop;
545         unsigned long long cycles[2];   /* gotta be 64 bit */
546         unsigned int microseconds;      /* total time taken */
547
548         memset(&tz, 0, sizeof(tz));
549
550         /* get this function in cached memory */
551         gettimeofday(&tvstart, &tz);
552         cycles[0] = rdtsc();
553         gettimeofday(&tvstart, &tz);
554
555         /* we don't trust that this is any specific length of time */
556         usleep(100);
557         cycles[1] = rdtsc();
558         gettimeofday(&tvstop, &tz);
559         microseconds = ((tvstop.tv_sec - tvstart.tv_sec) * 1000000) +
560                 (tvstop.tv_usec - tvstart.tv_usec);
561
562         snprintf(p_client_buffer, client_buffer_size, p_format,
563                 (float) ((cycles[1] - cycles[0]) / microseconds) / divisor);
564 #else
565         get_freq(p_client_buffer, client_buffer_size, p_format, divisor, 1);
566 #endif
567 }
568
569 /* void */
570 char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format,
571                 int divisor, unsigned int cpu)
572 {
573         int freq;
574         char *freq_sysctl;
575
576         freq_sysctl = (char *) calloc(16, sizeof(char));
577         if (freq_sysctl == NULL) {
578                 exit(-1);
579         }
580
581         snprintf(freq_sysctl, 16, "dev.cpu.%d.freq", (cpu - 1));
582
583         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
584                         || divisor <= 0) {
585                 return 0;
586         }
587
588         if (GETSYSCTL(freq_sysctl, freq) == 0) {
589                 snprintf(p_client_buffer, client_buffer_size, p_format,
590                         (float) freq / divisor);
591         } else {
592                 snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
593         }
594
595         free(freq_sysctl);
596         return 1;
597 }
598
599 void update_top()
600 {
601         proc_find_top(info.cpu, info.memu);
602 }
603
604 #if 0
605 void update_wifi_stats()
606 {
607         struct ifreq ifr;               /* interface stats */
608         struct wi_req wireq;
609         struct net_stat *ns;
610         struct ifaddrs *ifap, *ifa;
611         struct ifmediareq ifmr;
612         int s;
613
614         /* Get iface table */
615         if (getifaddrs(&ifap) < 0) {
616                 return;
617         }
618
619         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
620                 ns = get_net_stat((const char *) ifa->ifa_name);
621
622                 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
623
624                 /* Get media type */
625                 bzero(&ifmr, sizeof(ifmr));
626                 strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
627                 if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
628                         close(s);
629                         return;
630                 }
631
632                 /* We can monitor only wireless interfaces
633                  * which are not in hostap mode */
634                 if ((ifmr.ifm_active & IFM_IEEE80211)
635                                 && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
636                         /* Get wi status */
637                         bzero(&ifr, sizeof(ifr));
638                         strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
639                         wireq.wi_type = WI_RID_COMMS_QUALITY;
640                         wireq.wi_len = WI_MAX_DATALEN;
641                         ifr.ifr_data = (void *) &wireq;
642
643                         if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) {
644                                 perror("ioctl (getting wi status)");
645                                 exit(1);
646                         }
647
648                         /* wi_val[0] = quality
649                          * wi_val[1] = signal
650                          * wi_val[2] = noise */
651                         ns->linkstatus = (int) wireq.wi_val[1];
652                 }
653 cleanup:
654                 close(s);
655         }
656 }
657 #endif
658
659 void update_diskio()
660 {
661         int devs_count, num_selected, num_selections;
662         struct device_selection *dev_select = NULL;
663         long select_generation;
664         int dn;
665         static struct statinfo statinfo_cur;
666         struct diskio_stat *cur;
667
668         bzero(&statinfo_cur, sizeof(statinfo_cur));
669         statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
670         stats.current = stats.current_read = stats.current_write = 0;
671
672         if (devstat_getdevs(NULL, &statinfo_cur) < 0)
673                 return;
674
675         devs_count = statinfo_cur.dinfo->numdevs;
676         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
677                         &select_generation, statinfo_cur.dinfo->generation,
678                         statinfo_cur.dinfo->devices, devs_count, NULL, 0, NULL, 0,
679                         DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
680                 for (dn = 0; dn < devs_count; ++dn) {
681                         int di;
682                         struct devstat *dev;
683
684                         di = dev_select[dn].position;
685                         dev = &statinfo_cur.dinfo->devices[di];
686
687                         for (cur = stats.next; cur; cur = cur->next) {
688                                 if (cur->dev && !strcmp(dev_select[dn].device_name, cur->dev)) {
689                                         cur->current = (dev->bytes[DEVSTAT_READ] +
690                                                         dev->bytes[DEVSTAT_WRITE] - cur->last) / 1024;
691                                         cur->current_read = (dev->bytes[DEVSTAT_READ] -
692                                                         cur->last_read) / 1024;
693                                         cur->current_write = (dev->bytes[DEVSTAT_WRITE] -
694                                                         cur->last_write) / 1024;
695                                         if (dev->bytes[DEVSTAT_READ] + dev->bytes[DEVSTAT_WRITE] <
696                                                         cur->last) {
697                                                 cur->current = 0;
698                                         }
699                                         if (dev->bytes[DEVSTAT_READ] < cur->last_read) {
700                                                 cur->current_read = 0;
701                                                 cur->current = cur->current_write;
702                                         }
703                                         if (dev->bytes[DEVSTAT_WRITE] < cur->last_write) {
704                                                 cur->current_write = 0;
705                                                 cur->current = cur->current_read;
706                                         }
707                                         cur->last = dev->bytes[DEVSTAT_READ] +
708                                                 dev->bytes[DEVSTAT_WRITE];
709                                         cur->last_read = dev->bytes[DEVSTAT_READ];
710                                         cur->last_write = dev->bytes[DEVSTAT_WRITE];
711                                 }
712                         }
713                 }
714
715                 free(dev_select);
716         }
717
718         free(statinfo_cur.dinfo);
719 }
720
721 void clear_diskio_stats()
722 {
723         struct diskio_stat *cur;
724         while (stats.next) {
725                 cur = stats.next;
726                 stats.next = stats.next->next;
727                 free(cur);
728         }
729 }
730
731 struct diskio_stat *prepare_diskio_stat(const char *s)
732 {
733         struct diskio_stat *new = 0;
734         struct stat sb;
735         int found = 0;
736         char device[text_buffer_size], fbuf[text_buffer_size];
737         static int rep = 0;
738         /* lookup existing or get new */
739         struct diskio_stat *cur = &stats;
740
741         if (!s)
742                 return cur;
743
744         while (cur->next) {
745                 cur = cur->next;
746                 if (!strcmp(cur->dev, s))
747                         return cur;
748         }
749
750         /* new dev */
751         if (!(cur->next = calloc(1, sizeof(struct diskio_stat)))) {
752                 ERR("out of memory allocating new disk stats struct");
753                 return NULL;
754         }
755         cur = cur->next;
756         cur->last = cur->last_read = cur->last_write = UINT_MAX;
757         if (strncmp(s, "/dev/", 5) == 0) {
758                 // supplied a /dev/device arg, so cut off the /dev part
759                 cur->dev = strndup(s + 5, text_buffer_size);
760         } else {
761                 cur->dev = strndup(s, text_buffer_size);
762         }
763         /*
764          * check that device actually exists
765          */
766         snprintf(device, text_buffer_size, "/dev/%s", new->dev);
767
768         if (stat(device, &sb)) {
769                 ERR("diskio device '%s' does not exist", s);
770                 return 0;
771         }
772         return cur;
773 }
774
775 /* While topless is obviously better, top is also not bad. */
776
777 int comparecpu(const void *a, const void *b)
778 {
779         if (((struct process *)a)->amount > ((struct process *)b)->amount) {
780                 return -1;
781         } else if (((struct process *)a)->amount < ((struct process *)b)->amount) {
782                 return 1;
783         } else {
784                 return 0;
785         }
786 }
787
788 int comparemem(const void *a, const void *b)
789 {
790         if (((struct process *)a)->totalmem > ((struct process *)b)->totalmem) {
791                 return -1;
792         } else if (((struct process *)a)->totalmem < ((struct process *)b)->totalmem) {
793                 return 1;
794         } else {
795                 return 0;
796         }
797 }
798
799 inline void proc_find_top(struct process **cpu, struct process **mem)
800 {
801         struct kinfo_proc *p;
802         int n_processes;
803         int i, j = 0;
804         struct process *processes;
805
806         int total_pages;
807
808         /* we get total pages count again to be sure it is up to date */
809         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0) {
810                 CRIT_ERR("Cannot read sysctl \"vm.stats.vm.v_page_count\"");
811         }
812
813         p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
814         processes = malloc(n_processes * sizeof(struct process));
815
816         for (i = 0; i < n_processes; i++) {
817                 if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != NULL) {
818                         processes[j].pid = p[i].ki_pid;
819                         processes[j].name = strndup(p[i].ki_comm, text_buffer_size);
820                         processes[j].amount = 100.0 * p[i].ki_pctcpu / FSCALE;
821                         processes[j].totalmem = (float) (p[i].ki_rssize /
822                                 (float) total_pages) * 100.0;
823                         processes[j].vsize = p[i].ki_size;
824                         processes[j].rss = (p[i].ki_rssize * getpagesize());
825                         j++;
826                 }
827         }
828
829         qsort(processes, j - 1, sizeof(struct process), comparemem);
830         for (i = 0; i < 10 && i < n_processes; i++) {
831                 struct process *tmp, *ttmp;
832
833                 tmp = malloc(sizeof(struct process));
834                 tmp->pid = processes[i].pid;
835                 tmp->amount = processes[i].amount;
836                 tmp->totalmem = processes[i].totalmem;
837                 tmp->name = strndup(processes[i].name, text_buffer_size);
838                 tmp->rss = processes[i].rss;
839                 tmp->vsize = processes[i].vsize;
840
841                 ttmp = mem[i];
842                 mem[i] = tmp;
843                 if (ttmp != NULL) {
844                         free(ttmp->name);
845                         free(ttmp);
846                 }
847         }
848
849         qsort(processes, j - 1, sizeof(struct process), comparecpu);
850         for (i = 0; i < 10 && i < n_processes; i++) {
851                 struct process *tmp, *ttmp;
852
853                 tmp = malloc(sizeof(struct process));
854                 tmp->pid = processes[i].pid;
855                 tmp->amount = processes[i].amount;
856                 tmp->totalmem = processes[i].totalmem;
857                 tmp->name = strndup(processes[i].name, text_buffer_size);
858                 tmp->rss = processes[i].rss;
859                 tmp->vsize = processes[i].vsize;
860
861                 ttmp = cpu[i];
862                 cpu[i] = tmp;
863                 if (ttmp != NULL) {
864                         free(ttmp->name);
865                         free(ttmp);
866                 }
867         }
868
869 #if defined(FREEBSD_DEBUG)
870         printf("=====\nmem\n");
871         for (i = 0; i < 10; i++) {
872                 printf("%d: %s(%d) %.2f %ld %ld\n", i, mem[i]->name,
873                                 mem[i]->pid, mem[i]->totalmem, mem[i]->vsize, mem[i]->rss);
874         }
875 #endif
876
877         for (i = 0; i < j; i++) {
878                 free(processes[i].name);
879         }
880         free(processes);
881 }
882
883 #if     defined(i386) || defined(__i386__)
884 #define APMDEV          "/dev/apm"
885 #define APM_UNKNOWN     255
886
887 int apm_getinfo(int fd, apm_info_t aip)
888 {
889         if (ioctl(fd, APMIO_GETINFO, aip) == -1) {
890                 return -1;
891         }
892
893         return 0;
894 }
895
896 char *get_apm_adapter()
897 {
898         int fd;
899         struct apm_info info;
900         char *out;
901
902         out = (char *) calloc(16, sizeof(char));
903
904         fd = open(APMDEV, O_RDONLY);
905         if (fd < 0) {
906                 strncpy(out, "ERR", 16);
907                 return out;
908         }
909
910         if (apm_getinfo(fd, &info) != 0) {
911                 close(fd);
912                 strncpy(out, "ERR", 16);
913                 return out;
914         }
915         close(fd);
916
917         switch (info.ai_acline) {
918                 case 0:
919                         strncpy(out, "off-line", 16);
920                         return out;
921                         break;
922                 case 1:
923                         if (info.ai_batt_stat == 3) {
924                                 strncpy(out, "charging", 16);
925                                 return out;
926                         } else {
927                                 strncpy(out, "on-line", 16);
928                                 return out;
929                         }
930                         break;
931                 default:
932                         strncpy(out, "unknown", 16);
933                         return out;
934                         break;
935         }
936 }
937
938 char *get_apm_battery_life()
939 {
940         int fd;
941         u_int batt_life;
942         struct apm_info info;
943         char *out;
944
945         out = (char *) calloc(16, sizeof(char));
946
947         fd = open(APMDEV, O_RDONLY);
948         if (fd < 0) {
949                 strncpy(out, "ERR", 16);
950                 return out;
951         }
952
953         if (apm_getinfo(fd, &info) != 0) {
954                 close(fd);
955                 strncpy(out, "ERR", 16);
956                 return out;
957         }
958         close(fd);
959
960         batt_life = info.ai_batt_life;
961         if (batt_life == APM_UNKNOWN) {
962                 strncpy(out, "unknown", 16);
963         } else if (batt_life <= 100) {
964                 snprintf(out, 16, "%d%%", batt_life);
965                 return out;
966         } else {
967                 strncpy(out, "ERR", 16);
968         }
969
970         return out;
971 }
972
973 char *get_apm_battery_time()
974 {
975         int fd;
976         int batt_time;
977         int h, m, s;
978         struct apm_info info;
979         char *out;
980
981         out = (char *) calloc(16, sizeof(char));
982
983         fd = open(APMDEV, O_RDONLY);
984         if (fd < 0) {
985                 strncpy(out, "ERR", 16);
986                 return out;
987         }
988
989         if (apm_getinfo(fd, &info) != 0) {
990                 close(fd);
991                 strncpy(out, "ERR", 16);
992                 return out;
993         }
994         close(fd);
995
996         batt_time = info.ai_batt_time;
997
998         if (batt_time == -1) {
999                 strncpy(out, "unknown", 16);
1000         } else {
1001                 h = batt_time;
1002                 s = h % 60;
1003                 h /= 60;
1004                 m = h % 60;
1005                 h /= 60;
1006                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
1007         }
1008
1009         return out;
1010 }
1011
1012 #endif
1013
1014 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
1015 {
1016         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
1017         if (0 == strncmp("charging", buffer, 8)) {
1018                 buffer[0] = 'C';
1019                 memmove(buffer + 1, buffer + 8, n - 8);
1020         } else if (0 == strncmp("discharging", buffer, 11)) {
1021                 buffer[0] = 'D';
1022                 memmove(buffer + 1, buffer + 11, n - 11);
1023         } else if (0 == strncmp("absent/on AC", buffer, 12)) {
1024                 buffer[0] = 'A';
1025                 memmove(buffer + 1, buffer + 12, n - 12);
1026         }
1027 }
1028
1029 void update_entropy(void)
1030 {
1031         /* Not applicable for FreeBSD as it uses the yarrow prng. */
1032 }
1033
1034 /* empty stub so conky links */
1035 void free_all_processes(void)
1036 {
1037 }