freebsd memory usage

This commit is contained in:
bch 2018-12-26 18:46:16 +00:00
parent 3b3d39c18c
commit 75987c50d6

113
get_mem_fbsd.c Normal file
View File

@ -0,0 +1,113 @@
/* $Id: get_mem_fbsd.c,v 1.1 2018/12/26 18:46:16 bch Exp $
*
* Author: Christian Barthel <bch@online.de>
*/
#include <sys/types.h> /* DEV_BSIZE MAXCOMLEN PZERO */
#include <sys/sysctl.h>
#include <unistd.h>
#include <kvm.h>
#include <X11/Xos.h>
#include <X11/Intrinsic.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include "MemStripChart.h"
static int pageshift = -1;
static int pagesize = 0;
static kvm_t *kd = 0;
#define pagetok(size) ((size) << pageshift)
#define LOG1024 10
static unsigned int allmem_pages = 0;
static void initPageShift(void)
{
pagesize = getpagesize();
size_t len = sizeof(allmem_pages);
int mib[len];
pageshift = 0;
while (pagesize > 1) {
pageshift++;
pagesize >>= 1;
}
pageshift -= LOG1024;
kd = kvm_open(NULL, "/dev/null" ,NULL, O_RDONLY, "kvm_open");
if (sysctlbyname("vm.stats.vm.v_page_count", &allmem_pages, &len, NULL, 0) == -1)
perror("sysctl");
#ifdef DEBUG
printf("page_count: %d\n", allmem_pages);
#endif
}
static double getSwapFrac()
{
/* XXX Borrowed from top(1) code: */
int n;
struct kvm_swap swapary[1];
static int pagesize = 0;
static unsigned long swap_maxpages = 0;
size_t sz = sizeof(swap_maxpages);
int retavail = 0;
int retfree = 0;
n = kvm_getswapinfo(kd, swapary, 1, 0);
if (n < 0 || swapary[0].ksw_total == 0)
return (0);
if (swap_maxpages == 0)
sysctlbyname("vm.swap_maxpages", &swap_maxpages, &sz, NULL, 0);
if ( swapary[0].ksw_total > swap_maxpages )
swapary[0].ksw_total = swap_maxpages;
retavail = swapary[0].ksw_total;
retfree = swapary[0].ksw_total - swapary[0].ksw_used;
#ifdef DEBUG
printf("swap: %d %d %d %d\n", retavail, retavail, swapary[0].ksw_total,
swapary[0].ksw_used);
#endif
return (double)(retavail-retfree)/(double)retavail;
}
void GetMemLoadPoint(Widget w, caddr_t closure, caddr_t call_data)
{
MemStripChartCallbackData ret;
int a, b;
size_t sz = sizeof(int);
double cache = 0;
if (pageshift < 0)
initPageShift();
sysctlbyname("vm.stats.vm.v_wire_count", &a, &sz, NULL, 0);
ret.code = (double)a / (double)allmem_pages;
sysctlbyname("vm.stats.vm.v_active_count", &a, &sz, NULL, 0);
ret.buffer = (double)a / (double)allmem_pages;
/* v_cache_count and v_inactive_count are treated similarly */
sysctlbyname("vm.stats.vm.v_inactive_count", &a, &sz, NULL, 0);
sysctlbyname("vm.stats.vm.v_cache_count", &b, &sz, NULL, 0);
ret.cached = (double)(a + b) / allmem_pages;
sysctlbyname("vm.stats.vm.v_free_count", &a, &sz, NULL, 0);
ret.free = (double)a / allmem_pages;
ret.swap = getSwapFrac();
#ifdef DEBUG
printf("%u %lf %lf %lf %lf\n", allmem_pages,
ret.code, ret.cached, ret.free, ret.swap);
#endif
memcpy(call_data, &ret, sizeof(MemStripChartCallbackData));
}