#define _GNU_SOURCE
#include <features.h>
#include <stdbool.h>
#include <limits.h>
#include <linux/hpet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <memory.h>
#include <malloc.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <errno.h>
#include <sys/time.h>
#include <sys/mman.h>

bool hpet_open_close(int, const char **);
bool hpet_mmap(int, const char **);
bool hpet_info(int, const char **);
bool hpet_poll(int, const char **);
bool hpet_fasync(int, const char **);
bool hpet_read(int, const char **);
bool hpet_help(int, const char **);

#include <sys/poll.h>
#include <sys/ioctl.h>

struct hpet_command {
	char		*command;
	bool		(*func)(int argc, const char ** argv);
} hpet_command[] = {
	{
		"open-close",
		hpet_open_close
	},
	{
		"mmap",
		hpet_mmap
	},
	{
		"info",
		hpet_info
	},
	{
		"poll",
		hpet_poll
	},
	{
		"fasync",
		hpet_fasync
	},
	{
		"help",
		hpet_help
	},
	{
		"--help",
		hpet_help
	},
};

int main(int argc, const char ** argv)
{
	int	i;
	const char	*myname;

	myname = argv[0];
	argc--;
	argv++;

	if (!argc) {
		fprintf(stderr, "-hpet: requires command\n");
		return -1;
	}


	for (i = 0; i < (sizeof (hpet_command) / sizeof (hpet_command[0])); i++)
		if (!strcmp(argv[0], hpet_command[i].command)) {
			argc--;
			argv++;
			fprintf(stderr, "%s: executing %s\n",
				myname, hpet_command[i].command);
			if (!hpet_command[i].func(argc, argv)) {
				return 2;
			}
			return 0;
		}

	fprintf(stderr, "do_hpet: command %s not implemented\n", argv[0]);
	hpet_help(argc, argv);
	return -1;
}

bool hpet_help(int argc, const char **argv)
{	fprintf(stdout,
		"commands and arguments:\n"
		"open-close device_path [iterations]\n"
		"mmap device_path [offset] [size] [dump_size]\n"
		"info device_path\n"
		"poll device_path frequency iterations\n"
		"fasync device_name frequency iterations\n"
	);
	return true;
}

const char *path_none = "-";

bool hpet_open_close(int argc, const char **argv)
{
	const char	*path;
	int		fd;
	int		i;
	int		iterations;
	bool		result;

	result = false;
	path = path_none;
	if (argc < 1) {
		fprintf(stderr, "%s: %s.arg: device-path [iterations]\n",
			path, __func__
		);
		goto out;
	}
	path = argv[0];
	iterations = 1;
	if (argc >= 2) {
		const char	*p;
		char		*p2;
		
		p = argv[1];
		p2 = NULL;
		iterations = strtol(p, &p2, 0);
		if ((p2 == NULL) || (p2 == p)) {
			iterations = 1;
		}
	}
	result = true;
	i = 0;
	while (i < iterations) {
		fprintf(stdout, "%s: %s.open-close: try loop. i=%d\n",
			path, __func__, i
		);
		fd = open(path, O_RDONLY);
		if (fd < 0) {
			fprintf(stderr, "%s: %s.open: %s\n",
				path, __func__, strerror(errno)
			);
			result = false;
			goto out;
		}
		if (close(fd) != 0) {
			fprintf(stderr,"%s: %s.close: %s\n",
				path, __func__, strerror(errno)
			);
			result = false;
			goto out;
		}
		i++;
	}
out:
	if (result) {
		fprintf(stdout,"%s: %s.TEST: PASS.\n",
			path, __func__
		);
	} else {
		fprintf(stdout,"%s: %s.TEST: FAIL.\n",
			path, __func__
		);
	}
	return result;
}

void dump_memory_qword(unsigned long long *m, size_t elems)
{	size_t	i;
	size_t	c;
	i = 0;
	c = 0;
	while (i < elems) {
		if (c == 0) {
			fprintf(stdout, "%.4lx:", i * sizeof(unsigned long long));
		}
		fprintf(stdout, "%.16llx", *m);
		c++;
		if (c >= 2) {
			fprintf(stdout, "\n");
			c = 0;
		} else {
			fprintf(stdout, " ");
		}
		m++;
		i++;
	}
}

bool hpet_mmap(int argc, const char **argv)
{
	const char	*path;
	int		fd;
	off_t		offset;
	size_t		size;
	size_t		dump_size;
	bool		result;
	void		*hpet_reg;

	fd = -1;
	result = false;
	path = path_none;
	if (argc < 1) {
		fprintf(stderr, "%s: %s.arg: device-path [offset] [size] [dump_size]\n",
			path, __func__
		);
		goto out;
	}
	path = argv[0];

	offset = 0;
	if (argc >= 2) {
		const char	*p;
		char		*p2;
		
		p = argv[1];
		p2 = NULL;
		offset = strtoul(p, &p2, 0);
		if ((p2 == NULL) || (p2 == p)) {
			offset = 0;
		}
	}

	size = sysconf(_SC_PAGESIZE);
	if (argc >= 3) {
		const char	*p;
		char		*p2;
		
		p = argv[2];
		p2 = NULL;
		size = strtoul(p, &p2, 0);
		if ((p2 == NULL) || (p2 == p)) {
			size = 0;
		}
	}
	dump_size = size;
	if (argc >= 4) {
		const char	*p;
		char		*p2;
		
		p = argv[3];
		p2 = NULL;
		dump_size = strtoul(p, &p2, 0);
		if ((p2 == NULL) || (p2 == p)) {
			dump_size = size;
		}
	}

	result = true;
	fprintf(stdout, "%s: %s.mmap: test. offset=0x%lx, size=0x%lx, dump_size=0x%lx\n",
			path, __func__, offset, size, dump_size
	);
	fd = open(path, O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "%s: %s.open: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
		goto out;
	}
	hpet_reg = mmap(NULL, size, PROT_READ | PROT_WRITE,
		MAP_PRIVATE, fd, offset
	);
	if (hpet_reg == MAP_FAILED) {
		fprintf(stderr,"%s: %s.mmap: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	}
	if (close(fd) != 0) {
		fprintf(stderr,"%s: %s.close: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	} else {
		fd = -1;
	}
	if (hpet_reg != MAP_FAILED) {
		dump_memory_qword(hpet_reg, dump_size / sizeof(unsigned long long));
		if (munmap(hpet_reg, size) != 0) {
			fprintf(stderr,"%s: %s.munmap: %s\n",
				path, __func__, strerror(errno)
			);
			result = false;
		}
	}
out:
	if (fd >= 0) {
		if (close(fd) != 0) {
			fprintf(stderr,"%s: %s.close: %s\n",
				path, __func__, strerror(errno)
			);
			result = false;
		}
	}
	if (result) {
		fprintf(stdout,"%s: %s.TEST: PASS.\n",
			path, __func__
		);
	} else {
		fprintf(stdout,"%s: %s.TEST: FAIL.\n",
			path, __func__
		);
	}
	return result;
}



bool hpet_info(int argc, const char **argv)
{
	const char		*path;
	struct hpet_info	info;
	int			fd;
	bool			result;

	result = false;
	path = path_none;
	if (argc != 1) {
		fprintf(stderr, "%s: %s.arg: device-name\n",
			path, __func__
		);
		goto out_before_open;
	}
	path = argv[0];
	fd = open(path, O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "%s: %s.open: %s.\n",
			path, __func__, strerror(errno)
		);
		goto out_before_open;
	}

	memset(&info, 0, sizeof(info));

	if (ioctl(fd, HPET_INFO, &info) < 0) {
		fprintf(stderr, "%s: %s.INFO: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}


	fprintf(stdout, "%s: %s.print: hi_ireqfreq=0x%lx, hi_flags=0x%lx ",
		path, __func__, info.hi_ireqfreq, info.hi_flags);
	fprintf(stdout, "hi_hpet=%d, hi_timer=%d\n",
		info.hi_hpet, info.hi_timer);
	result = true;

out:
	if (close(fd) != 0) {
		fprintf(stderr, "%s: %s.close: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	}
out_before_open:
	if (result) {
		fprintf(stdout,"%s: %s.TEST: PASS.\n",
			path, __func__
		);
	} else {
		fprintf(stdout,"%s: %s.TEST: FAIL.\n",
			path, __func__
		);
	}
	return result;
}

bool hpet_poll(int argc, const char **argv)
{
	const char		*path;
	unsigned long		freq;
	int			iterations;
	int			i, fd;
	struct pollfd		pfd;
	struct hpet_info	info;
	struct timeval		stv, etv;
	struct timezone		tz;
	long			usec;
	bool			result;

	result = false;
	path = path_none;
	if (argc != 3) {
		fprintf(stderr, "%s: device-name frequency iterations\n",
			__func__
		);
		goto out_before_open;
	}
	path = argv[0];
	freq = atoi(argv[1]);
	iterations = atoi(argv[2]);

	fd = open(path, O_RDONLY);

	if (fd < 0) {
		fprintf(stderr, "%s: %s.open: %s\n",
			path, __func__, strerror(errno)
		);
		goto out_before_open;
	}

	if (ioctl(fd, HPET_IRQFREQ, freq) < 0) {
		fprintf(stderr, "%s: %s.IRQFREQ: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	if (ioctl(fd, HPET_INFO, &info) < 0) {
		fprintf(stderr, "%s: %s.INFO: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	fprintf(stdout, "%s: %s.print: info.hi_ireqfreq=%lu, info.hi_flags=0x%lx\n",
		path, __func__, info.hi_ireqfreq, info.hi_flags
	);

	if (info.hi_flags && (ioctl(fd, HPET_EPI, 0) < 0)) {
		fprintf(stderr, "%s: %s.EPI: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	if (ioctl(fd, HPET_IE_ON, 0) < 0) {
		fprintf(stderr, "%s: %s.IE_ON: %s\n", path, __func__,
			strerror(errno)
		);
		goto out;
	}

	pfd.fd = fd;
	pfd.events = POLLIN;
	result = true;
	for (i = 0; i < iterations; i++) {
		pfd.revents = 0;
		gettimeofday(&stv, &tz);
		if (poll(&pfd, 1, -1) < 0) {
			fprintf(stderr, "%s: %s.poll: %s\n",
				path, __func__, strerror(errno)
			);
			result = false;
		} else {
			long 	data;

			gettimeofday(&etv, &tz);
			usec = stv.tv_sec * 1000000 + stv.tv_usec;
			usec = (etv.tv_sec * 1000000 + etv.tv_usec) - usec;

			fprintf(stdout,
				"%s: %s.loop_0: expired time=%ld us\n",
					path, __func__, usec
			);

			fprintf(stdout, "%s: %s.loop_1: revents=0x%x\n",
				path, __func__, pfd.revents
			);

			if (read(fd, &data, sizeof(data)) != sizeof(data)) {
				fprintf(stderr, "%s: %s.read: %s\n",
					path, __func__, strerror(errno));
				result = false;
			}
			else
				fprintf(stdout, "%s: %s.read: data=0x%lx\n",
					path, __func__, data
				);
		}
	}
out:
	if (close(fd) != 0) {
		fprintf(stderr, "%s: %s.close: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	}
out_before_open:
	if (result) {
		fprintf(stdout,"%s: %s.TEST: PASS.\n",
			path, __func__
		);
	} else {
		fprintf(stdout,"%s: %s.TEST: FAIL.\n",
			path, __func__
		);
	}
	return result;
}

static int			hpet_sigio_count;
static siginfo_t		hpet_sigio_info;

static void hpet_sigio(int val, siginfo_t *info, void *context)
{
	fprintf(stderr, "hpet_sigio: called\n");
	hpet_sigio_info = *info;
	hpet_sigio_count++;
}

bool hpet_fasync(int argc, const char **argv)
{
	const char		*path;
	unsigned long		freq;
	int			iterations, i, fd, value;
	int			ret;
	struct sigaction	sigact;
	struct sigaction	sigact_old;

	struct hpet_info	info;
	bool			result;

	result = false;
	path = path_none;
	hpet_sigio_count = 0;
	memset(&sigact, 0, sizeof(sigact));
	memset(&sigact_old, 0, sizeof(sigact));

	if (argc < 3) {
		fprintf(stderr, "%s: %s.arg: device-name freq iterations\n",
			path, __func__
		);
		goto out_before_sigset;
	}

	path = argv[0];
	sigact.sa_sigaction = hpet_sigio;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = SA_SIGINFO;

	if (sigaction(SIGIO, &sigact, &sigact_old) != 0) {
		fprintf(stderr, "%s: %s.sigaction_0: %s\n",
			path, __func__, strerror(errno)
		);
		goto out_before_sigset;
	}

	fd = open(argv[0], O_RDONLY);
	if (fd < 0) {
		fprintf(stderr, "%s: %s.open: %s\n",
			path, __func__, strerror(errno)
		);
		goto out_before_open;
	}
	fprintf(stdout, "%s: %s.fd: fd=%d\n",
		path, __func__, fd
	);

	if (fcntl(fd, F_SETOWN, getpid()) != 0) {
		fprintf(stderr, "%s: %s.F_SETOWN: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	value = fcntl(fd, F_GETFL);
	value |= O_ASYNC;
	if (fcntl(fd, F_SETFL, value) != 0) {
		fprintf(stderr, "%s: %s.F_SETFL: %s value=0x%x\n",
			path, __func__, strerror(errno), value
		);
		goto out;
	}

	if (fcntl(fd, F_SETSIG, SIGIO) != 0) {
		fprintf(stderr, "%s: %s.F_SETSIG: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	freq = atoi(argv[1]);
	iterations = atoi(argv[2]);

	if (ioctl(fd, HPET_IRQFREQ, freq) != 0) {
		fprintf(stderr, "%s: %s.IRQFREQ: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	if (ioctl(fd, HPET_INFO, &info) != 0) {
		fprintf(stderr, "%s: %s.INFO: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	fprintf(stdout, "%s: %s.print: info.hi_flags=0x%lx\n",
		path, __func__, info.hi_flags
	);

	if (info.hi_flags && (ioctl(fd, HPET_EPI, 0) != 0)) {
		fprintf(stderr, "%s: %s.EPI: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	if (ioctl(fd, HPET_IE_ON, 0) != 0) {
		fprintf(stderr, "%s: %s.IE_ON: %s\n",
			path, __func__, strerror(errno)
		);
		goto out;
	}

	result = true;
	for (i = 0; i < iterations; i++) {
		ret = pause();
		if (ret == 0) {
			fprintf(stderr, "%s: %s.pause: Returns without error\n",
				path, __func__
			);
			result = false;
		} else {
			if (errno != EINTR) {
				fprintf(stderr, "%s: %s.pause: %s\n",
					path, __func__, strerror(errno)
				);
				result = false;
			}
		}
		fprintf(stdout, "%s: %s.pause: count=%d, si_signo=%d, si_errno=%d, si_code=0x%x, si_band=0x%lx, si_fd=%d\n",
			path, __func__, hpet_sigio_count,
			hpet_sigio_info.si_signo,
			hpet_sigio_info.si_errno,
			hpet_sigio_info.si_code,
			hpet_sigio_info.si_band,
			hpet_sigio_info.si_fd
		);
	}

out:
	if (close(fd) != 0) {
		fprintf(stderr, "%s: %s.close: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	}
out_before_open:
	if (sigaction(SIGIO, &sigact_old, &sigact) != 0) {
		fprintf(stderr, "%s: %s.sigaction_1: %s\n",
			path, __func__, strerror(errno)
		);
		result = false;
	}

out_before_sigset:
	if (result) {
		fprintf(stdout,"%s: %s.TEST: PASS.\n",
			path, __func__
		);
	} else {
		fprintf(stdout,"%s: %s.TEST: FAIL.\n",
			path, __func__
		);
	}
	return result;
}
