/*
 * 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/sysctl.h>
#include <sys/sched.h> /* CPUSTATES */
#include <pthread.h>
#include <stdlib.h>
#include <errno.h>

#include "../OpenBSD/utils.h"

static void create_keys();
static void calculate_cpu(struct sa_cpu* dst) SA_NONNULL;
static inline void percentages(u_int64_t *new, u_int64_t *old) SA_NONNULL;

pthread_key_t cp_time_key;
pthread_key_t cp_old_key;

int sa_open_cpu() {
	pthread_once_t key_once = PTHREAD_ONCE_INIT;
	if (pthread_once(&key_once, create_keys))
		return ENOSYS;

	u_int64_t * cp_time = malloc(CPUSTATES * sizeof (u_int64_t));
	if (cp_time == NULL)
		return ENOMEM;
	if (pthread_setspecific(cp_time_key, cp_time))
		return ENOSYS;

	u_int64_t * cp_old = malloc(CPUSTATES * sizeof (u_int64_t));
	if (cp_old == NULL)
		return ENOMEM;
	if (pthread_setspecific(cp_old_key, cp_old))
		return ENOSYS;
	return 0;
}

int sa_reset_cpus() {
	u_int64_t* cp_time = pthread_getspecific(cp_time_key);
	int cp_time_mib[] = { CTL_KERN, KERN_CP_TIME };
	size_t size = CPUSTATES * sizeof (u_int64_t);
	if (sysctl(cp_time_mib, 2, cp_time, &size, NULL, 0) == -1)
		return ENOSYS;

	return 0;
}

int sa_get_cpu(uint16_t index, struct sa_cpu* dst) {
	if (index > 0 || dst == NULL)
		return EINVAL;

	calculate_cpu(dst);
	return 0;
}

int sa_count_cpus(uint16_t* number) {
	if (number == NULL)
		return EINVAL;

	*number = 1;
	return 0;
}

int sa_get_cpus(struct sa_cpu* dst, uint16_t dst_size, uint16_t* written) {
	if (dst == NULL || dst_size == 0 || written == NULL)
		return EINVAL;

	*written = 1;
	calculate_cpu(dst);
	return 0;
}

static void create_keys() {
	static short keys_created = 0;
	if (keys_created) {
		return;
	}

	pthread_key_create(&cp_time_key, free_keys);
	pthread_key_create(&cp_old_key, free_keys);
	keys_created = 1;
}

static void calculate_cpu(struct sa_cpu* dst) {
	u_int64_t* cp_time = pthread_getspecific(cp_time_key);
	u_int64_t* cp_old = pthread_getspecific(cp_old_key);
	percentages(cp_time, cp_old);

	dst->id = 0;
	dst->user = cp_time[CP_USER] / 10;
	dst->nice = cp_time[CP_NICE] / 10;
	dst->system = cp_time[CP_SYS] / 10;
	dst->idle = cp_time[CP_IDLE] / 10;
	dst->intr = cp_time[CP_INTR] / 10;
}

/*
 * This function is taken from unixtop 3.8beta1 at http://www.unixtop.org/download/
 *
 * Copyright (c) 1984 through 2008, William LeFebvre
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 *     * Neither the name of William LeFebvre nor the names of other
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
static inline void percentages(u_int64_t *new, u_int64_t *old) {
	register int i;
	u_int64_t total_change;
	u_int64_t half_total;
	u_int64_t cp_diff[CPUSTATES];

	total_change = 0;

	/* calculate changes for each state and the overall change */
	for (i = 0; i < CPUSTATES; ++i) {
		total_change += (cp_diff[i] = new[i] - old[i]);
		old[i] = new[i];
	}

	/* avoid divide by zero potential */
	if (total_change == 0)
		total_change = 1;

	/* calculate percentages based on overall change, rounding up */
	half_total = total_change / 2l;
	for (i = 0; i < CPUSTATES; ++i)
		new[i] = (cp_diff[i] * 1000 + half_total) / total_change;
}
