#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <pthread.h>

/*
 * Usage: mmap_fault_vs_drop_caches /mnt/lustre/file
 *
 * Create and write /mnt/lustre/file{0..31}.

 * Race reads of the same file on two client mounts vs writes and drop
 * caches to detect sequential consistency violations. Run
 * indefinately.  all abort() if a consistency violation is found in
 * which case the wait status ($?) will be 134.
*/

#define handle_error(msg)	\
	do { perror(msg); exit(EXIT_FAILURE); } while (0)

enum {
	map_count = 128,
	map_size = 32768,
};

static char *map_base[map_count];

static void *access_thread_start(void *unused)
{
	while (1) {
		char *base = map_base[random() % map_count];
		char *addr = base + (random() % map_size);

		*addr = 'B';
	}

	return NULL; /* Make gcc happy. */
}

int main(int argc, char *argv[])
{
	int drop_caches_fd = -1;
	pthread_t access_thread;
	char buf[map_size];
	uint64_t u, u_max = UINT64_MAX / 2;
	ssize_t rc;
	size_t i;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s /mnt/lustre/file", argv[0]);
		exit(EXIT_FAILURE);
	}

	drop_caches_fd = open("/proc/sys/vm/drop_caches", O_WRONLY);
	if (drop_caches_fd < 0)
		handle_error("open");

	memset(buf, 'A', sizeof(buf));

	for (i = 0; i < map_count; i++) {
		char path[PATH_MAX];
		int fd = -1;

		snprintf(path, sizeof(path), "%s%zu", argv[1], i);

		fd = open(path, O_RDWR|O_CREAT|O_TRUNC);
		if (fd < 0)
			handle_error("open");

		rc = write(fd, buf, sizeof(buf));
		if (rc < 0 || rc != sizeof(buf))
			handle_error("write");

		map_base[i] = mmap(NULL, map_size, PROT_READ|PROT_WRITE,
				   MAP_SHARED /* MAP_* flags */,
				   fd,
				   0 /* offset */);
		if (map_base[i] == MAP_FAILED)
			handle_error("mmap");

		rc = close(fd);
		if (rc < 0)
			handle_error("close");
	}

	rc = pthread_create(&access_thread, NULL, &access_thread_start, NULL);
	if (rc != 0)
		handle_error("pthread_create");

	for (u = 0; u < u_max; u++) {
		rc = write(drop_caches_fd, "3\n", 2);
		if (rc < 0 || rc != 2)
			handle_error("drop caches");
	}

	rc = pthread_cancel(access_thread);
	if (rc != 0)
		handle_error("pthread_cancel");

	rc = pthread_join(access_thread, NULL);
	if (rc != 0)
		handle_error("pthread_join");

	return 0;
}
