/*
 * 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 <pthread.h>
#include <errno.h>
#include <osreldate.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <sys/sysctl.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void percentages(long* new, long* old) SA_NONNULL;
static void assign(struct sa_cpu* dst) SA_NONNULL;

__thread long cp_time[CPUSTATES];
__thread long cp_old[CPUSTATES]; // its first value is zero

int sa_reset_cpus() {
	size_t len = sizeof cp_time;
	if (sysctlbyname("kern.cp_time", &cp_time, &len, NULL, 0) == -1)
		return ENOSYS;

	return 0;
}

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

	*number = 1;
	return 0;
}

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

	percentages(cp_time, cp_old);
	assign(dst);
	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;
	percentages(cp_time, cp_old);
	assign(dst);
	return 0;
}

/*
 * 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 void percentages(long* new, long* old) {
	register int i;
	long change;
	long total_change;
	long half_total;
	long cp_diff[CPUSTATES];

	total_change = 0;

	/* calculate changes for each state and the overall change */
	for (i = 0; i < CPUSTATES; ++i) {
		if ((change = new[i] - old[i]) < 0) {
			/* this only happens when the counter wraps */
			change = (int) ((unsigned long) new[i] - (unsigned long) old[i]);
		}
		total_change += (cp_diff[i] = change);
		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;
}

static void assign(struct sa_cpu* dst) {
	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;
}
