- Fix networking stuff on FreeBSD (Petr Holub)
[monky] / src / freebsd.c
1 /*
2  * freebsd.c
3  * Contains FreeBSD specific stuff
4  *
5  * $Id$
6  */
7
8 #include <sys/dkstat.h>
9 #include <sys/param.h>
10 #include <sys/resource.h>
11 #include <sys/socket.h>
12 #include <sys/sysctl.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <sys/vmmeter.h>
16 #include <sys/user.h>
17
18 #include <net/if.h>
19 #include <net/if_mib.h>
20
21 #include <devstat.h>
22 #include <fcntl.h>
23 #include <ifaddrs.h>
24 #include <limits.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29
30 #include "conky.h"
31
32 #define GETSYSCTL(name, var)    getsysctl(name, &(var), sizeof (var))
33 #define KELVTOC(x)              ((x - 2732) / 10.0)
34 #define MAXSHOWDEVS             16
35
36 #if 0
37 #define FREEBSD_DEBUG
38 #endif
39
40 inline void proc_find_top(struct process **cpu, struct process **mem);
41
42 u_int64_t diskio_prev = 0;
43 static short cpu_setup = 0;
44 static short diskio_setup = 0;
45
46 static int getsysctl(char *name, void *ptr, size_t len)
47 {
48         size_t nlen = len;
49         if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) {
50                 return (-1);
51         }
52
53         if (nlen != len) {
54                 return (-1);
55         }
56
57         return (0);
58 }
59
60 struct ifmibdata *data = NULL;
61 size_t len = 0;
62
63 static int swapmode(int *retavail, int *retfree)
64 {
65         int n;
66         int pagesize = getpagesize();
67         struct kvm_swap swapary[1];
68
69         *retavail = 0;
70         *retfree = 0;
71
72 #define CONVERT(v)      ((quad_t)(v) * pagesize / 1024)
73
74         n = kvm_getswapinfo(kd, swapary, 1, 0);
75         if (n < 0 || swapary[0].ksw_total == 0)
76                 return (0);
77
78         *retavail = CONVERT(swapary[0].ksw_total);
79         *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
80
81         n = (int) ((double) swapary[0].ksw_used * 100.0 /
82                 (double) swapary[0].ksw_total);
83
84         return (n);
85 }
86
87 void
88 prepare_update()
89 {
90 }
91
92 void
93 update_uptime()
94 {
95         int mib[2] = { CTL_KERN, KERN_BOOTTIME };
96         struct timeval boottime;
97         time_t now;
98         size_t size = sizeof (boottime);
99
100         if ((sysctl(mib, 2, &boottime, &size, NULL, 0) != -1) &&
101                         (boottime.tv_sec != 0)) {
102                 time(&now);
103                 info.uptime = now - boottime.tv_sec;
104         } else {
105                 fprintf(stderr, "Could not get uptime\n");
106                 info.uptime = 0;
107         }
108 }
109
110 void
111 update_meminfo()
112 {
113         int total_pages, inactive_pages, free_pages;
114         int swap_avail, swap_free;
115
116         int pagesize = getpagesize();
117
118         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages))
119                 fprintf(stderr,
120                         "Cannot read sysctl \"vm.stats.vm.v_page_count\"");
121
122         if (GETSYSCTL("vm.stats.vm.v_free_count", free_pages))
123                 fprintf(stderr,
124                         "Cannot read sysctl \"vm.stats.vm.v_free_count\"");
125
126         if (GETSYSCTL("vm.stats.vm.v_inactive_count", inactive_pages))
127                 fprintf(stderr,
128                         "Cannot read sysctl \"vm.stats.vm.v_inactive_count\"");
129
130         info.memmax = (total_pages * pagesize) >> 10;
131         info.mem =
132             ((total_pages - free_pages - inactive_pages) * pagesize) >> 10;
133
134
135         if ((swapmode(&swap_avail, &swap_free)) >= 0) {
136                 info.swapmax = swap_avail;
137                 info.swap = (swap_avail - swap_free);
138         } else {
139                 info.swapmax = 0;
140                 info.swap = 0;
141         }
142 }
143
144 void
145 update_net_stats()
146 {
147         struct net_stat *ns;
148         double delta;
149         long long r, t, last_recv, last_trans;
150         struct ifaddrs *ifap, *ifa;
151         struct if_data *ifd;
152
153
154         /* get delta */
155         delta = current_update_time - last_update_time;
156         if (delta <= 0.0001)
157                 return;
158
159         if (getifaddrs(&ifap) < 0)
160                 return;
161
162         for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
163                 ns = get_net_stat((const char *) ifa->ifa_name);
164
165                 if (ifa->ifa_flags & IFF_UP) {
166                         struct ifaddrs *iftmp;
167
168                         ns->up = 1;
169                         ns->linkstatus = 1;
170                         last_recv = ns->recv;
171                         last_trans = ns->trans;
172
173                         if (ifa->ifa_addr->sa_family != AF_LINK)
174                                 continue;
175
176                         for (iftmp = ifa->ifa_next; iftmp != NULL &&
177                                 strcmp(ifa->ifa_name, iftmp->ifa_name) == 0;
178                                 iftmp = iftmp->ifa_next)
179                                 if (iftmp->ifa_addr->sa_family == AF_INET)
180                                         memcpy(&(ns->addr), iftmp->ifa_addr,
181                                                 iftmp->ifa_addr->sa_len);
182
183                         ifd = (struct if_data *) ifa->ifa_data;
184                         r = ifd->ifi_ibytes;
185                         t = ifd->ifi_obytes;
186
187                         if (r < ns->last_read_recv)
188                                 ns->recv +=
189                                     ((long long) 4294967295U -
190                                         ns->last_read_recv) + r;
191                         else
192                                 ns->recv += (r - ns->last_read_recv);
193
194                         ns->last_read_recv = r;
195
196                         if (t < ns->last_read_trans)
197                                 ns->trans +=
198                                     ((long long) 4294967295U -
199                                         ns->last_read_trans) + t;
200                         else
201                                 ns->trans += (t - ns->last_read_trans);
202
203                         ns->last_read_trans = t;
204
205                         /* calculate speeds */
206                         ns->recv_speed = (ns->recv - last_recv) / delta;
207                         ns->trans_speed = (ns->trans - last_trans) / delta;
208                 } else {
209                         ns->up = 0;
210                         ns->linkstatus = 0;
211                 }
212         }
213
214         freeifaddrs(ifap);
215 }
216
217 void
218 update_total_processes()
219 {
220         int n_processes;
221
222         kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
223
224         info.procs = n_processes;
225 }
226
227 void
228 update_running_processes()
229 {
230         struct kinfo_proc *p;
231         int n_processes;
232         int i, cnt = 0;
233
234         p = kvm_getprocs(kd, KERN_PROC_ALL, 0, &n_processes);
235         for (i = 0; i < n_processes; i++) {
236 #if __FreeBSD__ < 5
237                 if (p[i].kp_proc.p_stat == SRUN)
238 #else
239                 if (p[i].ki_stat == SRUN)
240 #endif
241                         cnt++;
242         }
243
244         info.run_procs = cnt;
245 }
246
247 struct cpu_load_struct {
248         unsigned long load[5];
249 };
250
251 struct cpu_load_struct fresh = { {0, 0, 0, 0, 0} };
252 long cpu_used, oldtotal, oldused;
253
254 void
255 get_cpu_count()
256 {
257         /* int cpu_count = 0; */
258
259         /*
260          * XXX
261          * FreeBSD doesn't allow to get per CPU load stats
262          * on SMP machines. It's possible to get a CPU count,
263          * but as we fulfil only info.cpu_usage[0], it's better
264          * to report there's only one CPU. It should fix some bugs
265          * (e.g. cpugraph)
266          */
267 #if 0
268         if (GETSYSCTL("hw.ncpu", cpu_count) == 0)
269                 info.cpu_count = cpu_count;
270 #endif
271         info.cpu_count = 1;
272
273         info.cpu_usage = malloc(info.cpu_count * sizeof (float));
274         if (info.cpu_usage == NULL)
275                 CRIT_ERR("malloc");
276 }
277
278 /* XXX: SMP support */
279 void
280 update_cpu_usage()
281 {
282         long used, total;
283         long cp_time[CPUSTATES];
284         size_t len = sizeof (cp_time);
285
286         if (cpu_setup == 0) {
287                 get_cpu_count();
288                 cpu_setup = 1;
289         }
290
291         if (sysctlbyname("kern.cp_time", &cp_time, &len, NULL, 0) < 0) {
292                 (void) fprintf(stderr, "Cannot get kern.cp_time");
293         }
294
295         fresh.load[0] = cp_time[CP_USER];
296         fresh.load[1] = cp_time[CP_NICE];
297         fresh.load[2] = cp_time[CP_SYS];
298         fresh.load[3] = cp_time[CP_IDLE];
299         fresh.load[4] = cp_time[CP_IDLE];
300
301         used = fresh.load[0] + fresh.load[1] + fresh.load[2];
302         total =
303             fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3];
304
305         if ((total - oldtotal) != 0) {
306                 info.cpu_usage[0] = ((double) (used - oldused)) /
307                         (double) (total - oldtotal);
308         } else {
309                 info.cpu_usage[0] = 0;
310         }
311
312         oldused = used;
313         oldtotal = total;
314 }
315
316 double
317 get_i2c_info(int *fd, int arg, char *devtype, char *type)
318 {
319         return (0);
320 }
321
322 void
323 update_load_average()
324 {
325         double v[3];
326         getloadavg(v, 3);
327
328         info.loadavg[0] = (float) v[0];
329         info.loadavg[1] = (float) v[1];
330         info.loadavg[2] = (float) v[2];
331 }
332
333 double
334 get_acpi_temperature(int fd)
335 {
336         int temp;
337
338         if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
339                 fprintf(stderr,
340                 "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
341                 return (0.0);
342         }
343
344         return (KELVTOC(temp));
345 }
346
347 void
348 get_battery_stuff(char *buf, unsigned int n, const char *bat)
349 {
350         int battime;
351
352         if (GETSYSCTL("hw.acpi.battery.time", battime))
353                 (void) fprintf(stderr,
354                         "Cannot read sysctl \"hw.acpi.battery.time\"\n");
355
356         if (battime != -1)
357                 snprintf(buf, n, "Discharging, remaining %d:%2.2d",
358                         battime / 60, battime % 60);
359         else
360                 snprintf(buf, n, "Battery is charging");
361 }
362
363 int
364 open_i2c_sensor(const char *dev, const char *type, int n, int *div,
365                 char *devtype)
366 {
367         return (0);
368 }
369
370 int
371 open_acpi_temperature(const char *name)
372 {
373         return (0);
374 }
375
376 void
377 get_acpi_ac_adapter(char *p_client_buffer, size_t client_buffer_size)
378 {
379         int state;
380
381         if (!p_client_buffer || client_buffer_size <= 0)
382                 return;
383
384         if (GETSYSCTL("hw.acpi.acline", state)) {
385                 fprintf(stderr,
386                         "Cannot read sysctl \"hw.acpi.acline\"\n");
387                 return;
388         }
389
390
391         if (state)
392                 strncpy(p_client_buffer, "Running on AC Power",
393                                 client_buffer_size);
394         else
395                 strncpy(p_client_buffer, "Running on battery",
396                                 client_buffer_size);
397
398 }
399
400 void
401 get_acpi_fan(char *p_client_buffer, size_t client_buffer_size)
402 {
403         if (!p_client_buffer || client_buffer_size <= 0)
404                 return;
405
406         /* not implemented */
407         memset(p_client_buffer, 0, client_buffer_size);
408 }
409
410 void
411 get_adt746x_cpu(char *p_client_buffer, size_t client_buffer_size)
412 {
413         if (!p_client_buffer || client_buffer_size <= 0)
414                 return;
415
416         /* not implemented */
417         memset(p_client_buffer, 0, client_buffer_size);
418 }
419
420 void
421 get_adt746x_fan(char *p_client_buffer, size_t client_buffer_size)
422 {
423         if (!p_client_buffer || client_buffer_size <= 0)
424                 return;
425
426         /* not implemented */
427         memset(p_client_buffer, 0, client_buffer_size);
428 }
429
430 /* rdtsc() and get_freq_dynamic() copied from linux.c */
431
432 #if  defined(__i386) || defined(__x86_64)
433 __inline__ unsigned long long int
434 rdtsc()
435 {
436         unsigned long long int x;
437         __asm__ volatile(".byte 0x0f, 0x31":"=A" (x));
438         return (x);
439 }
440 #endif
441
442 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
443 void
444 get_freq_dynamic(char *p_client_buffer, size_t client_buffer_size,
445                 char *p_format, int divisor)
446 {
447 #if  defined(__i386) || defined(__x86_64)
448         struct timezone tz;
449         struct timeval tvstart, tvstop;
450         unsigned long long cycles[2];   /* gotta be 64 bit */
451         unsigned int microseconds;      /* total time taken */
452
453         memset(&tz, 0, sizeof (tz));
454
455         /* get this function in cached memory */
456         gettimeofday(&tvstart, &tz);
457         cycles[0] = rdtsc();
458         gettimeofday(&tvstart, &tz);
459
460         /* we don't trust that this is any specific length of time */
461         usleep(100);
462         cycles[1] = rdtsc();
463         gettimeofday(&tvstop, &tz);
464         microseconds = ((tvstop.tv_sec - tvstart.tv_sec) * 1000000) +
465                 (tvstop.tv_usec - tvstart.tv_usec);
466
467         snprintf(p_client_buffer, client_buffer_size, p_format,
468                 (float)((cycles[1] - cycles[0]) / microseconds) / divisor);
469 #else
470         get_freq(p_client_buffer, client_buffer_size, p_format, divisor);
471 #endif
472 }
473
474 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
475 void
476 get_freq(char *p_client_buffer, size_t client_buffer_size,
477                 char *p_format, int divisor)
478 {
479         int freq;
480
481         if (!p_client_buffer || client_buffer_size <= 0 ||
482                         !p_format || divisor <= 0)
483                 return;
484
485         if (GETSYSCTL("dev.cpu.0.freq", freq) == 0)
486                 snprintf(p_client_buffer, client_buffer_size,
487                                 p_format, freq/divisor);
488         else
489                 snprintf(p_client_buffer, client_buffer_size, p_format, 0.0f);
490 }
491
492 void
493 update_top()
494 {
495         proc_find_top(info.cpu, info.memu);
496 }
497
498 void
499 update_wifi_stats()
500 {
501         /* XXX */
502 }
503 void
504 update_diskio()
505 {
506         int devs_count,
507             num_selected,
508             num_selections;
509         struct device_selection *dev_select = NULL;
510         long select_generation;
511         int dn;
512         static struct statinfo  statinfo_cur;
513         u_int64_t diskio_current = 0;
514
515         bzero(&statinfo_cur, sizeof (statinfo_cur));
516         statinfo_cur.dinfo = (struct devinfo *)malloc(sizeof (struct devinfo));
517         bzero(statinfo_cur.dinfo, sizeof (struct devinfo));
518
519         if (devstat_getdevs(NULL, &statinfo_cur) < 0)
520                 return;
521
522         devs_count = statinfo_cur.dinfo->numdevs;
523         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
524                         &select_generation, statinfo_cur.dinfo->generation,
525                         statinfo_cur.dinfo->devices, devs_count, NULL, 0,
526                         NULL, 0, DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
527                 for (dn = 0; dn < devs_count; ++dn) {
528                         int di;
529                         struct devstat  *dev;
530
531                         di = dev_select[dn].position;
532                         dev = &statinfo_cur.dinfo->devices[di];
533
534                         diskio_current += dev->bytes[DEVSTAT_READ] +
535                                 dev->bytes[DEVSTAT_WRITE];
536                 }
537
538                 free(dev_select);
539         }
540
541         /*
542          * Since we return (diskio_total_current - diskio_total_old), first
543          * frame will be way too high (it will be equal to
544          * diskio_total_current, i.e. all disk I/O since boot). That's why
545          * it is better to return 0 first time;
546          */
547         if (diskio_setup == 0) {
548                 diskio_setup = 1;
549                 diskio_value = 0;
550         } else
551                 diskio_value = (unsigned int)((diskio_current - diskio_prev)/
552                                 1024);
553         diskio_prev = diskio_current;
554
555         free(statinfo_cur.dinfo);
556 }
557
558 /*
559  * While topless is obviously better, top is also not bad.
560  */
561
562 int
563 comparecpu(const void *a, const void *b)
564 {
565         if (((struct process *)a)->amount > ((struct process *)b)->amount)
566                 return (-1);
567
568         if (((struct process *)a)->amount < ((struct process *)b)->amount)
569                 return (1);
570
571         return (0);
572 }
573
574 int
575 comparemem(const void *a, const void *b)
576 {
577         if (((struct process *)a)->totalmem > ((struct process *)b)->totalmem)
578                 return (-1);
579
580         if (((struct process *)a)->totalmem < ((struct process *)b)->totalmem)
581                 return (1);
582
583         return (0);
584 }
585
586 inline void
587 proc_find_top(struct process **cpu, struct process **mem)
588 {
589         struct kinfo_proc *p;
590         int n_processes;
591         int i, j = 0;
592         struct process *processes;
593
594         int total_pages;
595
596         /* we get total pages count again to be sure it is up to date */
597         if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0)
598                 CRIT_ERR("Cannot read sysctl"
599                         "\"vm.stats.vm.v_page_count\"");
600
601         p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
602         processes = malloc(n_processes * sizeof (struct process));
603
604         for (i = 0; i < n_processes; i++) {
605                 if (!((p[i].ki_flag & P_SYSTEM)) &&
606                                 p[i].ki_comm != NULL) {
607                         processes[j].pid = p[i].ki_pid;
608                         processes[j].name =  strdup(p[i].ki_comm);
609                         processes[j].amount = 100.0 *
610                                 p[i].ki_pctcpu / FSCALE;
611                         processes[j].totalmem = (float)(p[i].ki_rssize /
612                                         (float)total_pages) * 100.0;
613                         j++;
614                 }
615         }
616
617         qsort(processes, j - 1, sizeof (struct process), comparemem);
618         for (i = 0; i < 10; i++) {
619                 struct process *tmp, *ttmp;
620
621                 tmp = malloc(sizeof (struct process));
622                 tmp->pid = processes[i].pid;
623                 tmp->amount = processes[i].amount;
624                 tmp->totalmem = processes[i].totalmem;
625                 tmp->name = strdup(processes[i].name);
626
627                 ttmp = mem[i];
628                 mem[i] = tmp;
629                 if (ttmp != NULL) {
630                         free(ttmp->name);
631                         free(ttmp);
632                 }
633         }
634
635         qsort(processes, j - 1, sizeof (struct process), comparecpu);
636         for (i = 0; i < 10; i++) {
637                 struct process *tmp, *ttmp;
638
639                 tmp = malloc(sizeof (struct process));
640                 tmp->pid = processes[i].pid;
641                 tmp->amount = processes[i].amount;
642                 tmp->totalmem = processes[i].totalmem;
643                 tmp->name = strdup(processes[i].name);
644
645                 ttmp = cpu[i];
646                 cpu[i] = tmp;
647                 if (ttmp != NULL) {
648                         free(ttmp->name);
649                         free(ttmp);
650                 }
651         }
652
653 #if defined(FREEBSD_DEBUG)
654         printf("=====\nmem\n");
655         for (i = 0; i < 10; i++) {
656                 printf("%d: %s(%d) %.2f\n", i, mem[i]->name,
657                                 mem[i]->pid, mem[i]->totalmem);
658         }
659 #endif
660
661         for (i = 0; i < j; free(processes[i++].name));
662         free(processes);
663 }
664
665 #if     defined(i386) || defined(__i386__)
666 #define APMDEV          "/dev/apm"
667 #define APM_UNKNOWN     255
668
669 int
670 apm_getinfo(int fd, apm_info_t aip)
671 {
672         if (ioctl(fd, APMIO_GETINFO, aip) == -1)
673                 return (-1);
674
675         return (0);
676 }
677
678 char
679 *get_apm_adapter()
680 {
681         int fd;
682         struct apm_info info;
683
684         fd = open(APMDEV, O_RDONLY);
685         if (fd < 0)
686                 return ("ERR");
687
688         if (apm_getinfo(fd, &info) != 0) {
689                 close(fd);
690                 return ("ERR");
691         }
692         close(fd);
693
694         switch (info.ai_acline) {
695                 case 0:
696                         return ("off-line");
697                         break;
698                 case 1:
699                         if (info.ai_batt_stat == 3)
700                                 return ("charging");
701                         else
702                                 return ("on-line");
703                         break;
704                 default:
705                         return ("unknown");
706                         break;
707         }
708 }
709
710 char
711 *get_apm_battery_life()
712 {
713         int fd;
714         u_int batt_life;
715         struct apm_info info;
716         char *out;
717
718         out = (char *)calloc(16, sizeof (char));
719
720         fd = open(APMDEV, O_RDONLY);
721         if (fd < 0) {
722                 strncpy(out, "ERR", 16);
723                 return (out);
724         }
725
726         if (apm_getinfo(fd, &info) != 0) {
727                 close(fd);
728                 strncpy(out, "ERR", 16);
729                 return (out);
730         }
731         close(fd);
732
733         batt_life = info.ai_batt_life;
734         if (batt_life == APM_UNKNOWN)
735                 strncpy(out, "unknown", 16);
736         else if (batt_life <= 100) {
737                 snprintf(out, 16, "%d%%", batt_life);
738                 return (out);
739         } else
740                 strncpy(out, "ERR", 16);
741
742         return (out);
743 }
744
745 char
746 *get_apm_battery_time()
747 {
748         int fd;
749         int batt_time;
750         int h, m, s;
751         struct apm_info info;
752         char *out;
753
754         out = (char *)calloc(16, sizeof (char));
755
756         fd = open(APMDEV, O_RDONLY);
757         if (fd < 0) {
758                 strncpy(out, "ERR", 16);
759                 return (out);
760         }
761
762         if (apm_getinfo(fd, &info) != 0) {
763                 close(fd);
764                 strncpy(out, "ERR", 16);
765                 return (out);
766         }
767         close(fd);
768
769         batt_time = info.ai_batt_time;
770
771         if (batt_time == -1)
772                 strncpy(out, "unknown", 16);
773         else {
774                 h = batt_time;
775                 s = h % 60;
776                 h /= 60;
777                 m = h % 60;
778                 h /= 60;
779                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
780         }
781
782         return (out);
783 }
784
785 #endif
786
787 /* empty stub so conky links */
788 void
789 free_all_processes(void)
790 {
791 }