fix typos
[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         if (GETSYSCTL("hw.ncpu", cpu_count) == 0)
277                 info.cpu_count = cpu_count;
278
279         info.cpu_usage = malloc(info.cpu_count * sizeof(float));
280         if (info.cpu_usage == NULL)
281                 CRIT_ERR("malloc");
282 }
283
284 /* XXX: SMP support */
285 void update_cpu_usage()
286 {
287         long used, total;
288         long cp_time[CPUSTATES];
289         size_t len = sizeof(cp_time);
290         
291         if (cpu_setup == 0) {
292                 get_cpu_count();
293                 cpu_setup = 1;
294         }
295         
296         if (sysctlbyname("kern.cp_time", &cp_time, &len, NULL, 0) < 0) {
297                 (void) fprintf(stderr, "Cannot get kern.cp_time");
298         }
299
300         fresh.load[0] = cp_time[CP_USER];
301         fresh.load[1] = cp_time[CP_NICE];
302         fresh.load[2] = cp_time[CP_SYS];
303         fresh.load[3] = cp_time[CP_IDLE];
304         fresh.load[4] = cp_time[CP_IDLE];
305
306         used = fresh.load[0] + fresh.load[1] + fresh.load[2];
307         total =
308             fresh.load[0] + fresh.load[1] + fresh.load[2] + fresh.load[3];
309
310         if ((total - oldtotal) != 0) {
311                 info.cpu_usage[0] = ((double) (used - oldused)) / (double) (total - oldtotal);
312         } else {
313                 info.cpu_usage[0] = 0;
314         }
315
316         oldused = used;
317         oldtotal = total;
318 }
319
320 double get_i2c_info(int *fd, int arg, char *devtype, char *type)
321 {
322         return 0;
323 }
324
325 void update_load_average()
326 {
327         double v[3];
328         getloadavg(v, 3);
329
330         info.loadavg[0] = (float) v[0];
331         info.loadavg[1] = (float) v[1];
332         info.loadavg[2] = (float) v[2];
333 }
334
335 double get_acpi_temperature(int fd)
336 {
337         int temp;
338
339         if (GETSYSCTL("hw.acpi.thermal.tz0.temperature", temp)) {
340                 (void) fprintf(stderr,
341                                "Cannot read sysctl \"hw.acpi.thermal.tz0.temperature\"\n");
342                 return 0.0;
343         }
344
345         return KELVTOC(temp);
346 }
347
348 void 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 open_acpi_temperature(const char *name)
371 {
372         return 0;
373 }
374
375 void get_acpi_ac_adapter( char * p_client_buffer, size_t client_buffer_size )
376 {
377         int state;
378
379         if ( !p_client_buffer || client_buffer_size <= 0 )
380                 return;
381
382         if (GETSYSCTL("hw.acpi.acline", state)) {
383                 (void) fprintf(stderr,
384                                "Cannot read sysctl \"hw.acpi.acline\"\n");
385                 return;
386         }
387
388
389         if (state)
390                 strncpy( p_client_buffer, "Running on AC Power", client_buffer_size );
391         else
392                 strncpy( p_client_buffer, "Running on battery", client_buffer_size );
393
394         return;
395 }
396
397 void get_acpi_fan( char * p_client_buffer, size_t client_buffer_size )
398 {
399         if ( !p_client_buffer !! client_buffer_size <= 0 )
400                 return;
401
402         /* not implemented */
403         memset(p_client_buffer,0,client_buffer_size);
404
405         return;
406 }
407
408 void get_adt746x_cpu( char * p_client_buffer, size_t client_buffer_size )
409 {
410         if ( !p_client_buffer || client_buffer_size <= 0 )
411                 return;
412
413         /* not implemented */
414         memset(p_client_buffer,0,client_buffer_size);
415
416         return;
417 }
418
419 void get_adt746x_fan( char * p_client_buffer, size_t client_buffer_size )
420 {
421         if ( !p_client_buffer || client_buffer_size <= 0 )
422                 return;
423
424         /* not implemented */
425         memset(p_client_buffer,0,client_buffer_size);
426
427         return; 
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 rdtsc()
434 {
435         unsigned long long int x;
436         __asm__ volatile (".byte 0x0f, 0x31":"=A" (x));
437         return x;
438 }
439 #endif
440
441 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
442 void get_freq_dynamic( char * p_client_buffer, size_t client_buffer_size, char * p_format, int divisor )
443 {
444 #if  defined(__i386) || defined(__x86_64)
445         struct timezone tz;
446         struct timeval tvstart, tvstop;
447         unsigned long long cycles[2];   /* gotta be 64 bit */
448         unsigned int microseconds;      /* total time taken */
449
450         memset(&tz, 0, sizeof(tz));
451
452         /* get this function in cached memory */
453         gettimeofday(&tvstart, &tz);
454         cycles[0] = rdtsc();
455         gettimeofday(&tvstart, &tz);
456          
457         /* we don't trust that this is any specific length of time */
458         usleep(100);
459         cycles[1] = rdtsc();
460         gettimeofday(&tvstop, &tz);
461         microseconds = ((tvstop.tv_sec - tvstart.tv_sec) * 1000000) +
462             (tvstop.tv_usec - tvstart.tv_usec);
463                              
464         snprintf( p_client_buffer, client_buffer_size, p_format, (float)((cycles[1] - cycles[0]) / microseconds) / divisor );
465         return;
466 #else
467         get_freq( p_client_buffer, client_buffer_size, p_format, divisor );
468         return;
469 #endif
470 }
471
472 /* return system frequency in MHz (use divisor=1) or GHz (use divisor=1000) */
473 void get_freq( char * p_client_buffer, size_t client_buffer_size, char * p_format, int divisor )
474 {
475         int freq;
476
477         if ( !p_client_buffer || client_buffer_size <= 0 || !p_format || divisor <= 0 )
478               return;
479         
480         if (GETSYSCTL("dev.cpu.0.freq", freq) == 0)
481         {
482                 snprintf( p_client_buffer, client_buffer_size, p_format, freq/divisor );
483         }
484         else
485         {
486                 snprintf( p_client_buffer, client_buffer_size, p_format, (float)0 );
487         }
488
489         return;
490 }
491
492 void update_top()
493 {
494         proc_find_top(info.cpu, info.memu);
495 }
496
497 void update_wifi_stats()
498 {
499         /* XXX */
500 }
501 void update_diskio()
502 {
503         int devs_count,
504             num_selected,
505             num_selections;
506         struct device_selection *dev_select = NULL;
507         long select_generation;
508         int dn;
509         static struct statinfo  statinfo_cur;
510         u_int64_t diskio_current = 0;
511
512         bzero(&statinfo_cur, sizeof(statinfo_cur));
513         statinfo_cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
514         bzero(statinfo_cur.dinfo, sizeof(struct devinfo));
515         
516         if (devstat_getdevs(NULL, &statinfo_cur) < 0)
517                 return;
518
519         devs_count = statinfo_cur.dinfo->numdevs;
520         if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
521                         &select_generation, statinfo_cur.dinfo->generation,
522                         statinfo_cur.dinfo->devices, devs_count, NULL, 0, 
523                         NULL, 0, DS_SELECT_ONLY, MAXSHOWDEVS, 1) >= 0) {
524                 for (dn = 0; dn < devs_count; ++dn) {
525                         int di;
526                         struct devstat  *dev;
527
528                         di = dev_select[dn].position;
529                         dev = &statinfo_cur.dinfo->devices[di];
530
531                         diskio_current += dev->bytes[DEVSTAT_READ] + dev->bytes[DEVSTAT_WRITE];
532                 }
533                 
534                 free(dev_select);
535         }
536
537         /* 
538          * Since we return (diskio_total_current - diskio_total_old), first
539          * frame will be way too high (it will be equal to diskio_total_current, i.e.
540          * all disk I/O since boot). That's why it is better to return 0 first time;
541          */
542         if (diskio_setup == 0) {
543                 diskio_setup = 1;
544                 diskio_value = 0;
545         } else
546                 diskio_value = (unsigned int)((diskio_current - diskio_prev)/1024);
547         diskio_prev = diskio_current;
548
549         free(statinfo_cur.dinfo);
550 }
551
552 /*
553  * While topless is obviously better, top is also not bad.
554  */
555
556 int comparecpu(const void * a, const void * b)
557 {
558         if (((struct process *)a)->amount > ((struct process *)b)->amount)
559                 return -1;
560         
561         if (((struct process *)a)->amount < ((struct process *)b)->amount)
562                 return 1;
563         
564         return 0;
565 }
566
567 int comparemem(const void * a, const void * b)
568 {
569         if (((struct process *)a)->totalmem > ((struct process *)b)->totalmem)
570                 return -1;
571         
572         if (((struct process *)a)->totalmem < ((struct process *)b)->totalmem)
573                 return 1;
574         
575         return 0;
576 }
577
578 inline void proc_find_top(struct process **cpu, struct process **mem)
579 {
580         static int kd_init = 1;
581         struct kinfo_proc *p;
582         int n_processes;
583         int i, j = 0;
584         struct process *processes;
585         
586         if (kd_init) {
587                 kd_init = 0;
588                 if ((kd =
589                      kvm_open("/dev/null", "/dev/null", "/dev/null",
590                               O_RDONLY, "kvm_open")) == NULL) {
591                         (void) fprintf(stderr, "Cannot read kvm.");
592                 }
593         }
594
595         if (kd != NULL) {
596                 int total_pages;
597
598                 /* we get total pages count again to be sure it is up to date */
599                 if (GETSYSCTL("vm.stats.vm.v_page_count", total_pages) != 0)
600                         CRIT_ERR("Cannot read sysctl \"vm.stats.vm.v_page_count\"");
601                 
602                 p = kvm_getprocs(kd, KERN_PROC_PROC, 0, &n_processes);
603                 processes = malloc(n_processes * sizeof(struct process));
604
605                 for (i = 0; i < n_processes; i++) {
606                         if (!((p[i].ki_flag & P_SYSTEM)) && 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 * p[i].ki_pctcpu / FSCALE;
610                                 processes[j].totalmem = (float)(p[i].ki_rssize / (float)total_pages) * 100.0;
611                                 j++;
612                         }
613                 }
614
615                 qsort(processes, j, sizeof(struct process), comparemem);
616                 for (i = 0; i < 10; mem[i] = &processes[i], i++);
617
618                 qsort(processes, j, sizeof(struct process), comparecpu);
619                 for (i = 0; i < 10; cpu[i] = &processes[i], i++);
620                 
621                 free(processes);
622         } else
623                 return;
624 }
625
626 #if defined(i386) || defined(__i386__)
627 #define APMDEV  "/dev/apm"
628 #define APM_UNKNOWN     255
629
630 int apm_getinfo(int fd, apm_info_t aip)
631 {
632         if (ioctl(fd, APMIO_GETINFO, aip) == -1)
633                 return -1;
634
635         return 0;
636 }
637
638 char *get_apm_adapter()
639 {
640         int fd;
641         struct apm_info info;
642
643         fd = open(APMDEV, O_RDONLY);
644         if(fd < 0) 
645                 return "ERR";
646
647         if(apm_getinfo(fd, &info) != 0 ) {
648                 close(fd);
649                 return "ERR";
650         }
651         close(fd);
652
653         switch(info.ai_acline) {
654                 case 0:
655                         return "off-line";
656                         break;
657                 case 1:
658                         if(info.ai_batt_stat == 3)
659                                 return "charging";
660                         else
661                                 return "on-line";
662                         break;
663                 default:
664                         return "unknown";
665                         break;
666         }
667 }
668
669 char *get_apm_battery_life()
670 {
671         int fd;
672         u_int batt_life;
673         struct apm_info info;
674         char *out;
675
676         out = (char *)calloc(16, sizeof(char));
677         
678
679         fd = open(APMDEV, O_RDONLY);
680         if(fd < 0) {
681                 strncpy(out, "ERR", 16);
682                 return out;
683         }
684
685         if(apm_getinfo(fd, &info) != 0 ) {
686                 close(fd);
687                 strncpy(out, "ERR", 16);
688                 return out;
689         }
690         close(fd);
691
692         batt_life = info.ai_batt_life;
693         if (batt_life == APM_UNKNOWN)
694                 strncpy(out, "unknown", 16);
695         else if (batt_life <= 100) {
696                 snprintf(out, 20,"%d%%", batt_life);
697                 return out;
698         }
699         else
700                 strncpy(out, "ERR", 16);
701
702         return out;
703 }
704
705 char *get_apm_battery_time()
706 {
707         int fd;
708         int batt_time;
709         int h, m, s;
710         struct apm_info info;
711         char *out;
712
713         out = (char *)calloc(16, sizeof(char));
714
715         fd = open(APMDEV, O_RDONLY);
716         if(fd < 0) {
717                 strncpy(out, "ERR", 16);
718                 return out;
719         }
720
721         if(apm_getinfo(fd, &info) != 0 ) {
722                 close(fd);
723                 strncpy(out, "ERR", 16);
724                 return out;
725         }
726         close(fd);
727
728         batt_time = info.ai_batt_time;
729
730         if (batt_time == -1)
731                 strncpy(out, "unknown", 16);
732         else {
733                 h = batt_time;
734                 s = h % 60;
735                 h /= 60;
736                 m = h % 60;
737                 h /= 60;
738                 snprintf(out, 16, "%2d:%02d:%02d", h, m, s);
739         }
740
741         return out;
742 }
743 #endif