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