/* DF-3092: append exactly <nbytes> to a file in ONE write(2).
 * Used to probe the fillinusemap()/chainlength() tail behavior:
 *   - append 3584 (7 clusters) : finding claims phantom clusters 4110.. get
 *     allocated (panic on INVARIANTS, out-of-volume data clusters here)
 *   - append 3072 (6 clusters) : the real free tail 4104..4109
 *   - append 512  after that   : must ENOSPC if phantom bits are marked used
 * build: cc -O -o trigger trigger.c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>

int
main(int argc, char **argv)
{
	unsigned long nbyte;
	char *buf;
	ssize_t n;
	int fd;

	if (argc != 3) {
		fprintf(stderr, "usage: %s file nbytes\n", argv[0]);
		return (1);
	}
	nbyte = strtoul(argv[2], NULL, 0);
	if (nbyte == 0 || nbyte > 64 * 1024 * 1024) {
		fprintf(stderr, "bad nbytes\n");
		return (1);
	}
	fd = open(argv[1], O_WRONLY | O_APPEND);
	if (fd < 0) { perror("open"); return (1); }
	buf = malloc(nbyte);
	memset(buf, 'Z', nbyte);
	n = write(fd, buf, nbyte);
	printf("write(%lu) returned %zd", nbyte, n);
	if (n < 0)
		printf(" errno=%d (%s)", errno, strerror(errno));
	printf("\n");
	free(buf);
	close(fd);
	return (0);
}
