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