read() data corruption with CONFIG_READ_ONLY_THP_FOR_FS=y

From: Vlastimil Babka
Date: Wed Feb 23 2022 - 08:54:49 EST


Hi,

we have found a bug involving CONFIG_READ_ONLY_THP_FOR_FS=y, introduced in
5.12 by cbd59c48ae2b ("mm/filemap: use head pages in
generic_file_buffered_read")
and apparently fixed in 5.17-rc1 by 6b24ca4a1a8d ("mm: Use multi-index
entries in the page cache")
The latter commit is part of folio rework so likely not stable material, so
it would be nice to have a small fix for e.g. 5.15 LTS. Preferably from
someone who understands xarray :)

The bug was found while building nodejs16, which involves running some
tests, first with a non-stripped node16 binary, and then stripping it. This
has a good chance of the stripped result becoming corrupted and not
executable anymore due to dynamic loader failures. It turns out that while
executed during tests, CONFIG_READ_ONLY_THP_FOR_FS=y allows khugepaged to
collapse the large executable mappings. Then /usr/bin/strip uses read() to
process the binary and triggers a bug introduced in cbd59c48ae2b where if a
read spans two or more collapsed THPs in the page cache, the first one will
be read multiple times instead.

Takashi Iwai has bisected using the nodejs build scenario to commit
cbd59c48ae2b.

I have distilled the scenario to the attached reproducer. There are some
assumptions for it to work:

- the passed path for file it creates/works with should be on a filesystem
such as xfs or ext4 that uses generic_file_buffered_read()
- the kernel should have e6be37b2e7bd ("mm/huge_memory.c: add missing
read-only THP checking in transparent_hugepage_enabled()") otherwise
khugepaged will not recognize the reproducer's mm as thp eligible (it had to
be some other mapping in nodejs that made it still possible to trigger this
during bisect)
- there's a pause to allow khugepaged to do its job, you can increase the
speed as instructed and verify with /proc/pid/smaps and meminfo that the
collapse in page cache has happened
- if the bug is reproduced, the reproducer will complain like this:
mismatch at offset 2097152: read value expected for offset 0 instead of 2097152

I've hacked some printk on top 5.16 (attached debug.patch)
which gives this output:

i=0 page=ffffea0004340000 page_offset=0 uoff=0 bytes=2097152
i=1 page=ffffea0004340000 page_offset=0 uoff=0 bytes=2097152
i=2 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=3 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=4 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=5 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=6 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=7 page=ffffea0004340000 page_offset=0 uoff=0 bytes=0
i=8 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=9 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=10 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=11 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=12 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=13 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0
i=14 page=ffffea0004470000 page_offset=2097152 uoff=0 bytes=0

It seems filemap_get_read_batch() should be returning pages ffffea0004340000
and ffffea0004470000 consecutively in the pvec, but returns the first one 8
times, so it's read twice and then the rest is just skipped over as it's
beyond the requested read size.

I suspect these lines:
xas.xa_index = head->index + thp_nr_pages(head) - 1;
xas.xa_offset = (xas.xa_index >> xas.xa_shift) & XA_CHUNK_MASK;

commit 6b24ca4a1a8d changes those to xas_advance() (introduced one patch
earlier), so some self-contained fix should be possible for prior kernels?
But I don't understand xarray well enough.

My colleagues should be credited for initial analysis of the nodejs build
scenario:

Analyzed-by: Adam Majer <amajer@xxxxxxxx>
Analyzed-by: Dirk Mueller <dmueller@xxxxxxxx>
Bisected-by: Takashi Iwai <tiwai@xxxxxxx>

Thanks,
Vlastimil
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/param.h>

#define PAGE_SIZE (4096)
#define PMD_SIZE (PAGE_SIZE * 512)
#define ULONG_SIZE (sizeof(unsigned long))
#define ULONGS_PER_PAGE ((PAGE_SIZE) / (ULONG_SIZE))
#define MAGIC_VALUE 0xabcd


int write_file(char *name, unsigned long size)
{
unsigned long *buf;
unsigned long i, p;
int fd;
int ret;

buf = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

if (buf == MAP_FAILED) {
printf("mmap failed\n");
exit(1);
}

fd = creat(name, S_IRWXU);
if (fd == -1) {
perror("creat");
exit(1);
}

for (i = 0; i < size / PAGE_SIZE; i++) {
buf[0] = MAGIC_VALUE + i;
ret = write(fd, buf, PAGE_SIZE);
// yeah, sloppy
if (ret != PAGE_SIZE) {
perror("write");
exit(1);
}
}

close(fd);
munmap(buf, PAGE_SIZE);
}

void touch(char * buf, unsigned long start, unsigned long size)
{
volatile char foo;

for (char * ptr = buf + start;
ptr < buf + start + size;
ptr += PAGE_SIZE) {
foo = *ptr;
}
}

void test_read(int fd, off_t off, size_t count, size_t bufsize)
{
char *buf = NULL;
int ret;

buf = mmap(NULL, bufsize, PROT_READ|PROT_WRITE,
MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
if (buf == MAP_FAILED) {
perror("mmap");
exit(1);
}

off = lseek(fd, off, SEEK_SET);
if (off == -1) {
perror("lseek");
exit(1);
}

for (size_t done = 0; done < count; done += bufsize) {
size_t to_read = MIN(bufsize, count - done);
size_t buf_read = 0;

while (to_read > 0) {
ssize_t read_once = read(fd, buf + buf_read, to_read);

if (read_once == -1) {
perror("read");
exit(1);
}
if (read_once == 0) {
printf("EOF while reading\n");
return;
}
to_read -= read_once;
buf_read += read_once;
}

for (size_t pos = 0; pos < buf_read; pos += PMD_SIZE) {
unsigned long abs_pos = off + done + pos;
unsigned long found_val = *((unsigned long *)(buf + pos)) - MAGIC_VALUE;
unsigned long expected_val = abs_pos / PAGE_SIZE;

if (found_val != expected_val) {
printf("mismatch at offset %llu: read value expected for offset %llu instead of %llu\n",
abs_pos, found_val * PAGE_SIZE, expected_val * PAGE_SIZE);
}
}
}

munmap(buf, bufsize);
}

#define MAP_SIZE (2*PMD_SIZE)

int main(int argc, char **argv)
{
int fd, ret;
unsigned char *buf;
pid_t pid;

if (argc != 2) {
printf("usage: %s /path/to/test_file\n", argv[0]);
printf("use a filesystem using generic_file_read_iter() such as ext3 or xfs\n");
exit(1);
}

write_file(argv[1], MAP_SIZE);

fd = open(argv[1], O_RDONLY);

if (fd == -1) {
perror("open");
exit(1);
}

buf = mmap((void *)0x700000000000UL, MAP_SIZE, PROT_READ|PROT_EXEC,
MAP_PRIVATE, fd, 0);

if (buf == MAP_FAILED) {
perror("mmap failed");
exit(1);
}

ret = madvise(buf, MAP_SIZE, MADV_HUGEPAGE);

if (ret)
perror("madvise");

touch(buf, 0, MAP_SIZE);

printf("pid: %d\n", getpid());

printf("press enter to continue after khugepaged has collapsed the huge pages\n");
printf("check /proc/meminfo FileHugePages: to verify\n");
printf("use 'echo 100 > /sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs' to speed khugepaged up\n");

getchar();

touch(buf, 0, MAP_SIZE);

ret = munmap(buf, MAP_SIZE);
if (ret) {
perror("munmap");
exit(1);
}

ret = close(fd);
if (ret) {
perror("close");
exit(1);
}

fd = open(argv[1], O_RDONLY);

if (fd == -1) {
perror("open");
exit(1);
}

test_read(fd, 0, MAP_SIZE, MAP_SIZE);

close(fd);
}
diff --git a/mm/filemap.c b/mm/filemap.c
index 39c4c46c6133..ce39c15e8379 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -2682,6 +2682,11 @@ ssize_t filemap_read(struct kiocb *iocb, struct iov_iter *iter,
break;
if (i > 0)
mark_page_accessed(page);
+
+ if (page_size > PAGE_SIZE)
+ pr_info("i=%d page=%px page_offset=%lld off=%lu bytes=%lu\n",
+ i, page, page_offset(page), offset, bytes);
+
/*
* If users can be writing to this page using arbitrary
* virtual addresses, take care about potential aliasing