/*
 * DF-2834 fix-validation helper: exercises the per-proc cap arithmetic.
 *  1. fill a fresh process up to the cap (expect ETOOMANYREFS at #65)
 *  2. destroy one vmspace
 *  3. create again -- must succeed (nvmspaces decremented on delete)
 * Unprivileged; requires vm.vkernel_enable=1.
 */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>

int
main(void)
{
	long i, r;

	printf("uid=%d\n", getuid());
	for (i = 0; i < 1000; ++i) {
		errno = 0;
		r = syscall(SYS_vmspace_create,
		    (void *)(0x20000000UL + (unsigned long)i), 0, NULL);
		if (r != 0) {
			printf("create #%ld -> rc=%ld errno=%d (%s)  [cap hit]\n",
			    i + 1, r, errno, strerror(errno));
			break;
		}
	}
	errno = 0;
	r = syscall(SYS_vmspace_destroy, (void *)0x20000000UL);
	printf("destroy(id=0x20000000) -> rc=%ld errno=%d\n", r, errno);
	errno = 0;
	r = syscall(SYS_vmspace_create, (void *)0x30000000UL, 0, NULL);
	printf("create after destroy     -> rc=%ld errno=%d (%s)  [want 0: slot freed]\n",
	    r, errno, errno ? strerror(errno) : "OK");
	return (0);
}
