2 * mem_freebsd.c - module to get memory/swap usages in percent, for FreeBSD
4 * Copyright(c) 2001 Seiichi SATO <ssato@sh.rim.or.jp>
6 * licensed under the GPL
18 #include <vm/vm_param.h>
19 #include <sys/errno.h>
20 #include <sys/sysctl.h>
23 /* initialize function */
29 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var))
31 static void getsysctl(const char *name
, void *ptr
, size_t len
)
35 if (sysctlbyname(name
, ptr
, &nlen
, NULL
, 0) == -1) {
36 fprintf(stderr
, "sysctl(%s...) failed: %s\n", name
,
41 fprintf(stderr
, "sysctl(%s...) expected %lu, got %lu\n",
42 name
, (unsigned long)len
, (unsigned long)nlen
);
47 /* return mem/swap usage in percent 0 to 100 */
48 void mem_getusage(int *per_mem
, int *per_swap
, const struct mem_options
*opts
)
50 u_int mtotal
, mwired
, mcached
, mfree
, mused
;
54 u_int new_swappgsin
, new_swappgsout
;
55 static int swap_firsttime
= 1;
56 static int swappgsin
= -1;
57 static int swappgsout
= -1;
58 static int swapmax
, swapused
;
60 static time_t last_time_swap
;
64 GETSYSCTL("vm.stats.vm.v_page_count", mtotal
);
65 GETSYSCTL("vm.stats.vm.v_wire_count", mwired
);
66 GETSYSCTL("vm.stats.vm.v_cache_count", mcached
);
67 GETSYSCTL("vm.stats.vm.v_free_count", mfree
);
69 GETSYSCTL("hw.pagesize", pagesize
);
73 /* only calculate when first time or when changes took place */
74 /* do not call it more than 1 time per 2 seconds */
75 /* otherwise it can eat up to 50% of CPU time on heavy swap activity */
76 cur_time
= time(NULL
);
78 GETSYSCTL("vm.stats.vm.v_swappgsin", new_swappgsin
);
79 GETSYSCTL("vm.stats.vm.v_swappgsout", new_swappgsout
);
82 (((new_swappgsin
> swappgsin
) || (new_swappgsout
> swappgsout
))
83 && cur_time
> last_time_swap
+ 1)) {
88 mibsize
= sizeof(mib
) / sizeof(mib
[0]);
89 if (sysctlnametomib("vm.swap_info", mib
, &mibsize
) == -1) {
90 fprintf(stderr
, "sysctlnametomib() failed: %s\n", strerror(errno
));
100 if (sysctl(mib
, mibsize
+ 1, &xsw
, &size
, NULL
, 0) == -1) {
103 fprintf(stderr
, "sysctl() failed: %s\n", strerror(errno
));
106 swapmax
+= xsw
.xsw_nblks
;
107 swapused
+= xsw
.xsw_used
;
111 last_time_swap
= cur_time
;
114 swappgsin
= new_swappgsin
;
115 swappgsout
= new_swappgsout
;
118 printf("-------------------\n");
119 printf("total:%10d\n", mtotal
* pagesize
);
120 printf("free :%10d\n", mfree
* pagesize
);
121 printf("wired:%10d\n", mwired
* pagesize
);
122 printf("cache:%10d\n", mcached
* pagesize
);
123 printf("-------------------\n");
126 /* calc mem/swap usage in percent */
127 mused
= mtotal
- mfree
;
128 if (opts
->ignore_wired
)
130 if (opts
->ignore_cached
)
132 *per_mem
= 100 * (double) mused
/ (double) mtotal
;
133 *per_swap
= 100 * (double) swapused
/ (double) swapmax
;