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