Re: [patch] call truncate_inode_pages in the DIO fallback to buffered I/O path

Jeff Moyer
2006-10-04T21:22:59Z

==> Regarding Re: [patch] call truncate_inode_pages in the DIO fallback to buffered I/O path; Jeff Moyer <jmoyer@redhat.com> adds:
jmoyer> Again, sorry that I didn't include a better description. I've
jmoyer> attached my reproducer to this message.

Oops, forgot to attach it.

-Jeff

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int
make_sparse(const char *filename, off_t len)
{
int fd;

fd = open(filename, O_WRONLY | O_CREAT, 0644);
if (fd < 0) {
perror("open");
return -1;
}

if (ftruncate(fd, 0) != 0) {
perror("ftruncate");
return -1;
}
if (ftruncate(fd, len) != 0) {
perror("ftruncate");
return -1;
}

close(fd);
return 0;
}

int
main(int argc, char **argv)
{
int fd, i, nr_pages, ret;
off_t len;
int page_size = getpagesize();
char *buf;
char *pattern;

if (argc < 3) {
printf("Usage: %s <filename> <size-in-megabytes>\n", argv[0]);
exit(1);
}

/* convert length to megabytes */
len = strtoul(argv[2], NULL, 10);
len <<= 20;

if (make_sparse(argv[1], len) < 0)
exit(4);

nr_pages = len / page_size;

if ((ret = posix_memalign((void **)&buf, 1024, page_size)) != 0) {
errno = ret;
perror("posix_memalign");
exit(2);
}

fd = open(argv[1], O_WRONLY | O_CREAT | O_DIRECT);
if (fd < 0) {
perror("open");
exit(3);
}

memset(buf, 'b', page_size);
for (i = 0; i < nr_pages; i++) {
ret = write(fd, buf, page_size);
if (ret < 0) {
perror("write");
exit(5);
}
}
close(fd);

/* now read the data back in and make sure it hit the disk! */
pattern = malloc(page_size);
if (!pattern) {
perror("malloc");
exit(1);
}
memset(pattern, 'b', page_size);

fd = open(argv[1], O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}

while (i < len) {
memset(buf, 0, sizeof(buf));
ret = read(fd, buf, page_size);
if (ret != page_size) {
if (ret < 0)
perror("read");
else
fprintf(stderr, "short read of %d\n", ret);
exit(1);
}
if (memcmp(buf, pattern, page_size)) {
fprintf(stderr, "Invalid Data!\n");
exit(1);
}
i += page_size;
}

exit(0);
}