/*
 * 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 <kstat.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/swap.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

#include "utils.h"

__thread kstat_ctl_t* memory_kc;
__thread int pagesize = 0;

int sa_open_memory() {
	memory_kc = kstat_open();
	if (memory_kc == NULL)
		return ENOSYS;

	pagesize = sysconf(_SC_PAGESIZE);
	return 0;
}

int sa_close_memory() {
	if (memory_kc != NULL)
		kstat_close(memory_kc);
	return 0;
}

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

	kstat_t* ks;
	if (get_ks(memory_kc, &ks, "unix", "system_pages") != 0)
		return ENOSYS;

	kstat_named_t* kn = kstat_data_lookup(ks, "pagestotal");
	if (kn == NULL)
		return ENOSYS;
	dst->total = (uint64_t) kn->value.ui64 * pagesize;

	kn = kstat_data_lookup(ks, "pagesfree");
	if (kn == NULL)
		return ENOSYS;
	dst->free = (uint64_t) kn->value.ui64 * pagesize;

	kn = kstat_data_lookup(ks, "pageslocked");
	if (kn == NULL)
		return ENOSYS;
	dst->locked = (uint64_t) kn->value.ui64 * pagesize;

	struct anoninfo swap_info; 
	if (swapctl(SC_AINFO, &swap_info) == -1)
		return ENOSYS; 
	dst->swap_total = swap_info.ani_max;
	dst->swap_free = swap_info.ani_free; 

	return 0;
}
