/*
 *  nzmmap-test by Davide Libenzi (test program for MAP_NOZERO)
 *  Copyright (C) 2007  Davide Libenzi
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Davide Libenzi <davidel@xmailserver.org>
 *
 */

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>

#ifndef MAP_NOZERO
#define MAP_NOZERO	0x04000000
#endif

#define DEFAULT_SIZE	(sysconf(_SC_PAGESIZE) * 32)

static int page_is_zero(void *page, unsigned int pgsize) {
	unsigned long *p, *top;

	p = page;
	top = page + pgsize;
	/*
	 * Write-fault the page before, otherwise you get ZERO_PAGE plus
	 * copy_page() behaviour ...
	 */
	*p++ = 1;
	for (; p < top; p++)
		if (*p)
			return 0;
	((unsigned long *) page)[1] = 2;

	return 1;
}

static int test_mmap(unsigned int size, unsigned int mmflags) {
	unsigned int pgsize, nzcount;
	char *addr, *p, *top;

	pgsize = sysconf(_SC_PAGESIZE);
	size = ((size + pgsize - 1) / pgsize) * pgsize;
	addr = mmap(NULL, size, PROT_READ | PROT_WRITE, mmflags, -1, 0);
	if (addr == MAP_FAILED) {
		perror("mmap");
		return -1;
	}
	for (p = addr, top = addr + size, nzcount = 0; p < top; p += pgsize) {
		if (!page_is_zero(p, pgsize))
			nzcount++;
	}
	munmap(addr, size);
	fprintf(stdout, "mapping had %u non-zero pages\n", nzcount);

	return 0;
}

int main(int ac, char **av) {
	int i;
	unsigned int size = DEFAULT_SIZE, mmflags = MAP_ANONYMOUS | MAP_PRIVATE;

	while ((i = getopt(ac, av, "s:nh")) != -1) {
		switch (i) {
		case 's':
			size = atoi(optarg);
			break;
		case 'n':
			mmflags |= MAP_NOZERO;
			break;
		case 'h':

			break;
		}
	}
	test_mmap(size, mmflags);

	return 0;
}


