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