/*
 * 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 <stdlib.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <string.h>
#include <errno.h>
#include <vm/vm_param.h>
#include <sys/stat.h>
#include <limits.h>
#include <fcntl.h>

#include "utils.h"

#define M_MIB_SIZE 3

extern long pagesize;
__thread int m_mib[M_MIB_SIZE];

int sa_open_memory() {
	size_t m_mib_size = M_MIB_SIZE;
	if (sysctlnametomib("vm.swap_info", m_mib, &m_mib_size) == -1)
		return ENOSYS;

	return 0;
}

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

	uint64_t tmp64 = 0;
	size_t len = sizeof tmp64;
	if (sysctlbyname("hw.physmem", &tmp64, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->total = tmp64;

	if (sysctlbyname("vfs.bufspace", &tmp64, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->buffers = tmp64;

	uint32_t tmp32;
	len = sizeof tmp32;
	if (sysctlbyname("vm.stats.vm.v_free_count", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->free = (uint64_t) tmp32 * pagesize;

	if (sysctlbyname("vm.stats.vm.v_cache_count", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->cached = (uint64_t) tmp32 * pagesize;

	if (sysctlbyname("vm.stats.vm.v_active_count", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->active = (uint64_t) tmp32 * pagesize;

	if (sysctlbyname("vm.stats.vm.v_inactive_count", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->inactive = (uint64_t) tmp32 * pagesize;

	if (sysctlbyname("vm.stats.vm.v_wire_count", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->wired = (uint64_t) tmp32 * pagesize;

	struct xswdev xsw;
	size_t size = sizeof xsw;
	dst->swap_total = 0;
	dst->swap_free = 0;
	for (m_mib[M_MIB_SIZE - 1] = 0; sysctl(m_mib, M_MIB_SIZE, &xsw, &size, NULL, 0) != -1; ++m_mib[M_MIB_SIZE - 1]) {
		dst->swap_total += (uint64_t) xsw.xsw_nblks * pagesize;
		dst->swap_free += (uint64_t)(xsw.xsw_nblks - xsw.xsw_used) * pagesize;
	}
	return 0;
}
