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