kvm_proc needs synchronized access
[monky] / src / freebsd.c
1 /* -*- mode: c; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: t -*-
2  * vim: ts=4 sw=4 noet ai cindent syntax=c
3  *
4  * Conky, a system monitor, based on torsmo
5  *
6  * Any original torsmo code is licensed under the BSD license
7  *
8  * All code written since the fork of torsmo is licensed under the GPL
9  *
10  * Please see COPYING for details
11  *
12  * Copyright (c) 2005-2010 Brenden Matthews, Philip Kovacs, et. al.
13  *      (see AUTHORS)
14  * All rights reserved.
15  *
16  * This program is free software: you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation, either version 3 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24  * GNU General Public License for more details.
25  * You should have received a copy of the GNU General Public License
26  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
27  *
28  */
29
30 #include <sys/ioctl.h>
31 #include <sys/dkstat.h>
32 #include <sys/param.h>
33 #include <sys/resource.h>
34 #include <sys/socket.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <sys/user.h>
40
41 #include <net/if.h>
42 #include <net/if_mib.h>
43 #include <net/if_media.h>
44 #include <net/if_var.h>
45
46 #include <devstat.h>
47 #include <ifaddrs.h>
48 #include <limits.h>
49 #include <unistd.h>
50
51 #include <dev/wi/if_wavelan_ieee.h>
52 #include <dev/acpica/acpiio.h>
53
54 #include "conky.h"
55 #include "freebsd.h"
56 #include "logging.h"
57 #include "net_stat.h"
58 #include "top.h"
59 #include "diskio.h"
60
61 #define GETSYSCTL(name, var)    getsysctl(name, &(var), sizeof(var))
62 #define KELVTOC(x)                              ((x - 2732) / 10.0)
63 #define MAXSHOWDEVS                             16
64
65 #if 0
66 #define FREEBSD_DEBUG
67 #endif
68
69 __attribute__((gnu_inline)) inline void
70 proc_find_top(struct process **cpu, struct process **mem, struct process **time);
71
72 static short cpu_setup = 0;
73
74 static int getsysctl(const char *name, void *ptr, size_t len)
75 {
76         size_t nlen = len;
77
78         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
79                 return -1;
80         }
81
82         if (nlen != len && errno == ENOMEM) {
83                 return -1;
84         }
85
86         return 0;
87 }
88
89 struct ifmibdata *data = NULL;
90 size_t len = 0;
91
92 static int swapmode(unsigned long *retavail, unsigned long *retfree)
93 {
94         int n;
95         unsigned long pagesize = getpagesize();
96         struct kvm_swap swapary[1];
97
98         *retavail = 0;
99         *retfree = 0;
100
101 #define CONVERT(v)      ((quad_t)(v) * (pagesize / 1024))
102
103         n = kvm_getswapinfo(kd, swapary, 1, 0);
104         if (n < 0 || swapary[0].ksw_total == 0) {
105                 return 0;
106         }
107
108         *retavail = CONVERT(swapary[0].ksw_total);
109         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
110
111         n = (int) ((double) swapary[0].ksw_used * 100.0 /
112                 (double) swapary[0].ksw_total);
113
114         return n;
115 }
116
117 void prepare_update(void)
118 {
119 }
120
121 int update_uptime(void)
122 {
123         int mib[2] = { CTL_KERN, KERN_BOOTTIME };
124         struct timeval boottime;
125         time_t now;
126         size_t size = sizeof(boottime);
127
128         if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
129                         && (boottime.tv_sec != 0)) {
130                 time(&now);
131                 info.uptime = now - boottime.tv_sec;
132         } else {
133                 fprintf(stderr, "Could not get uptime\n");
134                 info.uptime = 0;
135         }
136
137         return 0;
138 }
139
140 int check_mount(char *s)
141 {
142         struct statfs *mntbuf;
143         int i, mntsize;
144
145         mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
146         for (i = mntsize - 1; i >= 0; i--) {
147                 if (strcmp(mntbuf[i].f_mntonname, s) == 0) {
148                         return 1;
149                 }
150         }
151
152         return 0;
153 }
154
155 int update_meminfo(void)
156 {
157         u_int total_pages, inactive_pages, free_pages;
158         unsigned long swap_avail, swap_free;
159
160         int pagesize = getpagesize();
161
162         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages)) {
163                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_page_count\"\n");
164         }
165
166         if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages)) {
167                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_free_count\"\n");
168         }
169
170         if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages)) {
171                 fprintf(stderr, "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"\n");
172         }
173
174         info.memmax = total_pages * (pagesize >> 10);
175         info.mem = (total_pages - free_pages - inactive_pages) * (pagesize >> 10);
176         info.memeasyfree = info.memfree = info.memmax - info.mem;
177
178         if ((swapmode(&swap_avail, &swap_free)) >= 0) {
179                 info.swapmax = swap_avail;
180                 info.swap = (swap_avail - swap_free);
181                 info.swapfree = swap_free;
182         } else {
183                 info.swapmax = 0;
184                 info.swap = 0;
185                 info.swapfree = 0;
186         }
187
188         return 0;
189 }
190
191 int update_net_stats(void)
192 {
193         struct net_stat *ns;
194         double delta;
195         long long r, t, last_recv, last_trans;
196         struct ifaddrs *ifap, *ifa;
197         struct if_data *ifd;
198
199         /* get delta */
200         delta = current_update_time - last_update_time;
201         if (delta <= 0.0001) {
202                 return 0;
203         }
204
205         if (getifaddrs(&ifap) < 0) {
206                 return 0;
207         }
208
209         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
210                 ns = get_net_stat((const char *) ifa->ifa_name, NULL, NULL);
211
212                 if (ifa->ifa_flags & IFF_UP) {
213                         struct ifaddrs *iftmp;
214
215                         ns->up = 1;
216                         last_recv = ns->recv;
217                         last_trans = ns->trans;
218
219                         if (ifa->ifa_addr->sa_family != AF_LINK) {
220                                 continue;
221                         }
222
223                         for (iftmp = ifa->ifa_next;
224                                         iftmp != NULL && strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
225                                         iftmp = iftmp->ifa_next) {
226                                 if (iftmp->ifa_addr->sa_family == AF_INET) {
227                                         memcpy(&(ns->addr), iftmp->ifa_addr,
228                                                 iftmp->ifa_addr->sa_len);
229                                 }
230                         }
231
232                         ifd = (struct if_data *) ifa->ifa_data;
233                         r = ifd->ifi_ibytes;
234                         t = ifd->ifi_obytes;
235
236                         if (r < ns->last_read_recv) {
237                                 ns->recv += ((long long) 4294967295U - ns->last_read_recv) + r;
238                         } else {
239                                 ns->recv += (r - ns->last_read_recv);
240                         }
241
242                         ns->last_read_recv = r;
243
244                         if (t < ns->last_read_trans) {
245                                 ns->trans += ((long long) 4294967295U -
246                                         ns->last_read_trans) + t;
247                         } else {
248                                 ns->trans += (t - ns->last_read_trans);
249                         }
250
251                         ns->last_read_trans = t;
252
253                         /* calculate speeds */
254                         ns->recv_speed = (ns->recv - last_recv) / delta;
255                         ns->trans_speed = (ns->trans - last_trans) / delta;
256                 } else {
257                         ns->up = 0;
258                 }
259         }
260
261         freeifaddrs(ifap);
262         return 0;
263 }
264
265 int update_total_processes(void)
266 {
267         int n_processes;
268
269         pthread_mutex_lock(&kvm_proc_mutex);
270         kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
271         pthread_mutex_unlock(&kvm_proc_mutex);
272
273         info.procs = n_processes;
274         return 0;
275 }
276
277 int update_running_processes(void)
278 {
279         struct kinfo_proc *p;
280         int n_processes;
281         int i, cnt = 0;
282
283         pthread_mutex_lock(&kvm_proc_mutex);
284         p = kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
285         for (i = 0; i < n_processes; i++) {
286 #if (__FreeBSD__ < 5) && (__FreeBSD_kernel__ < 5)
287                 if (p[i].kp_proc.p_stat == SRUN) {
288 #else
289                 if (p[i].ki_stat == SRUN) {
290 #endif
291                         cnt++;
292                 }
293         }
294         pthread_mutex_unlock(&kvm_proc_mutex);
295
296         info.run_procs = cnt;
297         return 0;
298 }
299
300 void get_cpu_count(void)
301 {
302         int cpu_count = 0;
303         size_t cpu_count_len = sizeof(cpu_count);
304
305         if (GETSYSCTL("hw.ncpu", cpu_count) == 0) {
306                 info.cpu_count = cpu_count;
307         } else {
308                 fprintf(stderr, "Cannot get hw.ncpu\n");
309                 info.cpu_count = 0;
310         }
311
312         info.cpu_usage = malloc((info.cpu_count + 1) * sizeof(float));
313         if (info.cpu_usage == NULL) {
314                 CRIT_ERR(NULL, NULL, "malloc");
315         }
316 }
317
318 struct cpu_info {
319         long oldtotal;
320         long oldused;
321 };
322
323 int update_cpu_usage(void)
324 {
325         int i, j = 0;
326         long used, total;
327         long *cp_time = NULL;
328         size_t cp_len;
329         static struct cpu_info *cpu = NULL;
330         unsigned int malloc_cpu_size = 0;
331         extern void* global_cpu;
332
333         /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
334         if ((cpu_setup == 0) || (!info.cpu_usage)) {
335                 get_cpu_count();
336                 cpu_setup = 1;
337         }
338
339         if (!global_cpu) {
340                 malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
341                 cpu = malloc(malloc_cpu_size);
342                 memset(cpu, 0, malloc_cpu_size);
343                 global_cpu = cpu;
344         }
345
346         /* cpu[0] is overall stats, get it from separate sysctl */
347         cp_len = CPUSTATES * sizeof(long);
348         cp_time = malloc(cp_len);
349
350         if (sysctlbyname("kern.cp_time", cp_time, &cp_len, NULL, 0) < 0) {
351                 fprintf(stderr, "Cannot get kern.cp_time\n");
352         }
353
354         total = 0;
355         for (j = 0; j < CPUSTATES; j++)
356                 total += cp_time[j];
357
358         used = total - cp_time[CP_IDLE];
359
360         if ((total - cpu[0].oldtotal) != 0) {
361                 info.cpu_usage[0] = ((double) (used - cpu[0].oldused)) /
362                 (double) (total - cpu[0].oldtotal);
363         } else {
364                 info.cpu_usage[0] = 0;
365         }
366
367         cpu[0].oldused = used;
368         cpu[0].oldtotal = total;
369
370         free(cp_time);
371
372         /* per-core stats */
373         cp_len = CPUSTATES * sizeof(long) * info.cpu_count;
374         cp_time = malloc(cp_len);
375
376         /* on e.g. i386 SMP we may have more values than actual cpus; this will just drop extra values */
377         if (sysctlbyname("kern.cp_times", cp_time, &cp_len, NULL, 0) < 0 && errno != ENOMEM) {
378                 fprintf(stderr, "Cannot get kern.cp_times\n");
379         }
380
381         for (i = 0; i < info.cpu_count; i++)
382         {
383                 total = 0;
384                 for (j = 0; j < CPUSTATES; j++)
385                         total += cp_time[i*CPUSTATES + j];
386
387                 used = total - cp_time[i*CPUSTATES + CP_IDLE];
388
389                 if ((total - cpu[i+1].oldtotal) != 0) {
390                         info.cpu_usage[i+1] = ((double) (used - cpu[i+1].oldused)) /
391                         (double) (total - cpu[i+1].oldtotal);
392                 } else {
393                         info.cpu_usage[i+1] = 0;
394                 }
395
396                 cpu[i+1].oldused = used;
397                 cpu[i+1].oldtotal = total;
398         }
399
400         free(cp_time);
401         return 0;
402 }
403
404 int update_load_average(void)
405 {
406         double v[3];
407
408         getloadavg(v, 3);
409
410         info.loadavg[0] = (double) v[0];
411         info.loadavg[1] = (double) v[1];
412         info.loadavg[2] = (double) v[2];
413
414         return 0;
415 }
416
417 double get_acpi_temperature(int fd)
418 {
419         int temp;
420         (void)fd;
421
422         if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
423                 fprintf(stderr,
424                         "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
425                 return 0.0;
426         }
427
428         return KELVTOC(temp);
429 }
430
431 static void get_battery_stats(int *battime, int *batcapacity, int *batstate, int *ac) {
432         if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) {
433                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.time\"\n");
434         }
435         if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) {
436                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.life\"\n");
437         }
438         if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) {
439                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.state\"\n");
440         }
441         if (ac && GETSYSCTL("hw.acpi.acline", *ac)) {
442                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
443         }
444 }
445
446 void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item)
447 {
448         int battime, batcapacity, batstate, ac;
449         (void)bat;
450
451         get_battery_stats(&battime, &batcapacity, &batstate, &ac);
452
453         if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
454                 fprintf(stderr, "Unknown battery state %d!\n", batstate);
455         else if (batstate != 1 && ac == 0)
456                 fprintf(stderr, "Battery charging while not on AC!\n");
457         else if (batstate == 1 && ac == 1)
458                 fprintf(stderr, "Battery discharing while on AC!\n");
459
460         switch (item) {
461                 case BATTERY_TIME:
462                         if (batstate == 1 && battime != -1)
463                                 snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
464                         break;
465                 case BATTERY_STATUS:
466                         if (batstate == 1) // Discharging
467                                 snprintf(buf, n, "remaining %d%%", batcapacity);
468                         else
469                                 snprintf(buf, n, batstate == 2 ? "charging (%d%%)" :
470                                                 (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
471                                                 batcapacity);
472                         break;
473                 default:
474                         fprintf(stderr, "Unknown requested battery stat %d\n", item);
475         }
476 }
477
478 static int check_bat(const char *bat)
479 {
480         int batnum, numbatts;
481         char *endptr;
482         if (GETSYSCTL("hw.acpi.battery.units", numbatts)) {
483                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n");
484                 return -1;
485         }
486         if (numbatts <= 0) {
487                 fprintf(stderr, "No battery unit detected\n");
488                 return -1;
489         }
490         if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 ||
491                         bat == endptr || batnum > numbatts) {
492                 fprintf(stderr, "Wrong battery unit %s requested\n", bat ? bat : "");
493                 return -1;
494         }
495         return batnum;
496 }
497
498 int get_battery_perct(const char *bat)
499 {
500         union acpi_battery_ioctl_arg battio;
501         int batnum, acpifd;
502         int designcap, lastfulcap, batperct;
503
504         if ((battio.unit = batnum = check_bat(bat)) < 0)
505                 return 0;
506         if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) {
507                 fprintf(stderr, "Can't open ACPI device\n");
508                 return 0;
509         }
510         if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) {
511                 fprintf(stderr, "Unable to get info for battery unit %d\n", batnum);
512                 return 0;
513         }
514         close(acpifd);
515         designcap = battio.bif.dcap;
516         lastfulcap = battio.bif.lfcap;
517         batperct = (designcap > 0 && lastfulcap > 0) ?
518                 (int) (((float) lastfulcap / designcap) * 100) : 0;
519         return batperct > 100 ? 100 : batperct;
520 }
521
522 int get_battery_perct_bar(const char *bar)
523 {
524         int batperct = get_battery_perct(bar);
525         return (int)(batperct * 2.56 - 1);
526 }
527
528 int open_acpi_temperature(const char *name)
529 {
530         (void)name;
531         /* Not applicable for FreeBSD. */
532         return 0;
533 }
534
535 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, const char *adapter)
536 {
537         int state;
538
539         (void) adapter; // only linux uses this
540
541         if (!p_client_buffer || client_buffer_size <= 0) {
542                 return;
543         }
544
545         if (GETSYSCTL("hw.acpi.acline", state)) {
546                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
547                 return;
548         }
549
550         if (state) {
551                 strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
552         } else {
553                 strncpy(p_client_buffer, "Running on battery", client_buffer_size);
554         }
555 }
556
557 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
558 {
559         /* not implemented */
560         if (p_client_buffer && client_buffer_size > 0) {
561                 memset(p_client_buffer, 0, client_buffer_size);
562         }
563 }
564
565 /* void */
566 char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format,
567                 int divisor, unsigned int cpu)
568 {
569         int freq;
570         char *freq_sysctl;
571
572         freq_sysctl = (char *) calloc(16, sizeof(char));
573         if (freq_sysctl == NULL) {
574                 exit(-1);
575         }
576
577         snprintf(freq_sysctl, 16, "dev.cpu.%d.freq", (cpu - 1));
578
579         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
580                         || divisor <= 0) {
581                 return 0;
582         }
583
584         if (GETSYSCTL(freq_sysctl, freq) == 0) {
585                 snprintf(p_client_buffer, client_buffer_size, p_format,
586                         (float) freq / divisor);
587         } else {
588                 snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
589         }
590
591         free(freq_sysctl);
592         return 1;
593 }
594
595 int update_top(void)
596 {
597         proc_find_top(info.cpu, info.memu, info.time);
598         return 0;
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 int 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 0;
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         return 0;
707 }
708
709 /* While topless is obviously better, top is also not bad. */
710
711 int comparecpu(const void *a, const void *b)
712 {
713         if (((const struct process *)a)->amount > ((const struct process *)b)->amount) {
714                 return -1;
715         } else if (((const struct process *)a)->amount < ((const struct process *)b)->amount) {
716                 return 1;
717         } else {
718                 return 0;
719         }
720 }
721
722 int comparemem(const void *a, const void *b)
723 {
724         if (((const struct process *)a)->rss > ((const struct process *)b)->rss) {
725                 return -1;
726         } else if (((const struct process *)a)->rss < ((const struct process *)b)->rss) {
727                 return 1;
728         } else {
729                 return 0;
730         }
731 }
732
733 int comparetime(const void *va, const void *vb)
734 {
735         struct process *a = (struct process *)va, *b = (struct process *)vb;
736
737         return b->total_cpu_time - a->total_cpu_time;
738 }
739
740 __attribute__((gnu_inline)) inline void
741 proc_find_top(struct process **cpu, struct process **mem, struct process **time)
742 {
743         struct kinfo_proc *p;
744         int n_processes;
745         int i, j = 0;
746         struct process *processes;
747
748         int total_pages;
749
750         /* we get total pages count again to be sure it is up to date */
751         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0) {
752                 CRIT_ERR(NULL, NULL, "Cannot read sysctl \"vm.stats.vm.v_page_count\"");
753         }
754
755         pthread_mutex_lock(&kvm_proc_mutex);
756         p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
757         processes = malloc(n_processes * sizeof(struct process));
758
759         for (i = 0; i < n_processes; i++) {
760                 if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != NULL) {
761                         processes[j].pid = p[i].ki_pid;
762                         processes[j].name = strndup(p[i].ki_comm, text_buffer_size);
763                         processes[j].amount = 100.0 * p[i].ki_pctcpu / FSCALE;
764                         processes[j].vsize = p[i].ki_size;
765                         processes[j].rss = (p[i].ki_rssize * getpagesize());
766                         /* ki_runtime is in microseconds, total_cpu_time in centiseconds.
767                          * Therefore we divide by 10000. */
768                         processes[j].total_cpu_time = p[i].ki_runtime / 10000;
769                         j++;
770                 }
771         }
772         pthread_mutex_unlock(&kvm_proc_mutex);
773
774         qsort(processes, j - 1, sizeof(struct process), comparemem);
775         for (i = 0; i < 10 && i < n_processes; i++) {
776                 struct process *tmp, *ttmp;
777
778                 tmp = malloc(sizeof(struct process));
779                 memcpy(tmp, &processes[i], sizeof(struct process));
780                 tmp->name = strndup(processes[i].name, text_buffer_size);
781
782                 ttmp = mem[i];
783                 mem[i] = tmp;
784                 if (ttmp != NULL) {
785                         free(ttmp->name);
786                         free(ttmp);
787                 }
788         }
789
790         qsort(processes, j - 1, sizeof(struct process), comparecpu);
791         for (i = 0; i < 10 && i < n_processes; i++) {
792                 struct process *tmp, *ttmp;
793
794                 tmp = malloc(sizeof(struct process));
795                 memcpy(tmp, &processes[i], sizeof(struct process));
796                 tmp->name = strndup(processes[i].name, text_buffer_size);
797
798                 ttmp = cpu[i];
799                 cpu[i] = tmp;
800                 if (ttmp != NULL) {
801                         free(ttmp->name);
802                         free(ttmp);
803                 }
804         }
805
806         qsort(processes, j - 1, sizeof(struct process), comparetime);
807         for (i = 0; i < 10 && i < n_processes; i++) {
808                 struct process *tmp, *ttmp;
809
810                 tmp = malloc(sizeof(struct process));
811                 memcpy(tmp, &processes[i], sizeof(struct process));
812                 tmp->name = strndup(processes[i].name, text_buffer_size);
813
814                 ttmp = time[i];
815                 time[i] = tmp;
816                 if (ttmp != NULL) {
817                         free(ttmp->name);
818                         free(ttmp);
819                 }
820         }
821
822 #if defined(FREEBSD_DEBUG)
823         printf("=====\nmem\n");
824         for (i = 0; i < 10; i++) {
825                 printf("%d: %s(%d) %ld %ld\n", i, mem[i]->name,
826                                 mem[i]->pid, mem[i]->vsize, mem[i]->rss);
827         }
828 #endif
829
830         for (i = 0; i < j; i++) {
831                 free(processes[i].name);
832         }
833         free(processes);
834 }
835
836 #if     defined(i386) || defined(__i386__)
837 #define APMDEV          "/dev/apm"
838 #define APM_UNKNOWN     255
839
840 int apm_getinfo(int fd, apm_info_t aip)
841 {
842         if (ioctl(fd, APMIO_GETINFO, aip) == -1) {
843                 return -1;
844         }
845
846         return 0;
847 }
848
849 char *get_apm_adapter(void)
850 {
851         int fd;
852         struct apm_info a_info;
853         char *out;
854
855         out = (char *) calloc(16, sizeof(char));
856
857         fd = open(APMDEV, O_RDONLY);
858         if (fd < 0) {
859                 strncpy(out, "ERR", 16);
860                 return out;
861         }
862
863         if (apm_getinfo(fd, &a_info) != 0) {
864                 close(fd);
865                 strncpy(out, "ERR", 16);
866                 return out;
867         }
868         close(fd);
869
870         switch (a_info.ai_acline) {
871                 case 0:
872                         strncpy(out, "off-line", 16);
873                         return out;
874                         break;
875                 case 1:
876                         if (a_info.ai_batt_stat == 3) {
877                                 strncpy(out, "charging", 16);
878                                 return out;
879                         } else {
880                                 strncpy(out, "on-line", 16);
881                                 return out;
882                         }
883                         break;
884                 default:
885                         strncpy(out, "unknown", 16);
886                         return out;
887                         break;
888         }
889 }
890
891 char *get_apm_battery_life(void)
892 {
893         int fd;
894         u_int batt_life;
895         struct apm_info a_info;
896         char *out;
897
898         out = (char *) calloc(16, sizeof(char));
899
900         fd = open(APMDEV, O_RDONLY);
901         if (fd < 0) {
902                 strncpy(out, "ERR", 16);
903                 return out;
904         }
905
906         if (apm_getinfo(fd, &a_info) != 0) {
907                 close(fd);
908                 strncpy(out, "ERR", 16);
909                 return out;
910         }
911         close(fd);
912
913         batt_life = a_info.ai_batt_life;
914         if (batt_life == APM_UNKNOWN) {
915                 strncpy(out, "unknown", 16);
916         } else if (batt_life <= 100) {
917                 snprintf(out, 16, "%d%%", batt_life);
918                 return out;
919         } else {
920                 strncpy(out, "ERR", 16);
921         }
922
923         return out;
924 }
925
926 char *get_apm_battery_time(void)
927 {
928         int fd;
929         int batt_time;
930         int h, m, s;
931         struct apm_info a_info;
932         char *out;
933
934         out = (char *) calloc(16, sizeof(char));
935
936         fd = open(APMDEV, O_RDONLY);
937         if (fd < 0) {
938                 strncpy(out, "ERR", 16);
939                 return out;
940         }
941
942         if (apm_getinfo(fd, &a_info) != 0) {
943                 close(fd);
944                 strncpy(out, "ERR", 16);
945                 return out;
946         }
947         close(fd);
948
949         batt_time = a_info.ai_batt_time;
950
951         if (batt_time == -1) {
952                 strncpy(out, "unknown", 16);
953         } else {
954                 h = batt_time;
955                 s = h % 60;
956                 h /= 60;
957                 m = h % 60;
958                 h /= 60;
959                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
960         }
961
962         return out;
963 }
964
965 #endif
966
967 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
968 {
969         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
970         if (0 == strncmp("charging", buffer, 8)) {
971                 buffer[0] = 'C';
972                 memmove(buffer + 1, buffer + 8, n - 8);
973         } else if (0 == strncmp("discharging", buffer, 11)) {
974                 buffer[0] = 'D';
975                 memmove(buffer + 1, buffer + 11, n - 11);
976         } else if (0 == strncmp("absent/on AC", buffer, 12)) {
977                 buffer[0] = 'A';
978                 memmove(buffer + 1, buffer + 12, n - 12);
979         }
980 }
981
982 int get_entropy_avail(unsigned int *val)
983 {
984         /* Not applicable for FreeBSD as it uses the yarrow prng. */
985         (void)val;
986         return 1;
987 }
988
989 int get_entropy_poolsize(unsigned int *val)
990 {
991         /* Not applicable for FreeBSD as it uses the yarrow prng. */
992         (void)val;
993         return 1;
994 }