/*
 * race_clients.c -- unprivileged trigger for the drm_clients_info race
 * (models any local user reading hw.dri.0.clients while DRM clients
 * open/close the device; here the churn thread inside the harness models
 * the opens/closes).
 *
 * build:  cc -O2 -Wall -o race_clients race_clients.c
 * run:    ./race_clients <rounds>
 */
#include <sys/types.h>
#include <sys/sysctl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(int argc, char **argv)
{
	char buf[2048];
	size_t len;
	int rounds = (argc > 1) ? atoi(argv[1]) : 100000;
	int r, ok = 0, fail = 0;

	for (r = 0; r < rounds; r++) {
		len = sizeof(buf);
		if (sysctlbyname("hw.clirace.clients", buf, &len,
				 NULL, 0) != 0) {
			if (++fail <= 3)
				fprintf(stderr, "round %d: %s\n", r,
					strerror(errno));
			if (errno != ENOENT)
				continue;
			return 1;
		}
		ok++;
	}
	printf("race_clients: %d/%d passes as uid=%d\n", ok, rounds,
	    getuid());

	len = sizeof(buf);
	if (sysctlbyname("hw.clirace.status", buf, &len, NULL, 0) == 0) {
		if (len >= sizeof(buf))
			len = sizeof(buf) - 1;
		buf[len] = 0;
		printf("%s", buf);
	}
	return 0;
}
