a8cd8b1ef87eed1a62badaab4aaa7c4f030a5f39
[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         kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
270
271         info.procs = n_processes;
272         return 0;
273 }
274
275 int update_running_processes(void)
276 {
277         struct kinfo_proc *p;
278         int n_processes;
279         int i, cnt = 0;
280
281         p = kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
282         for (i = 0; i < n_processes; i++) {
283 #if (__FreeBSD__ < 5) && (__FreeBSD_kernel__ < 5)
284                 if (p[i].kp_proc.p_stat == SRUN) {
285 #else
286                 if (p[i].ki_stat == SRUN) {
287 #endif
288                         cnt++;
289                 }
290         }
291
292         info.run_procs = cnt;
293         return 0;
294 }
295
296 void get_cpu_count(void)
297 {
298         int cpu_count = 0;
299         size_t cpu_count_len = sizeof(cpu_count);
300
301         if (GETSYSCTL("hw.ncpu", cpu_count) == 0) {
302                 info.cpu_count = cpu_count;
303         } else {
304                 fprintf(stderr, "Cannot get hw.ncpu\n");
305                 info.cpu_count = 0;
306         }
307
308         info.cpu_usage = malloc((info.cpu_count + 1) * sizeof(float));
309         if (info.cpu_usage == NULL) {
310                 CRIT_ERR(NULL, NULL, "malloc");
311         }
312 }
313
314 struct cpu_info {
315         long oldtotal;
316         long oldused;
317 };
318
319 int update_cpu_usage(void)
320 {
321         int i, j = 0;
322         long used, total;
323         long *cp_time = NULL;
324         size_t cp_len;
325         static struct cpu_info *cpu = NULL;
326         unsigned int malloc_cpu_size = 0;
327         extern void* global_cpu;
328
329         /* add check for !info.cpu_usage since that mem is freed on a SIGUSR1 */
330         if ((cpu_setup == 0) || (!info.cpu_usage)) {
331                 get_cpu_count();
332                 cpu_setup = 1;
333         }
334
335         if (!global_cpu) {
336                 malloc_cpu_size = (info.cpu_count + 1) * sizeof(struct cpu_info);
337                 cpu = malloc(malloc_cpu_size);
338                 memset(cpu, 0, malloc_cpu_size);
339                 global_cpu = cpu;
340         }
341
342         /* cpu[0] is overall stats, get it from separate sysctl */
343         cp_len = CPUSTATES * sizeof(long);
344         cp_time = malloc(cp_len);
345
346         if (sysctlbyname("kern.cp_time", cp_time, &cp_len, NULL, 0) < 0) {
347                 fprintf(stderr, "Cannot get kern.cp_time\n");
348         }
349
350         total = 0;
351         for (j = 0; j < CPUSTATES; j++)
352                 total += cp_time[j];
353
354         used = total - cp_time[CP_IDLE];
355
356         if ((total - cpu[0].oldtotal) != 0) {
357                 info.cpu_usage[0] = ((double) (used - cpu[0].oldused)) /
358                 (double) (total - cpu[0].oldtotal);
359         } else {
360                 info.cpu_usage[0] = 0;
361         }
362
363         cpu[0].oldused = used;
364         cpu[0].oldtotal = total;
365
366         free(cp_time);
367
368         /* per-core stats */
369         cp_len = CPUSTATES * sizeof(long) * info.cpu_count;
370         cp_time = malloc(cp_len);
371
372         /* on e.g. i386 SMP we may have more values than actual cpus; this will just drop extra values */
373         if (sysctlbyname("kern.cp_times", cp_time, &cp_len, NULL, 0) < 0 && errno != ENOMEM) {
374                 fprintf(stderr, "Cannot get kern.cp_times\n");
375         }
376
377         for (i = 0; i < info.cpu_count; i++)
378         {
379                 total = 0;
380                 for (j = 0; j < CPUSTATES; j++)
381                         total += cp_time[i*CPUSTATES + j];
382
383                 used = total - cp_time[i*CPUSTATES + CP_IDLE];
384
385                 if ((total - cpu[i+1].oldtotal) != 0) {
386                         info.cpu_usage[i+1] = ((double) (used - cpu[i+1].oldused)) /
387                         (double) (total - cpu[i+1].oldtotal);
388                 } else {
389                         info.cpu_usage[i+1] = 0;
390                 }
391
392                 cpu[i+1].oldused = used;
393                 cpu[i+1].oldtotal = total;
394         }
395
396         free(cp_time);
397         return 0;
398 }
399
400 int update_load_average(void)
401 {
402         double v[3];
403
404         getloadavg(v, 3);
405
406         info.loadavg[0] = (double) v[0];
407         info.loadavg[1] = (double) v[1];
408         info.loadavg[2] = (double) v[2];
409
410         return 0;
411 }
412
413 double get_acpi_temperature(int fd)
414 {
415         int temp;
416         (void)fd;
417
418         if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
419                 fprintf(stderr,
420                         "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
421                 return 0.0;
422         }
423
424         return KELVTOC(temp);
425 }
426
427 static void get_battery_stats(int *battime, int *batcapacity, int *batstate, int *ac) {
428         if (battime && GETSYSCTL("hw.acpi.battery.time", *battime)) {
429                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.time\"\n");
430         }
431         if (batcapacity && GETSYSCTL("hw.acpi.battery.life", *batcapacity)) {
432                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.life\"\n");
433         }
434         if (batstate && GETSYSCTL("hw.acpi.battery.state", *batstate)) {
435                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.state\"\n");
436         }
437         if (ac && GETSYSCTL("hw.acpi.acline", *ac)) {
438                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
439         }
440 }
441
442 void get_battery_stuff(char *buf, unsigned int n, const char *bat, int item)
443 {
444         int battime, batcapacity, batstate, ac;
445         (void)bat;
446
447         get_battery_stats(&battime, &batcapacity, &batstate, &ac);
448
449         if (batstate != 1 && batstate != 2 && batstate != 0 && batstate != 7)
450                 fprintf(stderr, "Unknown battery state %d!\n", batstate);
451         else if (batstate != 1 && ac == 0)
452                 fprintf(stderr, "Battery charging while not on AC!\n");
453         else if (batstate == 1 && ac == 1)
454                 fprintf(stderr, "Battery discharing while on AC!\n");
455
456         switch (item) {
457                 case BATTERY_TIME:
458                         if (batstate == 1 && battime != -1)
459                                 snprintf(buf, n, "%d:%2.2d", battime / 60, battime % 60);
460                         break;
461                 case BATTERY_STATUS:
462                         if (batstate == 1) // Discharging
463                                 snprintf(buf, n, "remaining %d%%", batcapacity);
464                         else
465                                 snprintf(buf, n, batstate == 2 ? "charging (%d%%)" :
466                                                 (batstate == 7 ? "absent/on AC" : "charged (%d%%)"),
467                                                 batcapacity);
468                         break;
469                 default:
470                         fprintf(stderr, "Unknown requested battery stat %d\n", item);
471         }
472 }
473
474 static int check_bat(const char *bat)
475 {
476         int batnum, numbatts;
477         char *endptr;
478         if (GETSYSCTL("hw.acpi.battery.units", numbatts)) {
479                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.battery.units\"\n");
480                 return -1;
481         }
482         if (numbatts <= 0) {
483                 fprintf(stderr, "No battery unit detected\n");
484                 return -1;
485         }
486         if (!bat || (batnum = strtol(bat, &endptr, 10)) < 0 ||
487                         bat == endptr || batnum > numbatts) {
488                 fprintf(stderr, "Wrong battery unit %s requested\n", bat ? bat : "");
489                 return -1;
490         }
491         return batnum;
492 }
493
494 int get_battery_perct(const char *bat)
495 {
496         union acpi_battery_ioctl_arg battio;
497         int batnum, acpifd;
498         int designcap, lastfulcap, batperct;
499
500         if ((battio.unit = batnum = check_bat(bat)) < 0)
501                 return 0;
502         if ((acpifd = open("/dev/acpi", O_RDONLY)) < 0) {
503                 fprintf(stderr, "Can't open ACPI device\n");
504                 return 0;
505         }
506         if (ioctl(acpifd, ACPIIO_BATT_GET_BIF, &battio) == -1) {
507                 fprintf(stderr, "Unable to get info for battery unit %d\n", batnum);
508                 return 0;
509         }
510         close(acpifd);
511         designcap = battio.bif.dcap;
512         lastfulcap = battio.bif.lfcap;
513         batperct = (designcap > 0 && lastfulcap > 0) ?
514                 (int) (((float) lastfulcap / designcap) * 100) : 0;
515         return batperct > 100 ? 100 : batperct;
516 }
517
518 int get_battery_perct_bar(const char *bar)
519 {
520         int batperct = get_battery_perct(bar);
521         return (int)(batperct * 2.56 - 1);
522 }
523
524 int open_acpi_temperature(const char *name)
525 {
526         (void)name;
527         /* Not applicable for FreeBSD. */
528         return 0;
529 }
530
531 void get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size, const char *adapter)
532 {
533         int state;
534
535         (void) adapter; // only linux uses this
536
537         if (!p_client_buffer || client_buffer_size <= 0) {
538                 return;
539         }
540
541         if (GETSYSCTL("hw.acpi.acline", state)) {
542                 fprintf(stderr, "Cannot read sysctl \"hw.acpi.acline\"\n");
543                 return;
544         }
545
546         if (state) {
547                 strncpy(p_client_buffer, "Running on AC Power", client_buffer_size);
548         } else {
549                 strncpy(p_client_buffer, "Running on battery", client_buffer_size);
550         }
551 }
552
553 void get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
554 {
555         /* not implemented */
556         if (p_client_buffer && client_buffer_size > 0) {
557                 memset(p_client_buffer, 0, client_buffer_size);
558         }
559 }
560
561 /* void */
562 char get_freq(char *p_client_buffer, size_t client_buffer_size, const char *p_format,
563                 int divisor, unsigned int cpu)
564 {
565         int freq;
566         char *freq_sysctl;
567
568         freq_sysctl = (char *) calloc(16, sizeof(char));
569         if (freq_sysctl == NULL) {
570                 exit(-1);
571         }
572
573         snprintf(freq_sysctl, 16, "dev.cpu.%d.freq", (cpu - 1));
574
575         if (!p_client_buffer || client_buffer_size <= 0 || !p_format
576                         || divisor <= 0) {
577                 return 0;
578         }
579
580         if (GETSYSCTL(freq_sysctl, freq) == 0) {
581                 snprintf(p_client_buffer, client_buffer_size, p_format,
582                         (float) freq / divisor);
583         } else {
584                 snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
585         }
586
587         free(freq_sysctl);
588         return 1;
589 }
590
591 int update_top(void)
592 {
593         proc_find_top(info.cpu, info.memu, info.time);
594         return 0;
595 }
596
597 #if 0
598 void update_wifi_stats(void)
599 {
600         struct ifreq ifr;               /* interface stats */
601         struct wi_req wireq;
602         struct net_stat *ns;
603         struct ifaddrs *ifap, *ifa;
604         struct ifmediareq ifmr;
605         int s;
606
607         /* Get iface table */
608         if (getifaddrs(&ifap) < 0) {
609                 return;
610         }
611
612         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
613                 ns = get_net_stat((const char *) ifa->ifa_name, NULL, NULL);
614
615                 s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
616
617                 /* Get media type */
618                 bzero(&ifmr, sizeof(ifmr));
619                 strlcpy(ifmr.ifm_name, ifa->ifa_name, IFNAMSIZ);
620                 if (ioctl(s, SIOCGIFMEDIA, (caddr_t) &ifmr) < 0) {
621                         close(s);
622                         return;
623                 }
624
625                 /* We can monitor only wireless interfaces
626                  * which are not in hostap mode */
627                 if ((ifmr.ifm_active & IFM_IEEE80211)
628                                 && !(ifmr.ifm_active & IFM_IEEE80211_HOSTAP)) {
629                         /* Get wi status */
630                         bzero(&ifr, sizeof(ifr));
631                         strlcpy(ifr.ifr_name, ifa->ifa_name, IFNAMSIZ);
632                         wireq.wi_type = WI_RID_COMMS_QUALITY;
633                         wireq.wi_len = WI_MAX_DATALEN;
634                         ifr.ifr_data = (void *) &wireq;
635
636                         if (ioctl(s, SIOCGWAVELAN, (caddr_t) &ifr) < 0) {
637                                 perror("ioctl (getting wi status)");
638                                 exit(1);
639                         }
640
641                         /* wi_val[0] = quality
642                          * wi_val[1] = signal
643                          * wi_val[2] = noise */
644                         ns->linkstatus = (int) wireq.wi_val[1];
645                 }
646 cleanup:
647                 close(s);
648         }
649 }
650 #endif
651
652 int update_diskio(void)
653 {
654         int devs_count, num_selected, num_selections, dn;
655         struct device_selection *dev_select = NULL;
656         long select_generation;
657         static struct statinfo statinfo_cur;
658         char device_name[text_buffer_size];
659         struct diskio_stat *cur;
660         unsigned int reads, writes;
661         unsigned int total_reads = 0, total_writes = 0;
662
663
664         memset(&statinfo_cur, 0, sizeof(statinfo_cur));
665         statinfo_cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
666         stats.current = stats.current_read = stats.current_write = 0;
667
668         if (devstat_getdevs(NULL, &statinfo_cur) < 0) {
669                 free(statinfo_cur.dinfo);
670                 return 0;
671         }
672
673         devs_count = statinfo_cur.dinfo->numdevs;
674         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
675                         &select_generation, statinfo_cur.dinfo->generation,
676                         statinfo_cur.dinfo->devices, devs_count, NULL, 0, NULL, 0,
677                         DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
678                 for (dn = 0; dn < devs_count; dn++) {
679                         int di;
680                         struct devstat *dev;
681
682                         di = dev_select[dn].position;
683                         dev = &statinfo_cur.dinfo->devices[di];
684                         snprintf(device_name, text_buffer_size, "%s%d",
685                                         dev_select[dn].device_name, dev_select[dn].unit_number);
686
687                         total_reads += (reads = dev->bytes[DEVSTAT_READ] / 512);
688                         total_writes += (writes = dev->bytes[DEVSTAT_WRITE] / 512);
689                         for (cur = stats.next; cur; cur = cur->next) {
690                                 if (cur->dev && !strcmp(device_name, cur->dev)) {
691                                         update_diskio_values(cur, reads, writes);
692                                         break;
693                                 }
694                         }
695                 }
696                 update_diskio_values(&stats, total_reads, total_writes);
697
698                 free(dev_select);
699         }
700
701         free(statinfo_cur.dinfo);
702         return 0;
703 }
704
705 /* While topless is obviously better, top is also not bad. */
706
707 int comparecpu(const void *a, const void *b)
708 {
709         if (((const struct process *)a)->amount > ((const struct process *)b)->amount) {
710                 return -1;
711         } else if (((const struct process *)a)->amount < ((const struct process *)b)->amount) {
712                 return 1;
713         } else {
714                 return 0;
715         }
716 }
717
718 int comparemem(const void *a, const void *b)
719 {
720         if (((const struct process *)a)->rss > ((const struct process *)b)->rss) {
721                 return -1;
722         } else if (((const struct process *)a)->rss < ((const struct process *)b)->rss) {
723                 return 1;
724         } else {
725                 return 0;
726         }
727 }
728
729 int comparetime(const void *va, const void *vb)
730 {
731         struct process *a = (struct process *)va, *b = (struct process *)vb;
732
733         return b->total_cpu_time - a->total_cpu_time;
734 }
735
736 __attribute__((gnu_inline)) inline void
737 proc_find_top(struct process **cpu, struct process **mem, struct process **time)
738 {
739         struct kinfo_proc *p;
740         int n_processes;
741         int i, j = 0;
742         struct process *processes;
743
744         int total_pages;
745
746         /* we get total pages count again to be sure it is up to date */
747         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0) {
748                 CRIT_ERR(NULL, NULL, "Cannot read sysctl \"vm.stats.vm.v_page_count\"");
749         }
750
751         p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
752         processes = malloc(n_processes * sizeof(struct process));
753
754         for (i = 0; i < n_processes; i++) {
755                 if (!((p[i].ki_flag & P_SYSTEM)) && p[i].ki_comm != NULL) {
756                         processes[j].pid = p[i].ki_pid;
757                         processes[j].name = strndup(p[i].ki_comm, text_buffer_size);
758                         processes[j].amount = 100.0 * p[i].ki_pctcpu / FSCALE;
759                         processes[j].vsize = p[i].ki_size;
760                         processes[j].rss = (p[i].ki_rssize * getpagesize());
761                         /* ki_runtime is in microseconds, total_cpu_time in centiseconds.
762                          * Therefore we divide by 10000. */
763                         processes[j].total_cpu_time = p[i].ki_runtime / 10000;
764                         j++;
765                 }
766         }
767
768         qsort(processes, j - 1, sizeof(struct process), comparemem);
769         for (i = 0; i < 10 && i < n_processes; i++) {
770                 struct process *tmp, *ttmp;
771
772                 tmp = malloc(sizeof(struct process));
773                 memcpy(tmp, &processes[i], sizeof(struct process));
774                 tmp->name = strndup(processes[i].name, text_buffer_size);
775
776                 ttmp = mem[i];
777                 mem[i] = tmp;
778                 if (ttmp != NULL) {
779                         free(ttmp->name);
780                         free(ttmp);
781                 }
782         }
783
784         qsort(processes, j - 1, sizeof(struct process), comparecpu);
785         for (i = 0; i < 10 && i < n_processes; i++) {
786                 struct process *tmp, *ttmp;
787
788                 tmp = malloc(sizeof(struct process));
789                 memcpy(tmp, &processes[i], sizeof(struct process));
790                 tmp->name = strndup(processes[i].name, text_buffer_size);
791
792                 ttmp = cpu[i];
793                 cpu[i] = tmp;
794                 if (ttmp != NULL) {
795                         free(ttmp->name);
796                         free(ttmp);
797                 }
798         }
799
800         qsort(processes, j - 1, sizeof(struct process), comparetime);
801         for (i = 0; i < 10 && i < n_processes; i++) {
802                 struct process *tmp, *ttmp;
803
804                 tmp = malloc(sizeof(struct process));
805                 memcpy(tmp, &processes[i], sizeof(struct process));
806                 tmp->name = strndup(processes[i].name, text_buffer_size);
807
808                 ttmp = time[i];
809                 time[i] = tmp;
810                 if (ttmp != NULL) {
811                         free(ttmp->name);
812                         free(ttmp);
813                 }
814         }
815
816 #if defined(FREEBSD_DEBUG)
817         printf("=====\nmem\n");
818         for (i = 0; i < 10; i++) {
819                 printf("%d: %s(%d) %ld %ld\n", i, mem[i]->name,
820                                 mem[i]->pid, mem[i]->vsize, mem[i]->rss);
821         }
822 #endif
823
824         for (i = 0; i < j; i++) {
825                 free(processes[i].name);
826         }
827         free(processes);
828 }
829
830 #if     defined(i386) || defined(__i386__)
831 #define APMDEV          "/dev/apm"
832 #define APM_UNKNOWN     255
833
834 int apm_getinfo(int fd, apm_info_t aip)
835 {
836         if (ioctl(fd, APMIO_GETINFO, aip) == -1) {
837                 return -1;
838         }
839
840         return 0;
841 }
842
843 char *get_apm_adapter(void)
844 {
845         int fd;
846         struct apm_info a_info;
847         char *out;
848
849         out = (char *) calloc(16, sizeof(char));
850
851         fd = open(APMDEV, O_RDONLY);
852         if (fd < 0) {
853                 strncpy(out, "ERR", 16);
854                 return out;
855         }
856
857         if (apm_getinfo(fd, &a_info) != 0) {
858                 close(fd);
859                 strncpy(out, "ERR", 16);
860                 return out;
861         }
862         close(fd);
863
864         switch (a_info.ai_acline) {
865                 case 0:
866                         strncpy(out, "off-line", 16);
867                         return out;
868                         break;
869                 case 1:
870                         if (a_info.ai_batt_stat == 3) {
871                                 strncpy(out, "charging", 16);
872                                 return out;
873                         } else {
874                                 strncpy(out, "on-line", 16);
875                                 return out;
876                         }
877                         break;
878                 default:
879                         strncpy(out, "unknown", 16);
880                         return out;
881                         break;
882         }
883 }
884
885 char *get_apm_battery_life(void)
886 {
887         int fd;
888         u_int batt_life;
889         struct apm_info a_info;
890         char *out;
891
892         out = (char *) calloc(16, sizeof(char));
893
894         fd = open(APMDEV, O_RDONLY);
895         if (fd < 0) {
896                 strncpy(out, "ERR", 16);
897                 return out;
898         }
899
900         if (apm_getinfo(fd, &a_info) != 0) {
901                 close(fd);
902                 strncpy(out, "ERR", 16);
903                 return out;
904         }
905         close(fd);
906
907         batt_life = a_info.ai_batt_life;
908         if (batt_life == APM_UNKNOWN) {
909                 strncpy(out, "unknown", 16);
910         } else if (batt_life <= 100) {
911                 snprintf(out, 16, "%d%%", batt_life);
912                 return out;
913         } else {
914                 strncpy(out, "ERR", 16);
915         }
916
917         return out;
918 }
919
920 char *get_apm_battery_time(void)
921 {
922         int fd;
923         int batt_time;
924         int h, m, s;
925         struct apm_info a_info;
926         char *out;
927
928         out = (char *) calloc(16, sizeof(char));
929
930         fd = open(APMDEV, O_RDONLY);
931         if (fd < 0) {
932                 strncpy(out, "ERR", 16);
933                 return out;
934         }
935
936         if (apm_getinfo(fd, &a_info) != 0) {
937                 close(fd);
938                 strncpy(out, "ERR", 16);
939                 return out;
940         }
941         close(fd);
942
943         batt_time = a_info.ai_batt_time;
944
945         if (batt_time == -1) {
946                 strncpy(out, "unknown", 16);
947         } else {
948                 h = batt_time;
949                 s = h % 60;
950                 h /= 60;
951                 m = h % 60;
952                 h /= 60;
953                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
954         }
955
956         return out;
957 }
958
959 #endif
960
961 void get_battery_short_status(char *buffer, unsigned int n, const char *bat)
962 {
963         get_battery_stuff(buffer, n, bat, BATTERY_STATUS);
964         if (0 == strncmp("charging", buffer, 8)) {
965                 buffer[0] = 'C';
966                 memmove(buffer + 1, buffer + 8, n - 8);
967         } else if (0 == strncmp("discharging", buffer, 11)) {
968                 buffer[0] = 'D';
969                 memmove(buffer + 1, buffer + 11, n - 11);
970         } else if (0 == strncmp("absent/on AC", buffer, 12)) {
971                 buffer[0] = 'A';
972                 memmove(buffer + 1, buffer + 12, n - 12);
973         }
974 }
975
976 int get_entropy_avail(unsigned int *val)
977 {
978         /* Not applicable for FreeBSD as it uses the yarrow prng. */
979         (void)val;
980         return 1;
981 }
982
983 int get_entropy_poolsize(unsigned int *val)
984 {
985         /* Not applicable for FreeBSD as it uses the yarrow prng. */
986         (void)val;
987         return 1;
988 }