/*
 * libsysactivity
 * http://sourceforge.net/projects/libsysactivity/
 * Copyright (c) 2009, 2010 Carlos Olmedo Escobar <carlos.olmedo.e@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/param.h>
#include <sys/swap.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include "utils.h"

int pagesize;

int sa_open_memory() {
	int mib[] = { CTL_HW, HW_PAGESIZE };
	size_t len = sizeof (pagesize);
	if (sysctl(mib, 2, &pagesize, &len, NULL, 0) == -1)
		return ENOSYS;
	return 0;
}

int sa_get_memory(struct sa_memory* dst) {
	if (dst == NULL)
		return EINVAL;

	size_t memory_total;
	int mib[] = { CTL_HW, HW_PHYSMEM };
	size_t len = sizeof memory_total;
	if (sysctl(mib, 2, &memory_total, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->total = (uint64_t) memory_total;

	mib[0] = CTL_VM;
	mib[1] = VM_METER;
	struct vmtotal vmtotal;
	len = sizeof vmtotal;
	if (sysctl(mib, sizeof(mib) / sizeof(int), &vmtotal, &len, NULL, 0) == -1)
		return ENOSYS;

	dst->free = (uint64_t) vmtotal.t_free * pagesize;
	dst->active = (uint64_t) vmtotal.t_arm * pagesize;
	dst->inactive = (uint64_t) vmtotal.t_rm * pagesize;

	struct swapent swapent;
	if (swapctl(SWAP_STATS, &swapent, 1) == -1)
		return ENOSYS;
	dst->swap_total = (uint64_t) swapent.se_nblks * DEV_BSIZE;
	dst->swap_free = (uint64_t) (swapent.se_nblks - swapent.se_inuse) * DEV_BSIZE;
	return 0;
}
