#include <sys/mman.h>
#include <sys/stat.h>

#include <err.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
	unsigned char byte;
	char *end;
	void *map;
	uintmax_t raw_offset;
	off_t map_offset, offset;
	size_t delta, pagesize;
	struct stat sb;
	int fd;

	if (argc != 3)
		errx(2, "usage: sparse_hole_probe file offset");
	raw_offset = strtoumax(argv[2], &end, 0);
	if (*argv[2] == '\0' || *end != '\0' || raw_offset > INT64_MAX)
		errx(2, "invalid offset: %s", argv[2]);
	offset = (off_t)raw_offset;
	pagesize = (size_t)getpagesize();
	map_offset = offset & ~((off_t)pagesize - 1);
	delta = (size_t)(offset - map_offset);

	fd = open(argv[1], O_RDONLY);
	if (fd < 0)
		err(1, "open %s", argv[1]);
	if (fstat(fd, &sb) != 0)
		err(1, "fstat %s", argv[1]);
	if (offset < 0 || offset >= sb.st_size ||
	    sb.st_size - offset < (off_t)(pagesize - delta))
		errx(1, "probe page is outside the file");
	if (pread(fd, &byte, 1, offset) != 1)
		err(1, "pread at %jd", (intmax_t)offset);
	if (byte != 0)
		errx(1, "pread returned non-zero byte %#x", byte);

	map = mmap(NULL, pagesize, PROT_READ, MAP_PRIVATE, fd, map_offset);
	if (map == MAP_FAILED)
		err(1, "mmap at %jd", (intmax_t)map_offset);
	if (madvise(map, pagesize, MADV_DONTNEED) != 0)
		err(1, "madvise");
	if (((const unsigned char *)map)[delta] != 0 ||
	    ((const unsigned char *)map)[pagesize - 1] != 0)
		errx(1, "mmap returned non-zero hole data");
	if (munmap(map, pagesize) != 0)
		err(1, "munmap");
	if (close(fd) != 0)
		err(1, "close");

	printf("PASS size=%jd offset=%jd pread=zero mmap-page=zero\n",
	    (intmax_t)sb.st_size, (intmax_t)offset);
	return (0);
}
