#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/clonefile.h>
#include <sys/mman.h>

int main(int argc, char ** argv)
{
	// sparse mmap sync
	// block size i 4 KB
	int dst = open("cc1-mmap", O_RDONLY, 0700);
	printf("dst %i  MS_ASYNC %i  MS_INVALIDATE %i  MS_SYNC %i\n", dst, MS_ASYNC, MS_INVALIDATE, MS_SYNC);

	char * d = NULL;
	int a = 0;
	int b = 0;
	off_t s = 0;
	int ea = 0;
	int eb = 0;
	int ed = 0;
	int es = 0;

	errno = 0;
	s = lseek(dst, 0, SEEK_END);
	es = errno;

	if (s == -1)
	{
		printf(
			"lseek(SEEK_END) failed  s %lli %2i %s\n",
			s, es, strerror(es)
		);

		return 1;
	}

	d = mmap(NULL, s, PROT_READ, MAP_FILE | MAP_SHARED, dst, 0);
	ed = errno;

	if (!d)
	{
		printf("mmap failed  %p %i %s\n", d, ed, strerror(ed));
		return 2;
	}

	// MS_ASYNC 1  MS_INVALIDATE 2  MS_SYNC 16
	a = msync(d, s, 0);
	ea = errno;

	if (a == -1)
	{
		printf("msync failed  s %i %2i %s\n", a, ea, strerror(ea));
		return 3;
	}

	b = munmap(d, s);
	eb = errno;
	close(dst);

	printf("size bytes %llx  msync ok\n", s);

	return 0;
}
