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