/*
 * libsysactivity
 * http://sourceforge.net/projects/libsysactivity/
 * Copyright (c) 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 <sys/conf.h>
#include <limits.h>
#include "utils.h"

#define MIB_SIZE 3

__thread int m_mib[MIB_SIZE];
extern long pagesize;

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;

	// See http://bugs.dragonflybsd.org/issue1805 and
	// http://gitweb.dragonflybsd.org/dragonfly.git/blobdiff/878e32ca6306f6d48a6232ff29a6611adc74bd01..97a3ace7a60a869c957f6c0bb6d9f69bce477f80:/sys/vm/swap_pager.c
	if (sysctlbyname("vm.swap_size", &tmp32, &len, NULL, 0) == -1)
		return ENOSYS;
	dst->swap_total = (uint64_t) tmp32 * pagesize;

	size_t swap_anon_use;
	len = sizeof swap_anon_use;
	if (sysctlbyname("vm.swap_anon_use", &swap_anon_use, &len, NULL, 0) == -1)
		return ENOSYS;

	size_t swap_cache_use;
	len = sizeof swap_cache_use;
	if (sysctlbyname("vm.swap_cache_use", &swap_cache_use, &len, NULL, 0) == -1)
		return ENOSYS;

	dst->swap_free = (tmp32 - swap_anon_use - swap_cache_use) * pagesize;

	return 0;
}
