| 0/0 |
2026/08/04 00:56 |
flow |
assessment-security |
43m
Results: map[DenialOfService:true Explanation:**Bug Analysis:**
The bug report describes a deadlock (hung tasks) involving two threads. The
lockdep output and stack traces reveal a classic ABBA lock inversion between the
`filemap_invalidate_lock` and the `folio_lock` (page lock).
1. **Thread 1 (Filesystem operation, e.g., `ext4_truncate_failed_write` or
`fallocate`)**:
Filesystem operations that truncate a file or punch a hole (like
`fallocate(PUNCH_HOLE)`) must serialize against page faults and other
operations. They do this by first acquiring the `filemap_invalidate_lock`
exclusively. Then, they iterate over the affected folios in the page cache
and acquire the `folio_lock` for each one (e.g., inside
`truncate_inode_pages_range()`).
*Lock order: `filemap_invalidate_lock` -> `folio_lock`*
2. **Thread 2 (`MADV_COLLAPSE` or `khugepaged` background thread)**:
When collapsing file-backed pages into a Transparent Huge Page (THP),
`collapse_file()` in `mm/khugepaged.c` iterates over the PMD-sized range,
locking folios one by one and adding them to a local list (`pagelist`). If it
encounters a missing folio (a hole), it attempts to read it in by calling
`page_cache_sync_readahead()`.
To protect against concurrent truncation during readahead, the readahead code
(`page_cache_ra_order()` or `do_page_cache_ra()`) acquires the
`filemap_invalidate_lock` in shared mode.
*Lock order: `folio_lock` (held from previous iterations) ->
`filemap_invalidate_lock`*
**The Deadlock:**
If Thread 2 successfully locks a folio at index `N` and then finds that the
folio at index `N+1` is missing, it will call into the readahead code and block
trying to acquire `filemap_invalidate_lock_shared` (because Thread 1 holds it
exclusively). Meanwhile, Thread 1 is trying to truncate the file and blocks
trying to acquire the `folio_lock` for the folio at index `N` (which is held by
Thread 2). Both threads wait on each other indefinitely.
**Security Impact:**
* **Exploitable:** No. This is a pure concurrency logic bug (deadlock). It does
not cause memory corruption, use-after-free, or out-of-bounds accesses, and
therefore cannot be exploited for privilege escalation or information leaks.
* **Denial of Service (DoS):** Yes. An unprivileged local user can easily
trigger this deadlock by mapping a file, calling `madvise(..., MADV_COLLAPSE)`
on the mapping, and concurrently calling `fallocate(..., FALLOC_FL_PUNCH_HOLE,
...)` on the same file.
This will permanently hang the user's tasks. More importantly, if the background
`khugepaged` kernel thread scans the file while it is being truncated,
`khugepaged` itself will deadlock, permanently breaking THP collapsing for the
entire system. Furthermore, on production systems where `kernel.hung_task_panic
= 1` is configured, this deadlock will reliably trigger a kernel panic and crash
the system.
* **Accessible From Unprivileged Processes / User Namespaces:** Yes. The
`madvise(MADV_COLLAPSE)` and `fallocate()` system calls are available to
unprivileged users and do not require any special capabilities. Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:true UserNamespace:true VMGuestTrigger:false VMHostTrigger:false]
|
| 1/1 |
2026/08/04 00:56 |
action |
syz-repro-to-c-repro |
0m
Results: map[SimplifiedCRepro:// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <setjmp.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/loop.h>
#ifndef __NR_madvise
#define __NR_madvise 233
#endif
#ifndef __NR_memfd_create
#define __NR_memfd_create 279
#endif
#ifndef __NR_mmap
#define __NR_mmap 222
#endif
#ifndef __NR_openat
#define __NR_openat 56
#endif
#ifndef __NR_write
#define __NR_write 64
#endif
static unsigned long long procid;
//% This code is derived from puff.{c,h}, found in the zlib development. The
//% original files come with the following copyright notice:
//% Copyright (C) 2002-2013 Mark Adler, all rights reserved
//% version 2.3, 21 Jan 2013
//% This software is provided 'as-is', without any express or implied
//% warranty. In no event will the author be held liable for any damages
//% arising from the use of this software.
//% Permission is granted to anyone to use this software for any purpose,
//% including commercial applications, and to alter it and redistribute it
//% freely, subject to the following restrictions:
//% 1. The origin of this software must not be misrepresented; you must not
//% claim that you wrote the original software. If you use this software
//% in a product, an acknowledgment in the product documentation would be
//% appreciated but is not required.
//% 2. Altered source versions must be plainly marked as such, and must not be
//% misrepresented as being the original software.
//% 3. This notice may not be removed or altered from any source distribution.
//% Mark Adler madler@alumni.caltech.edu
//% BEGIN CODE DERIVED FROM puff.{c,h}
#define MAXBITS 15
#define MAXLCODES 286
#define MAXDCODES 30
#define MAXCODES (MAXLCODES + MAXDCODES)
#define FIXLCODES 288
struct puff_state {
unsigned char* out;
unsigned long outlen;
unsigned long outcnt;
const unsigned char* in;
unsigned long inlen;
unsigned long incnt;
int bitbuf;
int bitcnt;
jmp_buf env;
};
static int puff_bits(struct puff_state* s, int need)
{
long val = s->bitbuf;
while (s->bitcnt < need) {
if (s->incnt == s->inlen)
longjmp(s->env, 1);
val |= (long)(s->in[s->incnt++]) << s->bitcnt;
s->bitcnt += 8;
}
s->bitbuf = (int)(val >> need);
s->bitcnt -= need;
return (int)(val & ((1L << need) - 1));
}
static int puff_stored(struct puff_state* s)
{
s->bitbuf = 0;
s->bitcnt = 0;
if (s->incnt + 4 > s->inlen)
return 2;
unsigned len = s->in[s->incnt++];
len |= s->in[s->incnt++] << 8;
if (s->in[s->incnt++] != (~len & 0xff) ||
s->in[s->incnt++] != ((~len >> 8) & 0xff))
return -2;
if (s->incnt + len > s->inlen)
return 2;
if (s->outcnt + len > s->outlen)
return 1;
for (; len--; s->outcnt++, s->incnt++) {
if (s->in[s->incnt])
s->out[s->outcnt] = s->in[s->incnt];
}
return 0;
}
struct puff_huffman {
short* count;
short* symbol;
};
static int puff_decode(struct puff_state* s, const struct puff_huffman* h)
{
int first = 0;
int index = 0;
int bitbuf = s->bitbuf;
int left = s->bitcnt;
int code = first = index = 0;
int len = 1;
short* next = h->count + 1;
while (1) {
while (left--) {
code |= bitbuf & 1;
bitbuf >>= 1;
int count = *next++;
if (code - count < first) {
s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)];
}
index += count;
first += count;
first <<= 1;
code <<= 1;
len++;
}
left = (MAXBITS + 1) - len;
if (left == 0)
break;
if (s->incnt == s->inlen)
longjmp(s->env, 1);
bitbuf = s->in[s->incnt++];
if (left > 8)
left = 8;
}
return -10;
}
static int puff_construct(struct puff_huffman* h, const short* length, int n)
{
int len;
for (len = 0; len <= MAXBITS; len++)
h->count[len] = 0;
int symbol;
for (symbol = 0; symbol < n; symbol++)
(h->count[length[symbol]])++;
if (h->count[0] == n)
return 0;
int left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= h->count[len];
if (left < 0)
return left;
}
short offs[MAXBITS + 1];
offs[1] = 0;
for (len = 1; len < MAXBITS; len++)
offs[len + 1] = offs[len] + h->count[len];
for (symbol = 0; symbol < n; symbol++)
if (length[symbol] != 0)
h->symbol[offs[length[symbol]]++] = symbol;
return left;
}
static int puff_codes(struct puff_state* s,
const struct puff_huffman* lencode,
const struct puff_huffman* distcode)
{
static const short lens[29] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
static const short lext[29] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
static const short dists[30] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
static const short dext[30] = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
int symbol;
do {
symbol = puff_decode(s, lencode);
if (symbol < 0)
return symbol;
if (symbol < 256) {
if (s->outcnt == s->outlen)
return 1;
if (symbol)
s->out[s->outcnt] = symbol;
s->outcnt++;
} else if (symbol > 256) {
symbol -= 257;
if (symbol >= 29)
return -10;
int len = lens[symbol] + puff_bits(s, lext[symbol]);
symbol = puff_decode(s, distcode);
if (symbol < 0)
return symbol;
unsigned dist = dists[symbol] + puff_bits(s, dext[symbol]);
if (dist > s->outcnt)
return -11;
if (s->outcnt + len > s->outlen)
return 1;
while (len--) {
if (dist <= s->outcnt && s->out[s->outcnt - dist])
s->out[s->outcnt] = s->out[s->outcnt - dist];
s->outcnt++;
}
}
} while (symbol != 256);
return 0;
}
static int puff_fixed(struct puff_state* s)
{
static int virgin = 1;
static short lencnt[MAXBITS + 1], lensym[FIXLCODES];
static short distcnt[MAXBITS + 1], distsym[MAXDCODES];
static struct puff_huffman lencode, distcode;
if (virgin) {
lencode.count = lencnt;
lencode.symbol = lensym;
distcode.count = distcnt;
distcode.symbol = distsym;
short lengths[FIXLCODES];
int symbol;
for (symbol = 0; symbol < 144; symbol++)
lengths[symbol] = 8;
for (; symbol < 256; symbol++)
lengths[symbol] = 9;
for (; symbol < 280; symbol++)
lengths[symbol] = 7;
for (; symbol < FIXLCODES; symbol++)
lengths[symbol] = 8;
puff_construct(&lencode, lengths, FIXLCODES);
for (symbol = 0; symbol < MAXDCODES; symbol++)
lengths[symbol] = 5;
puff_construct(&distcode, lengths, MAXDCODES);
virgin = 0;
}
return puff_codes(s, &lencode, &distcode);
}
static int puff_dynamic(struct puff_state* s)
{
static const short order[19] =
{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
int nlen = puff_bits(s, 5) + 257;
int ndist = puff_bits(s, 5) + 1;
int ncode = puff_bits(s, 4) + 4;
if (nlen > MAXLCODES || ndist > MAXDCODES)
return -3;
short lengths[MAXCODES];
int index;
for (index = 0; index < ncode; index++)
lengths[order[index]] = puff_bits(s, 3);
for (; index < 19; index++)
lengths[order[index]] = 0;
short lencnt[MAXBITS + 1], lensym[MAXLCODES];
struct puff_huffman lencode = {lencnt, lensym};
int err = puff_construct(&lencode, lengths, 19);
if (err != 0)
return -4;
index = 0;
while (index < nlen + ndist) {
int symbol;
int len;
symbol = puff_decode(s, &lencode);
if (symbol < 0)
return symbol;
if (symbol < 16)
lengths[index++] = symbol;
else {
len = 0;
if (symbol == 16) {
if (index == 0)
return -5;
len = lengths[index - 1];
symbol = 3 + puff_bits(s, 2);
} else if (symbol == 17)
symbol = 3 + puff_bits(s, 3);
else
symbol = 11 + puff_bits(s, 7);
if (index + symbol > nlen + ndist)
return -6;
while (symbol--)
lengths[index++] = len;
}
}
if (lengths[256] == 0)
return -9;
err = puff_construct(&lencode, lengths, nlen);
if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
return -7;
short distcnt[MAXBITS + 1], distsym[MAXDCODES];
struct puff_huffman distcode = {distcnt, distsym};
err = puff_construct(&distcode, lengths + nlen, ndist);
if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
return -8;
return puff_codes(s, &lencode, &distcode);
}
static int puff(
unsigned char* dest,
unsigned long* destlen,
const unsigned char* source,
unsigned long sourcelen)
{
struct puff_state s = {
.out = dest,
.outlen = *destlen,
.outcnt = 0,
.in = source,
.inlen = sourcelen,
.incnt = 0,
.bitbuf = 0,
.bitcnt = 0,
};
int err;
if (setjmp(s.env) != 0)
err = 2;
else {
int last;
do {
last = puff_bits(&s, 1);
int type = puff_bits(&s, 2);
err = type == 0 ? puff_stored(&s) : (type == 1 ? puff_fixed(&s) : (type == 2 ? puff_dynamic(&s) : -1));
if (err != 0)
break;
} while (!last);
}
*destlen = s.outcnt;
return err;
}
//% END CODE DERIVED FROM puff.{c,h}
#define ZLIB_HEADER_WIDTH 2
static int puff_zlib_to_file(const unsigned char* source, unsigned long sourcelen, int dest_fd)
{
if (sourcelen < ZLIB_HEADER_WIDTH)
return 0;
source += ZLIB_HEADER_WIDTH;
sourcelen -= ZLIB_HEADER_WIDTH;
const unsigned long max_destlen = 132 << 20;
void* ret = mmap(0, max_destlen, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);
if (ret == MAP_FAILED)
return -1;
unsigned char* dest = (unsigned char*)ret;
unsigned long destlen = max_destlen;
int err = puff(dest, &destlen, source, sourcelen);
if (err) {
munmap(dest, max_destlen);
errno = -err;
return -1;
}
if (write(dest_fd, dest, destlen) != (ssize_t)destlen) {
munmap(dest, max_destlen);
return -1;
}
return munmap(dest, max_destlen);
}
static int setup_loop_device(unsigned char* data, unsigned long size, const char* loopname, int* loopfd_p)
{
int err = 0, loopfd = -1;
int memfd = syscall(__NR_memfd_create, "syzkaller", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (puff_zlib_to_file(data, size, memfd)) {
err = errno;
goto error_close_memfd;
}
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
close(memfd);
*loopfd_p = loopfd;
return 0;
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return -1;
}
static void reset_loop_device(const char* loopname)
{
int loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
return;
}
if (ioctl(loopfd, LOOP_CLR_FD, 0)) {
}
close(loopfd);
}
static long syz_mount_image(
volatile long fsarg,
volatile long dir,
volatile long flags,
volatile long optsarg,
volatile long change_dir,
volatile unsigned long size,
volatile long image)
{
unsigned char* data = (unsigned char*)image;
int res = -1, err = 0, need_loop_device = !!size;
char* mount_opts = (char*)optsarg;
char* target = (char*)dir;
char* fs = (char*)fsarg;
char* source = NULL;
char loopname[64];
if (need_loop_device) {
int loopfd;
memset(loopname, 0, sizeof(loopname));
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
if (setup_loop_device(data, size, loopname, &loopfd) == -1)
return -1;
close(loopfd);
source = loopname;
}
mkdir(target, 0777);
char opts[256];
memset(opts, 0, sizeof(opts));
if (strlen(mount_opts) > (sizeof(opts) - 32)) {
}
strncpy(opts, mount_opts, sizeof(opts) - 32);
if (strcmp(fs, "iso9660") == 0) {
flags |= MS_RDONLY;
} else if (strncmp(fs, "ext", 3) == 0) {
bool has_remount_ro = false;
char* remount_ro_start = strstr(opts, "errors=remount-ro");
if (remount_ro_start != NULL) {
char after = *(remount_ro_start + strlen("errors=remount-ro"));
char before = remount_ro_start == opts ? '\0' : *(remount_ro_start - 1);
has_remount_ro = ((before == '\0' || before == ',') && (after == '\0' || after == ','));
}
if (strstr(opts, "errors=panic") || !has_remount_ro)
strcat(opts, ",errors=continue");
} else if (strcmp(fs, "xfs") == 0) {
strcat(opts, ",nouuid");
} else if (strncmp(fs, "gfs2", 4) == 0 && (strstr(opts, "errors=panic") || strstr(opts, "debug"))) {
strcat(opts, ",errors=withdraw");
}
res = mount(source, target, fs, flags, opts);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
res = open(target, O_RDONLY | O_DIRECTORY);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
if (change_dir) {
res = chdir(target);
if (res == -1) {
err = errno;
}
}
error_clear_loop:
if (need_loop_device)
reset_loop_device(loopname);
errno = err;
return res;
}
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x21000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// syz_mount_image$ext4 arguments: [
// fs: ptr[in, buffer] {
// buffer: {65 78 74 34 00} (length 0x5)
// }
// dir: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// flags: mount_flags = 0x210008 (8 bytes)
// opts: ptr[in, fs_options[ext4_options]] {
// fs_options[ext4_options] {
// elems: array[fs_opt_elem[ext4_options]] {
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nodelalloc: buffer: {6e 6f 64 65 6c 61 6c 6c 6f 63} (length 0xa)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// dioread_lock: buffer: {64 69 6f 72 65 61 64 5f 6c 6f 63 6b} (length 0xc)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// barrier_val: fs_opt["barrier", fmt[hex, int32]] {
// name: buffer: {62 61 72 72 69 65 72} (length 0x7)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x4 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nolazytime: buffer: {6e 6f 6c 61 7a 79 74 69 6d 65} (length 0xa)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// debug_want_extra_isize: fs_opt["debug_want_extra_isize", fmt[hex, int32]] {
// name: buffer: {64 65 62 75 67 5f 77 61 6e 74 5f 65 78 74 72 61 5f 69 73 69 7a 65} (length 0x16)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x80 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// lazytime: buffer: {6c 61 7a 79 74 69 6d 65} (length 0x8)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// errors_remount: buffer: {65 72 72 6f 72 73 3d 72 65 6d 6f 75 6e 74 2d 72 6f} (length 0x11)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// stripe: fs_opt["stripe", fmt[hex, int32]] {
// name: buffer: {73 74 72 69 70 65} (length 0x6)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x5 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// bh: buffer: {62 68} (length 0x2)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nodiscard: buffer: {6e 6f 64 69 73 63 61 72 64} (length 0x9)
// }
// comma: const = 0x2c (1 bytes)
// }
// }
// common: array[fs_opt_elem[fs_options_common]] {
// }
// null: const = 0x0 (1 bytes)
// }
// }
// chdir: int8 = 0xfc (1 bytes)
// size: len = 0x56f (8 bytes)
// img: ptr[in, buffer] {
// buffer: (compressed buffer with length 0x56f)
// }
// ]
// returns fd_dir
memcpy((void*)0x200001c0, "ext4\000", 5);
memcpy((void*)0x20000340, "./file1\000", 8);
memcpy((void*)0x20000000, "nodelalloc", 10);
*(uint8_t*)0x2000000a = 0x2c;
memcpy((void*)0x2000000b, "dioread_lock", 12);
*(uint8_t*)0x20000017 = 0x2c;
memcpy((void*)0x20000018, "barrier", 7);
*(uint8_t*)0x2000001f = 0x3d;
sprintf((char*)0x20000020, "0x%016llx", (long long)4);
*(uint8_t*)0x20000032 = 0x2c;
memcpy((void*)0x20000033, "nolazytime", 10);
*(uint8_t*)0x2000003d = 0x2c;
memcpy((void*)0x2000003e, "debug_want_extra_isize", 22);
*(uint8_t*)0x20000054 = 0x3d;
sprintf((char*)0x20000055, "0x%016llx", (long long)0x80);
*(uint8_t*)0x20000067 = 0x2c;
memcpy((void*)0x20000068, "lazytime", 8);
*(uint8_t*)0x20000070 = 0x2c;
memcpy((void*)0x20000071, "errors=remount-ro", 17);
*(uint8_t*)0x20000082 = 0x2c;
memcpy((void*)0x20000083, "stripe", 6);
*(uint8_t*)0x20000089 = 0x3d;
sprintf((char*)0x2000008a, "0x%016llx", (long long)5);
*(uint8_t*)0x2000009c = 0x2c;
memcpy((void*)0x2000009d, "bh", 2);
*(uint8_t*)0x2000009f = 0x2c;
memcpy((void*)0x200000a0, "nodiscard", 9);
*(uint8_t*)0x200000a9 = 0x2c;
*(uint8_t*)0x200000aa = 0;
memcpy((void*)0x20003780, "... [truncated large byte array] ...", 1391);
syz_mount_image(/*fs=*/0x200001c0, /*dir=*/0x20000340, /*flags=MS_POSIXACL|MS_RELATIME|MS_NOEXEC*/0x210008, /*opts=*/0x20000000, /*chdir=*/0xfc, /*size=*/0x56f, /*img=*/0x20003780);
// openat$cgroup_ro arguments: [
// fd: fd_cgroup (resource)
// file: ptr[in, buffer] {
// buffer: {63 67 72 6f 75 70 2e 63 6f 6e 74 72 6f 6c 6c 65 72 73 00} (length 0x13)
// }
// flags: const = 0x275a (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x200001c0, "cgroup.controllers\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x200001c0ul, /*flags=*/0x275a, /*mode=*/0);
if (res != -1)
r[0] = res;
// openat$cgroup_ro arguments: [
// fd: fd_cgroup (resource)
// file: ptr[in, buffer] {
// buffer: {63 67 72 6f 75 70 2e 63 6f 6e 74 72 6f 6c 6c 65 72 73 00} (length 0x13)
// }
// flags: const = 0x275a (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x20000080, "cgroup.controllers\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x20000080ul, /*flags=*/0x275a, /*mode=*/0);
if (res != -1)
r[1] = res;
// write$binfmt_script arguments: [
// fd: fd_binfmt (resource)
// data: ptr[in, binfmt_script] {
// binfmt_script {
// hdr: buffer: {23 21 20} (length 0x3)
// bin: buffer: {} (length 0x0)
// args: array[binfmt_script_arg] {
// }
// nl: const = 0xa (1 bytes)
// data: buffer: {} (length 0x0)
// }
// }
// len: bytesize = 0xfea7 (8 bytes)
// ]
memcpy((void*)0x20000180, "#! ", 3);
*(uint8_t*)0x20000183 = 0xa;
syscall(__NR_write, /*fd=*/r[1], /*data=*/0x20000180ul, /*len=*/0xfea7ul);
// mmap arguments: [
// addr: VMA[0xb36000]
// len: len = 0xb36000 (4 bytes)
// prot: mmap_prot = 0x2 (8 bytes)
// flags: mmap_flags = 0x28011 (8 bytes)
// fd: fd (resource)
// offset: intptr = 0x0 (8 bytes)
// ]
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0xb36000, /*prot=PROT_WRITE*/2ul, /*flags=MAP_STACK|MAP_POPULATE|MAP_FIXED|MAP_SHARED*/0x28011ul, /*fd=*/r[0], /*offset=*/0ul);
// madvise arguments: [
// addr: VMA[0x800000]
// len: len = 0x800000 (8 bytes)
// advice: madvise_flags = 0xe (8 bytes)
// ]
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x800000ul, /*advice=MADV_HUGEPAGE*/0xeul);
// madvise arguments: [
// addr: VMA[0x600000]
// len: len = 0x600000 (8 bytes)
// advice: madvise_flags = 0x19 (8 bytes)
// ]
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x600000ul, /*advice=MADV_COLLAPSE*/0x19ul);
return 0;
}
]
|
| 2/1 |
2026/08/04 00:56 |
action |
kernel-checkouter |
1m
Results: map[KernelSrc:/app/workdir/cache/src/db7afdf0237c4efa4b5b2e085a1a558c7d763c3c]
|
| 3/1 |
2026/08/04 00:57 |
action |
kernel-builder |
17m
Results: map[KernelObj:/app/workdir/cache/build/e762d2e50cd15f72aa765e253c7c0b12064fd0dc]
|
| 4/1 |
2026/08/04 01:15 |
action |
codesearch-prepare |
12m
Results: map[Index:codesearch-index]
|
| 5/1 |
2026/08/04 01:28 |
agent |
expert |
11m
Model:
Results: map[DenialOfService:true Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:true UserNamespace:true VMGuestTrigger:false VMHostTrigger:false]
Instruction: You are an experienced Linux kernel security engineer. Your task is to analyze given kernel bug report
and determine its security impact based on the following dimensions.
Use the provided tools to examine the source code, check for capability checks (e.g., capable(), ns_capable()),
and understand the nature of the bug. Analyze the given kernel build and configuration.
You can check the kernel config by grepping ".config" file; you can check kernel cmdline by grepping
".config" file for "CONFIG_CMDLINE=". Assume sysctl parameters have default values.
But analyze for the corresponding production build w/o debugging tools enabled (like KASAN, KMSAN, UBSAN).
Try different strategies when analyzing the bug:
- think of ways in which the vulnerable code is unreachable
- or the other way around: try to come up with different ideas of how an unprivileged user can reach the bug
If still unsure err on the side of the bug being non-exploitable/not-accessible.
In the final reply, provide a reasoning for your assessment.
Analysis dimensions:
* Exploitable:
Determine if the bug can result in memory corruption, elevated privileges, or an information leak.
Memory safety issues are almost always exploitable (KASAN or UBSAN reports for use-after-free, out-of-bounds;
refcounting issues, corrupted lists, etc). When kernel is crashing on a completely wild pointer access
(e.g. user-space address, or non-canonical address, but not on NULL or address corresponding to KASAN shadow
for NULL address), including both data accesses and control transfers, that also usually implies possibility
of exploitation. Such reports usually say "unable to handle kernel paging request".
Uses of uninitialized values detected by KMSAN may be exploitable b/c attacker frequently can affect uninit
values with spraying techniques. However, for these exploitability depends on how exactly the uninit value
is used in the code, and what it affects.
Information leaks are exploitable on their own and should be classified as such. A bug that copies kernel
memory contents to userspace (e.g. an out-of-bounds read whose result is returned to the caller, or
uninitialized stack/heap bytes written to a user buffer) is exploitable: it can reveal kernel pointer
values and defeat KASLR, expose sensitive data such as cryptographic keys or other processes' memory, and
serves as a necessary building block in most modern kernel privilege-escalation exploit chains. Do not classify
an information leak as non-exploitable solely because it does not directly cause a memory write or control-flow
hijack; the leak itself is the exploit primitive.
Think of what happens after the bug is triggered. Some bugs cause kernel panic and halt execution,
they are harder to exploit. For example, BUG reports halts the kernel. However, WARNING reports don't halt
execution in production builds. Debug bug detection tools (like KASAN, KMSAN, KCSAN, UBSAN) are also not enabled
in production builds, so attacker can freely exploit these bugs w/o being detected by these tools.
If you see an integer overflow, think how the overflowed value used later (if it's used as allocation size,
or an array index). If you see an out-of-bounds read, think if it's followed by an out-of-bounds write as well.
Some KCSAN data-races may be exploitable by skilled attackers as well. Think what data structures got corrupted
as the result of data races and how. However, note that kernel has lots of "benign" data races that don't lead
to any runtime misbehavior at all.
* Denial Of Service:
Determine if the bug can result in denial-of-service. Most bugs can, since they cause system crash,
hangs, deadlocks, or resource leaks. This is mostly applicable to WARNING bugs that won't cause system crash
in production. For these think what will be consequences of the violation of the kernel assumptions flagged
by the WARNING. In some cases the unexpected condition is also properly handled by the normal control flow
(e.g. with "if (WARN_ON(...))"), these won't cause denial-of-service. If the condition is not handled,
then it may or may not cause denial-of-service.
* Accessible From Unprivileged Processes:
Determine if the bug can be reached from a typical (non-root) user process that does NOT have any special capabilities
(like CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_PERFMON) or access to device nodes restricted to root.
Assume that unprivileged_bpf_disabled=1, that is eBPF loading is not accessible. However, cBPF (classical BPF)
is still accessible to non-root processes.
Assume that user namespaces are not accessible, that is, the process cannot get the mentioned capabilities even
within a new user namespace (checked by ns_capable() function in the kernel sources).
* Accessible From User Namespaces:
Determine if the bug can be reached within a user-namespace where the process has all capabilities
(including CAP_SYS_ADMIN, CAP_NET_ADMIN, CAP_NET_RAW, CAP_PERFMON). Such capabilities are checked with ns_capable()
function in the kernel sources.
* VM Guest Trigger:
Determine if the bug can be triggered from the context of a typical KVM guest (e.g., set up by a QEMU VMM).
Consider accesses to standard Linux host paravirtualized features (virtio-blk, virtio-net, etc.),
and handling of VM exits in the KVM code.
* VM Host Trigger in The Confidential Computing Context:
Determine if the bug can be triggered in a confidential computing guest kernel from the context of a KVM host.
Consider access to standard Linux guest paravirtualized features (virtio-blk, virtio-net, etc.).
* Ethernet Network Trigger:
Determine if the bug can be triggered by processing ingress network Ethernet traffic, either directly (network stack)
or via drivers exposed to network data.
* Other Remote Trigger:
Determine if the bug can be triggered by processing remote traffic other than Ethernet (Wifi, Bluetooth, NFC, etc).
* Peripheral Trigger:
Determine if the bug can be triggered via an untrusted peripheral device that can be physically plugged
into a system, such as a USB device or a niche hardware driver handling external hardware inputs.
This is particularly important for mobile and desktop environments where users can plug in unknown devices.
* Malicious Filesystem Trigger:
Determine if the bug can be triggered by the kernel mounting and parsing a malicious filesystem image.
This is highly critical for Desktop and Mobile environments where external media or downloaded images
might be auto-mounted.
Don't make assumptions about the kernel source code (it may be different from what you assume it is).
Extensively use the provided code access tools (codesearch-*, git-*, grepper, etc)
to examine the actual source code, and confirm any assumptions.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt:
The kernel bug report is:
INFO: task syz.5.7528:29358 blocked in I/O wait for more than 143 seconds.
Not tainted syzkaller #0
"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
task:syz.5.7528 state:D stack:0 pid:29358 tgid:29355 ppid:27464 task_flags:0x400140 flags:0x00000011
Call trace:
__switch_to+0x2b0/0x6e0 arch/arm64/kernel/process.c:775 (T)
context_switch kernel/sched/core.c:5510 [inline]
__schedule+0x1370/0x2d80 kernel/sched/core.c:7234
__schedule_loop kernel/sched/core.c:7311 [inline]
schedule+0x13c/0x20c kernel/sched/core.c:7326
io_schedule+0x1c/0xe0 kernel/sched/core.c:8154
folio_wait_bit_common+0x6b8/0xa30 mm/filemap.c:1323
__folio_lock mm/filemap.c:1704 [inline]
folio_lock include/linux/pagemap.h:1157 [inline]
__filemap_get_folio_mpol+0x1f4/0x1054 mm/filemap.c:1960
__filemap_get_folio include/linux/pagemap.h:761 [inline]
ext4_load_tail_bh+0x94/0x704 fs/ext4/inode.c:4040
ext4_block_do_zero_range fs/ext4/inode.c:4111 [inline]
ext4_block_zero_range+0xd8/0x7b0 fs/ext4/inode.c:4199
ext4_block_zero_eof+0x22c/0x4b8 fs/ext4/inode.c:4229
ext4_truncate+0x500/0x10d4 fs/ext4/inode.c:4632
ext4_truncate_failed_write fs/ext4/truncate.h:22 [inline]
ext4_write_end+0x598/0x9e0 fs/ext4/inode.c:1495
generic_perform_write+0x504/0x7a4 mm/filemap.c:4379
ext4_buffered_write_iter+0xd0/0x2ec fs/ext4/file.c:316
ext4_file_write_iter+0x1dc/0x134c fs/ext4/file.c:-1
new_sync_write fs/read_write.c:595 [inline]
vfs_write+0x51c/0xa0c fs/read_write.c:687
ksys_write+0x12c/0x228 fs/read_write.c:739
__do_sys_write fs/read_write.c:750 [inline]
__se_sys_write fs/read_write.c:747 [inline]
__arm64_sys_write+0x7c/0x90 fs/read_write.c:747
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
INFO: task syz.5.7528:29366 blocked for more than 143 seconds.
Not tainted syzkaller #0
"echo 0 > /proc/sys/kernel/hung_task_timeout_secs" disables this message.
task:syz.5.7528 state:D stack:0 pid:29366 tgid:29355 ppid:27464 task_flags:0x440040 flags:0x00000011
Call trace:
__switch_to+0x2b0/0x6e0 arch/arm64/kernel/process.c:775 (T)
context_switch kernel/sched/core.c:5510 [inline]
__schedule+0x1370/0x2d80 kernel/sched/core.c:7234
__schedule_loop kernel/sched/core.c:7311 [inline]
schedule+0x13c/0x20c kernel/sched/core.c:7326
schedule_preempt_disabled+0x18/0x2c kernel/sched/core.c:7383
rwsem_down_read_slowpath+0x530/0x7b0 kernel/locking/rwsem.c:1114
__down_read_common kernel/locking/rwsem.c:1291 [inline]
__down_read kernel/locking/rwsem.c:1304 [inline]
down_read+0xa0/0x2bc kernel/locking/rwsem.c:1576
filemap_invalidate_lock_shared include/linux/fs.h:1089 [inline]
page_cache_ra_order+0x334/0xe20 mm/readahead.c:517
page_cache_sync_ra+0x66c/0xaf0 mm/readahead.c:649
page_cache_sync_readahead include/linux/pagemap.h:1395 [inline]
collapse_file mm/khugepaged.c:2335 [inline]
collapse_scan_file+0x16fc/0x4834 mm/khugepaged.c:2773
collapse_single_pmd+0x3c0/0x3b78 mm/khugepaged.c:2808
madvise_collapse+0x2a4/0x728 mm/khugepaged.c:3234
madvise_vma_behavior+0x408/0x3390 mm/madvise.c:1364
madvise_walk_vmas+0x4c8/0x9bc mm/madvise.c:1713
madvise_do_behavior+0x5f0/0x7c0 mm/madvise.c:1908
do_madvise+0x28c/0x2f0 mm/madvise.c:2006
__do_sys_madvise mm/madvise.c:2015 [inline]
__se_sys_madvise mm/madvise.c:2013 [inline]
__arm64_sys_madvise+0xa4/0xc0 mm/madvise.c:2013
__invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]
invoke_syscall+0x98/0x244 arch/arm64/kernel/syscall.c:49
el0_svc_common+0xec/0x23c arch/arm64/kernel/syscall.c:121
do_el0_svc+0x4c/0x5c arch/arm64/kernel/syscall.c:140
el0_svc+0x64/0x260 arch/arm64/kernel/entry-common.c:736
el0t_64_sync_handler+0x48/0x148 arch/arm64/kernel/entry-common.c:755
el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:594
Showing all locks held in the system:
2 locks held by kworker/u8:0/12:
1 lock held by khungtaskd/31:
#0: ffff800088cb6f20 (rcu_read_lock){....}-{1:3}, at: rcu_lock_acquire include/linux/rcupdate.h:300 [inline]
#0: ffff800088cb6f20 (rcu_read_lock){....}-{1:3}, at: rcu_read_lock include/linux/rcupdate.h:840 [inline]
#0: ffff800088cb6f20 (rcu_read_lock){....}-{1:3}, at: debug_show_all_locks+0x4c/0x188 kernel/locking/lockdep.c:6775
1 lock held by pr/ttyAMA-1/41:
2 locks held by getty/4492:
#0: ffff0000d159a0a0 (&tty->ldisc_sem){++++}-{0:0}, at: ldsem_down_read+0x3c/0x4c drivers/tty/tty_ldsem.c:340
#1: ffff80009248b2e8 (&ldata->atomic_read_lock){+.+.}-{4:4}, at: n_tty_read+0x348/0xf78 drivers/tty/n_tty.c:2211
3 locks held by udevd/4753:
2 locks held by kworker/0:4/4834:
3 locks held by udevd/5195:
1 lock held by udevd/5459:
2 locks held by udevd/25825:
4 locks held by syz.5.7528/29358:
#0: ffff0000cd7f3b30 (&f->f_pos_lock){+.+.}-{4:4}, at: fdget_pos+0x100/0x144 fs/file.c:1259
#1: ffff0000d54a2450 (sb_writers#3){.+.+}-{0:0}, at: file_start_write include/linux/fs.h:2728 [inline]
#1: ffff0000d54a2450 (sb_writers#3){.+.+}-{0:0}, at: vfs_write+0x248/0xa0c fs/read_write.c:683
#2: ffff0000dfbf9fa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: inode_lock include/linux/fs.h:1024 [inline]
#2: ffff0000dfbf9fa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: ext4_buffered_write_iter+0xa0/0x2ec fs/ext4/file.c:311
#3: ffff0000dfbfa138 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock include/linux/fs.h:1079 [inline]
#3: ffff0000dfbfa138 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_truncate_failed_write fs/ext4/truncate.h:20 [inline]
#3: ffff0000dfbfa138 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_write_end+0x574/0x9e0 fs/ext4/inode.c:1495
1 lock held by syz.5.7528/29366:
#0: ffff0000dfbfa138 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock_shared include/linux/fs.h:1089 [inline]
#0: ffff0000dfbfa138 (mapping.invalidate_lock#2){++++}-{4:4}, at: page_cache_ra_order+0x334/0xe20 mm/readahead.c:517
4 locks held by syz.3.8462/32291:
#0: ffff0000d18440f0 (&f->f_pos_lock){+.+.}-{4:4}, at: fdget_pos+0x100/0x144 fs/file.c:1259
#1: ffff0000ed44a450 (sb_writers#3){.+.+}-{0:0}, at: file_start_write include/linux/fs.h:2728 [inline]
#1: ffff0000ed44a450 (sb_writers#3){.+.+}-{0:0}, at: vfs_write+0x248/0xa0c fs/read_write.c:683
#2: ffff0000efc86aa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: inode_lock include/linux/fs.h:1024 [inline]
#2: ffff0000efc86aa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: ext4_buffered_write_iter+0xa0/0x2ec fs/ext4/file.c:311
#3: ffff0000efc86c38 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock include/linux/fs.h:1079 [inline]
#3: ffff0000efc86c38 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_truncate_failed_write fs/ext4/truncate.h:20 [inline]
#3: ffff0000efc86c38 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_write_end+0x574/0x9e0 fs/ext4/inode.c:1495
1 lock held by syz.3.8462/32302:
#0: ffff0000efc86c38 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock_shared include/linux/fs.h:1089 [inline]
#0: ffff0000efc86c38 (mapping.invalidate_lock#2){++++}-{4:4}, at: page_cache_ra_order+0x334/0xe20 mm/readahead.c:517
4 locks held by syz.7.12097/10967:
#0: ffff0000c98c2630 (&f->f_pos_lock){+.+.}-{4:4}, at: fdget_pos+0x100/0x144 fs/file.c:1259
#1: ffff0000d4d4c450 (sb_writers#3){.+.+}-{0:0}, at: file_start_write include/linux/fs.h:2728 [inline]
#1: ffff0000d4d4c450 (sb_writers#3){.+.+}-{0:0}, at: vfs_write+0x248/0xa0c fs/read_write.c:683
#2: ffff0000dfba1fa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: inode_lock include/linux/fs.h:1024 [inline]
#2: ffff0000dfba1fa0 (&sb->s_type->i_mutex_key#10){++++}-{4:4}, at: ext4_buffered_write_iter+0xa0/0x2ec fs/ext4/file.c:311
#3: ffff0000dfba2138 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock include/linux/fs.h:1079 [inline]
#3: ffff0000dfba2138 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_truncate_failed_write fs/ext4/truncate.h:20 [inline]
#3: ffff0000dfba2138 (mapping.invalidate_lock#2){++++}-{4:4}, at: ext4_write_end+0x574/0x9e0 fs/ext4/inode.c:1495
1 lock held by syz.7.12097/10978:
#0: ffff0000dfba2138 (mapping.invalidate_lock#2){++++}-{4:4}, at: filemap_invalidate_lock_shared include/linux/fs.h:1089 [inline]
#0: ffff0000dfba2138 (mapping.invalidate_lock#2){++++}-{4:4}, at: page_cache_ra_order+0x334/0xe20 mm/readahead.c:517
1 lock held by syz-executor/12531:
1 lock held by syz.2.13521/15260:
1 lock held by syz.1.13518/15265:
=============================================
It is reproducible with the followint program.
Keep in mind that it may lack the precise threading, sandboxing, and some arguments of a working reproducer.
But it should give an idea of the involved syscalls.
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#define _GNU_SOURCE
#include <endian.h>
#include <errno.h>
#include <fcntl.h>
#include <setjmp.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <linux/loop.h>
#ifndef __NR_madvise
#define __NR_madvise 233
#endif
#ifndef __NR_memfd_create
#define __NR_memfd_create 279
#endif
#ifndef __NR_mmap
#define __NR_mmap 222
#endif
#ifndef __NR_openat
#define __NR_openat 56
#endif
#ifndef __NR_write
#define __NR_write 64
#endif
static unsigned long long procid;
//% This code is derived from puff.{c,h}, found in the zlib development. The
//% original files come with the following copyright notice:
//% Copyright (C) 2002-2013 Mark Adler, all rights reserved
//% version 2.3, 21 Jan 2013
//% This software is provided 'as-is', without any express or implied
//% warranty. In no event will the author be held liable for any damages
//% arising from the use of this software.
//% Permission is granted to anyone to use this software for any purpose,
//% including commercial applications, and to alter it and redistribute it
//% freely, subject to the following restrictions:
//% 1. The origin of this software must not be misrepresented; you must not
//% claim that you wrote the original software. If you use this software
//% in a product, an acknowledgment in the product documentation would be
//% appreciated but is not required.
//% 2. Altered source versions must be plainly marked as such, and must not be
//% misrepresented as being the original software.
//% 3. This notice may not be removed or altered from any source distribution.
//% Mark Adler madler@alumni.caltech.edu
//% BEGIN CODE DERIVED FROM puff.{c,h}
#define MAXBITS 15
#define MAXLCODES 286
#define MAXDCODES 30
#define MAXCODES (MAXLCODES + MAXDCODES)
#define FIXLCODES 288
struct puff_state {
unsigned char* out;
unsigned long outlen;
unsigned long outcnt;
const unsigned char* in;
unsigned long inlen;
unsigned long incnt;
int bitbuf;
int bitcnt;
jmp_buf env;
};
static int puff_bits(struct puff_state* s, int need)
{
long val = s->bitbuf;
while (s->bitcnt < need) {
if (s->incnt == s->inlen)
longjmp(s->env, 1);
val |= (long)(s->in[s->incnt++]) << s->bitcnt;
s->bitcnt += 8;
}
s->bitbuf = (int)(val >> need);
s->bitcnt -= need;
return (int)(val & ((1L << need) - 1));
}
static int puff_stored(struct puff_state* s)
{
s->bitbuf = 0;
s->bitcnt = 0;
if (s->incnt + 4 > s->inlen)
return 2;
unsigned len = s->in[s->incnt++];
len |= s->in[s->incnt++] << 8;
if (s->in[s->incnt++] != (~len & 0xff) ||
s->in[s->incnt++] != ((~len >> 8) & 0xff))
return -2;
if (s->incnt + len > s->inlen)
return 2;
if (s->outcnt + len > s->outlen)
return 1;
for (; len--; s->outcnt++, s->incnt++) {
if (s->in[s->incnt])
s->out[s->outcnt] = s->in[s->incnt];
}
return 0;
}
struct puff_huffman {
short* count;
short* symbol;
};
static int puff_decode(struct puff_state* s, const struct puff_huffman* h)
{
int first = 0;
int index = 0;
int bitbuf = s->bitbuf;
int left = s->bitcnt;
int code = first = index = 0;
int len = 1;
short* next = h->count + 1;
while (1) {
while (left--) {
code |= bitbuf & 1;
bitbuf >>= 1;
int count = *next++;
if (code - count < first) {
s->bitbuf = bitbuf;
s->bitcnt = (s->bitcnt - len) & 7;
return h->symbol[index + (code - first)];
}
index += count;
first += count;
first <<= 1;
code <<= 1;
len++;
}
left = (MAXBITS + 1) - len;
if (left == 0)
break;
if (s->incnt == s->inlen)
longjmp(s->env, 1);
bitbuf = s->in[s->incnt++];
if (left > 8)
left = 8;
}
return -10;
}
static int puff_construct(struct puff_huffman* h, const short* length, int n)
{
int len;
for (len = 0; len <= MAXBITS; len++)
h->count[len] = 0;
int symbol;
for (symbol = 0; symbol < n; symbol++)
(h->count[length[symbol]])++;
if (h->count[0] == n)
return 0;
int left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= h->count[len];
if (left < 0)
return left;
}
short offs[MAXBITS + 1];
offs[1] = 0;
for (len = 1; len < MAXBITS; len++)
offs[len + 1] = offs[len] + h->count[len];
for (symbol = 0; symbol < n; symbol++)
if (length[symbol] != 0)
h->symbol[offs[length[symbol]]++] = symbol;
return left;
}
static int puff_codes(struct puff_state* s,
const struct puff_huffman* lencode,
const struct puff_huffman* distcode)
{
static const short lens[29] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
static const short lext[29] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
static const short dists[30] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577};
static const short dext[30] = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13};
int symbol;
do {
symbol = puff_decode(s, lencode);
if (symbol < 0)
return symbol;
if (symbol < 256) {
if (s->outcnt == s->outlen)
return 1;
if (symbol)
s->out[s->outcnt] = symbol;
s->outcnt++;
} else if (symbol > 256) {
symbol -= 257;
if (symbol >= 29)
return -10;
int len = lens[symbol] + puff_bits(s, lext[symbol]);
symbol = puff_decode(s, distcode);
if (symbol < 0)
return symbol;
unsigned dist = dists[symbol] + puff_bits(s, dext[symbol]);
if (dist > s->outcnt)
return -11;
if (s->outcnt + len > s->outlen)
return 1;
while (len--) {
if (dist <= s->outcnt && s->out[s->outcnt - dist])
s->out[s->outcnt] = s->out[s->outcnt - dist];
s->outcnt++;
}
}
} while (symbol != 256);
return 0;
}
static int puff_fixed(struct puff_state* s)
{
static int virgin = 1;
static short lencnt[MAXBITS + 1], lensym[FIXLCODES];
static short distcnt[MAXBITS + 1], distsym[MAXDCODES];
static struct puff_huffman lencode, distcode;
if (virgin) {
lencode.count = lencnt;
lencode.symbol = lensym;
distcode.count = distcnt;
distcode.symbol = distsym;
short lengths[FIXLCODES];
int symbol;
for (symbol = 0; symbol < 144; symbol++)
lengths[symbol] = 8;
for (; symbol < 256; symbol++)
lengths[symbol] = 9;
for (; symbol < 280; symbol++)
lengths[symbol] = 7;
for (; symbol < FIXLCODES; symbol++)
lengths[symbol] = 8;
puff_construct(&lencode, lengths, FIXLCODES);
for (symbol = 0; symbol < MAXDCODES; symbol++)
lengths[symbol] = 5;
puff_construct(&distcode, lengths, MAXDCODES);
virgin = 0;
}
return puff_codes(s, &lencode, &distcode);
}
static int puff_dynamic(struct puff_state* s)
{
static const short order[19] =
{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
int nlen = puff_bits(s, 5) + 257;
int ndist = puff_bits(s, 5) + 1;
int ncode = puff_bits(s, 4) + 4;
if (nlen > MAXLCODES || ndist > MAXDCODES)
return -3;
short lengths[MAXCODES];
int index;
for (index = 0; index < ncode; index++)
lengths[order[index]] = puff_bits(s, 3);
for (; index < 19; index++)
lengths[order[index]] = 0;
short lencnt[MAXBITS + 1], lensym[MAXLCODES];
struct puff_huffman lencode = {lencnt, lensym};
int err = puff_construct(&lencode, lengths, 19);
if (err != 0)
return -4;
index = 0;
while (index < nlen + ndist) {
int symbol;
int len;
symbol = puff_decode(s, &lencode);
if (symbol < 0)
return symbol;
if (symbol < 16)
lengths[index++] = symbol;
else {
len = 0;
if (symbol == 16) {
if (index == 0)
return -5;
len = lengths[index - 1];
symbol = 3 + puff_bits(s, 2);
} else if (symbol == 17)
symbol = 3 + puff_bits(s, 3);
else
symbol = 11 + puff_bits(s, 7);
if (index + symbol > nlen + ndist)
return -6;
while (symbol--)
lengths[index++] = len;
}
}
if (lengths[256] == 0)
return -9;
err = puff_construct(&lencode, lengths, nlen);
if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
return -7;
short distcnt[MAXBITS + 1], distsym[MAXDCODES];
struct puff_huffman distcode = {distcnt, distsym};
err = puff_construct(&distcode, lengths + nlen, ndist);
if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
return -8;
return puff_codes(s, &lencode, &distcode);
}
static int puff(
unsigned char* dest,
unsigned long* destlen,
const unsigned char* source,
unsigned long sourcelen)
{
struct puff_state s = {
.out = dest,
.outlen = *destlen,
.outcnt = 0,
.in = source,
.inlen = sourcelen,
.incnt = 0,
.bitbuf = 0,
.bitcnt = 0,
};
int err;
if (setjmp(s.env) != 0)
err = 2;
else {
int last;
do {
last = puff_bits(&s, 1);
int type = puff_bits(&s, 2);
err = type == 0 ? puff_stored(&s) : (type == 1 ? puff_fixed(&s) : (type == 2 ? puff_dynamic(&s) : -1));
if (err != 0)
break;
} while (!last);
}
*destlen = s.outcnt;
return err;
}
//% END CODE DERIVED FROM puff.{c,h}
#define ZLIB_HEADER_WIDTH 2
static int puff_zlib_to_file(const unsigned char* source, unsigned long sourcelen, int dest_fd)
{
if (sourcelen < ZLIB_HEADER_WIDTH)
return 0;
source += ZLIB_HEADER_WIDTH;
sourcelen -= ZLIB_HEADER_WIDTH;
const unsigned long max_destlen = 132 << 20;
void* ret = mmap(0, max_destlen, PROT_WRITE | PROT_READ, MAP_PRIVATE | MAP_ANON, -1, 0);
if (ret == MAP_FAILED)
return -1;
unsigned char* dest = (unsigned char*)ret;
unsigned long destlen = max_destlen;
int err = puff(dest, &destlen, source, sourcelen);
if (err) {
munmap(dest, max_destlen);
errno = -err;
return -1;
}
if (write(dest_fd, dest, destlen) != (ssize_t)destlen) {
munmap(dest, max_destlen);
return -1;
}
return munmap(dest, max_destlen);
}
static int setup_loop_device(unsigned char* data, unsigned long size, const char* loopname, int* loopfd_p)
{
int err = 0, loopfd = -1;
int memfd = syscall(__NR_memfd_create, "syzkaller", 0);
if (memfd == -1) {
err = errno;
goto error;
}
if (puff_zlib_to_file(data, size, memfd)) {
err = errno;
goto error_close_memfd;
}
loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
err = errno;
goto error_close_memfd;
}
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
if (errno != EBUSY) {
err = errno;
goto error_close_loop;
}
ioctl(loopfd, LOOP_CLR_FD, 0);
usleep(1000);
if (ioctl(loopfd, LOOP_SET_FD, memfd)) {
err = errno;
goto error_close_loop;
}
}
close(memfd);
*loopfd_p = loopfd;
return 0;
error_close_loop:
close(loopfd);
error_close_memfd:
close(memfd);
error:
errno = err;
return -1;
}
static void reset_loop_device(const char* loopname)
{
int loopfd = open(loopname, O_RDWR);
if (loopfd == -1) {
return;
}
if (ioctl(loopfd, LOOP_CLR_FD, 0)) {
}
close(loopfd);
}
static long syz_mount_image(
volatile long fsarg,
volatile long dir,
volatile long flags,
volatile long optsarg,
volatile long change_dir,
volatile unsigned long size,
volatile long image)
{
unsigned char* data = (unsigned char*)image;
int res = -1, err = 0, need_loop_device = !!size;
char* mount_opts = (char*)optsarg;
char* target = (char*)dir;
char* fs = (char*)fsarg;
char* source = NULL;
char loopname[64];
if (need_loop_device) {
int loopfd;
memset(loopname, 0, sizeof(loopname));
snprintf(loopname, sizeof(loopname), "/dev/loop%llu", procid);
if (setup_loop_device(data, size, loopname, &loopfd) == -1)
return -1;
close(loopfd);
source = loopname;
}
mkdir(target, 0777);
char opts[256];
memset(opts, 0, sizeof(opts));
if (strlen(mount_opts) > (sizeof(opts) - 32)) {
}
strncpy(opts, mount_opts, sizeof(opts) - 32);
if (strcmp(fs, "iso9660") == 0) {
flags |= MS_RDONLY;
} else if (strncmp(fs, "ext", 3) == 0) {
bool has_remount_ro = false;
char* remount_ro_start = strstr(opts, "errors=remount-ro");
if (remount_ro_start != NULL) {
char after = *(remount_ro_start + strlen("errors=remount-ro"));
char before = remount_ro_start == opts ? '\0' : *(remount_ro_start - 1);
has_remount_ro = ((before == '\0' || before == ',') && (after == '\0' || after == ','));
}
if (strstr(opts, "errors=panic") || !has_remount_ro)
strcat(opts, ",errors=continue");
} else if (strcmp(fs, "xfs") == 0) {
strcat(opts, ",nouuid");
} else if (strncmp(fs, "gfs2", 4) == 0 && (strstr(opts, "errors=panic") || strstr(opts, "debug"))) {
strcat(opts, ",errors=withdraw");
}
res = mount(source, target, fs, flags, opts);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
res = open(target, O_RDONLY | O_DIRECTORY);
if (res == -1) {
err = errno;
goto error_clear_loop;
}
if (change_dir) {
res = chdir(target);
if (res == -1) {
err = errno;
}
}
error_clear_loop:
if (need_loop_device)
reset_loop_device(loopname);
errno = err;
return res;
}
uint64_t r[2] = {0xffffffffffffffff, 0xffffffffffffffff};
int main(void)
{
syscall(__NR_mmap, /*addr=*/0x1ffff000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0x1000000, /*prot=PROT_WRITE|PROT_READ|PROT_EXEC*/7ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
syscall(__NR_mmap, /*addr=*/0x21000000ul, /*len=*/0x1000, /*prot=*/0ul, /*flags=MAP_FIXED|MAP_ANONYMOUS|MAP_PRIVATE*/0x32ul, /*fd=*/(intptr_t)-1, /*offset=*/0ul);
const char* reason;
(void)reason;
intptr_t res = 0;
if (write(1, "executing program\n", sizeof("executing program\n") - 1)) {}
// syz_mount_image$ext4 arguments: [
// fs: ptr[in, buffer] {
// buffer: {65 78 74 34 00} (length 0x5)
// }
// dir: ptr[in, buffer] {
// buffer: {2e 2f 66 69 6c 65 31 00} (length 0x8)
// }
// flags: mount_flags = 0x210008 (8 bytes)
// opts: ptr[in, fs_options[ext4_options]] {
// fs_options[ext4_options] {
// elems: array[fs_opt_elem[ext4_options]] {
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nodelalloc: buffer: {6e 6f 64 65 6c 61 6c 6c 6f 63} (length 0xa)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// dioread_lock: buffer: {64 69 6f 72 65 61 64 5f 6c 6f 63 6b} (length 0xc)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// barrier_val: fs_opt["barrier", fmt[hex, int32]] {
// name: buffer: {62 61 72 72 69 65 72} (length 0x7)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x4 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nolazytime: buffer: {6e 6f 6c 61 7a 79 74 69 6d 65} (length 0xa)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// debug_want_extra_isize: fs_opt["debug_want_extra_isize", fmt[hex, int32]] {
// name: buffer: {64 65 62 75 67 5f 77 61 6e 74 5f 65 78 74 72 61 5f 69 73 69 7a 65} (length 0x16)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x80 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// lazytime: buffer: {6c 61 7a 79 74 69 6d 65} (length 0x8)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// errors_remount: buffer: {65 72 72 6f 72 73 3d 72 65 6d 6f 75 6e 74 2d 72 6f} (length 0x11)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// stripe: fs_opt["stripe", fmt[hex, int32]] {
// name: buffer: {73 74 72 69 70 65} (length 0x6)
// eq: const = 0x3d (1 bytes)
// val: int32 = 0x5 (18 bytes)
// }
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// bh: buffer: {62 68} (length 0x2)
// }
// comma: const = 0x2c (1 bytes)
// }
// fs_opt_elem[ext4_options] {
// elem: union ext4_options {
// nodiscard: buffer: {6e 6f 64 69 73 63 61 72 64} (length 0x9)
// }
// comma: const = 0x2c (1 bytes)
// }
// }
// common: array[fs_opt_elem[fs_options_common]] {
// }
// null: const = 0x0 (1 bytes)
// }
// }
// chdir: int8 = 0xfc (1 bytes)
// size: len = 0x56f (8 bytes)
// img: ptr[in, buffer] {
// buffer: (compressed buffer with length 0x56f)
// }
// ]
// returns fd_dir
memcpy((void*)0x200001c0, "ext4\000", 5);
memcpy((void*)0x20000340, "./file1\000", 8);
memcpy((void*)0x20000000, "nodelalloc", 10);
*(uint8_t*)0x2000000a = 0x2c;
memcpy((void*)0x2000000b, "dioread_lock", 12);
*(uint8_t*)0x20000017 = 0x2c;
memcpy((void*)0x20000018, "barrier", 7);
*(uint8_t*)0x2000001f = 0x3d;
sprintf((char*)0x20000020, "0x%016llx", (long long)4);
*(uint8_t*)0x20000032 = 0x2c;
memcpy((void*)0x20000033, "nolazytime", 10);
*(uint8_t*)0x2000003d = 0x2c;
memcpy((void*)0x2000003e, "debug_want_extra_isize", 22);
*(uint8_t*)0x20000054 = 0x3d;
sprintf((char*)0x20000055, "0x%016llx", (long long)0x80);
*(uint8_t*)0x20000067 = 0x2c;
memcpy((void*)0x20000068, "lazytime", 8);
*(uint8_t*)0x20000070 = 0x2c;
memcpy((void*)0x20000071, "errors=remount-ro", 17);
*(uint8_t*)0x20000082 = 0x2c;
memcpy((void*)0x20000083, "stripe", 6);
*(uint8_t*)0x20000089 = 0x3d;
sprintf((char*)0x2000008a, "0x%016llx", (long long)5);
*(uint8_t*)0x2000009c = 0x2c;
memcpy((void*)0x2000009d, "bh", 2);
*(uint8_t*)0x2000009f = 0x2c;
memcpy((void*)0x200000a0, "nodiscard", 9);
*(uint8_t*)0x200000a9 = 0x2c;
*(uint8_t*)0x200000aa = 0;
memcpy((void*)0x20003780, "... [truncated large byte array] ...", 1391);
syz_mount_image(/*fs=*/0x200001c0, /*dir=*/0x20000340, /*flags=MS_POSIXACL|MS_RELATIME|MS_NOEXEC*/0x210008, /*opts=*/0x20000000, /*chdir=*/0xfc, /*size=*/0x56f, /*img=*/0x20003780);
// openat$cgroup_ro arguments: [
// fd: fd_cgroup (resource)
// file: ptr[in, buffer] {
// buffer: {63 67 72 6f 75 70 2e 63 6f 6e 74 72 6f 6c 6c 65 72 73 00} (length 0x13)
// }
// flags: const = 0x275a (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x200001c0, "cgroup.controllers\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x200001c0ul, /*flags=*/0x275a, /*mode=*/0);
if (res != -1)
r[0] = res;
// openat$cgroup_ro arguments: [
// fd: fd_cgroup (resource)
// file: ptr[in, buffer] {
// buffer: {63 67 72 6f 75 70 2e 63 6f 6e 74 72 6f 6c 6c 65 72 73 00} (length 0x13)
// }
// flags: const = 0x275a (4 bytes)
// mode: const = 0x0 (2 bytes)
// ]
// returns fd
memcpy((void*)0x20000080, "cgroup.controllers\000", 19);
res = syscall(__NR_openat, /*fd=*/0xffffff9c, /*file=*/0x20000080ul, /*flags=*/0x275a, /*mode=*/0);
if (res != -1)
r[1] = res;
// write$binfmt_script arguments: [
// fd: fd_binfmt (resource)
// data: ptr[in, binfmt_script] {
// binfmt_script {
// hdr: buffer: {23 21 20} (length 0x3)
// bin: buffer: {} (length 0x0)
// args: array[binfmt_script_arg] {
// }
// nl: const = 0xa (1 bytes)
// data: buffer: {} (length 0x0)
// }
// }
// len: bytesize = 0xfea7 (8 bytes)
// ]
memcpy((void*)0x20000180, "#! ", 3);
*(uint8_t*)0x20000183 = 0xa;
syscall(__NR_write, /*fd=*/r[1], /*data=*/0x20000180ul, /*len=*/0xfea7ul);
// mmap arguments: [
// addr: VMA[0xb36000]
// len: len = 0xb36000 (4 bytes)
// prot: mmap_prot = 0x2 (8 bytes)
// flags: mmap_flags = 0x28011 (8 bytes)
// fd: fd (resource)
// offset: intptr = 0x0 (8 bytes)
// ]
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0xb36000, /*prot=PROT_WRITE*/2ul, /*flags=MAP_STACK|MAP_POPULATE|MAP_FIXED|MAP_SHARED*/0x28011ul, /*fd=*/r[0], /*offset=*/0ul);
// madvise arguments: [
// addr: VMA[0x800000]
// len: len = 0x800000 (8 bytes)
// advice: madvise_flags = 0xe (8 bytes)
// ]
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x800000ul, /*advice=MADV_HUGEPAGE*/0xeul);
// madvise arguments: [
// addr: VMA[0x600000]
// len: len = 0x600000 (8 bytes)
// advice: madvise_flags = 0x19 (8 bytes)
// ]
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x600000ul, /*advice=MADV_COLLAPSE*/0x19ul);
return 0;
}
Reply: **Bug Analysis:**
The bug report describes a deadlock (hung tasks) involving two threads. The lockdep output and stack traces reveal a classic ABBA lock inversion between the `filemap_invalidate_lock` and the `folio_lock` (page lock).
1. **Thread 1 (Filesystem operation, e.g., `ext4_truncate_failed_write` or `fallocate`)**:
Filesystem operations that truncate a file or punch a hole (like `fallocate(PUNCH_HOLE)`) must serialize against page faults and other operations. They do this by first acquiring the `filemap_invalidate_lock` exclusively. Then, they iterate over the affected folios in the page cache and acquire the `folio_lock` for each one (e.g., inside `truncate_inode_pages_range()`).
*Lock order: `filemap_invalidate_lock` -> `folio_lock`*
2. **Thread 2 (`MADV_COLLAPSE` or `khugepaged` background thread)**:
When collapsing file-backed pages into a Transparent Huge Page (THP), `collapse_file()` in `mm/khugepaged.c` iterates over the PMD-sized range, locking folios one by one and adding them to a local list (`pagelist`). If it encounters a missing folio (a hole), it attempts to read it in by calling `page_cache_sync_readahead()`.
To protect against concurrent truncation during readahead, the readahead code (`page_cache_ra_order()` or `do_page_cache_ra()`) acquires the `filemap_invalidate_lock` in shared mode.
*Lock order: `folio_lock` (held from previous iterations) -> `filemap_invalidate_lock`*
**The Deadlock:**
If Thread 2 successfully locks a folio at index `N` and then finds that the folio at index `N+1` is missing, it will call into the readahead code and block trying to acquire `filemap_invalidate_lock_shared` (because Thread 1 holds it exclusively). Meanwhile, Thread 1 is trying to truncate the file and blocks trying to acquire the `folio_lock` for the folio at index `N` (which is held by Thread 2). Both threads wait on each other indefinitely.
**Security Impact:**
* **Exploitable:** No. This is a pure concurrency logic bug (deadlock). It does not cause memory corruption, use-after-free, or out-of-bounds accesses, and therefore cannot be exploited for privilege escalation or information leaks.
* **Denial of Service (DoS):** Yes. An unprivileged local user can easily trigger this deadlock by mapping a file, calling `madvise(..., MADV_COLLAPSE)` on the mapping, and concurrently calling `fallocate(..., FALLOC_FL_PUNCH_HOLE, ...)` on the same file.
This will permanently hang the user's tasks. More importantly, if the background `khugepaged` kernel thread scans the file while it is being truncated, `khugepaged` itself will deadlock, permanently breaking THP collapsing for the entire system. Furthermore, on production systems where `kernel.hung_task_panic = 1` is configured, this deadlock will reliably trigger a kernel panic and crash the system.
* **Accessible From Unprivileged Processes / User Namespaces:** Yes. The `madvise(MADV_COLLAPSE)` and `fallocate()` system calls are available to unprivileged users and do not require any special capabilities.
|
| 6/2 |
2026/08/04 01:28 |
llm |
expert |
0m
Model:
Tokens:
input: 19827
output: 17
thoughts: 1148
Thoughts: **Analyzing a Truncate/Readahead Deadlock in ext4**
Okay, so I've got this syzkaller report β a task blocked in I/O wait for a long time. The stack traces point to a potential issue involving ext4 and, specifically, truncation. We've got two tasks blocked, and the traces are giving us some interesting details.
Task 1 is deeply involved in ext4's truncate process. It looks like it's trying to zero out a range of blocks as part of a truncate operation, and it's holding various locks along the way. Specifically, it's holding `mapping.invalidate_lock` exclusively, and looks to be blocked waiting for a folio lock. The trace makes it clear that we have been in the `ext4_truncate` code path, and more specifically in `ext4_truncate_failed_write`
Task 2, on the other hand, seems to be doing some sort of readahead or madvise operation using `page_cache_sync_readahead` and then `madvise_do_behavior`. It's trying to acquire `filemap_invalidate_lock_shared`, which is actually the same `mapping.invalidate_lock` that Task 1 holds. The key here is the `down_read` call.
Now, things get interesting. Lockdep is telling me that Task 2 *also* appears to be holding the very lock it's trying to acquire (`mapping.invalidate_lock`), which is why it's in the `rwsem_down_read_slowpath`. I know that lockdep reports locks held and the context within `rwsem_down_read_slowpath` means a request is being made. Lockdep *must* be reporting the lock acquisition mid-process. Let's dig deeper: in `collapse_file` which is called in `madvise_do_behavior`.
Wait, Task 1 *definitely* holds `mapping.invalidate_lock` exclusively. So Task 1 is attempting to acquire the `folio_lock` for a file that is in the process of being truncated. Since Task 2 is in `collapse_file`, it's clear Task 2 will be holding folio locks. And `collapse_file` is related to transparent hugepages or madvise. It is at that point where the issue is. This must be the source of the deadlock. I need to examine the interactions within `collapse_file` and figure out how it interacts with the `folio_lock` and the `mapping.invalidate_lock`.
|
| 7/2 |
2026/08/04 01:28 |
tool |
grepper |
0m
Args: map[Expression:collapse_file]
Results: map[Output:fs/inode.c=755=void clear_inode(struct inode *inode)
--
fs/inode.c-775- * (when deep radix-tree node allocation failed partway; or when THP
fs/inode.c:776: * collapse_file() failed). Until those two known cases are cleaned up,
fs/inode.c-777- * or a cleanup function is called here, do not BUG_ON(!mapping_empty),
--
fs/xfs/xfs_bmap_util.c=919=xfs_prepare_shift(
--
fs/xfs/xfs_bmap_util.c-972-/*
fs/xfs/xfs_bmap_util.c:973: * xfs_collapse_file_space()
fs/xfs/xfs_bmap_util.c-974- * This routine frees disk space and shift extent for the given file.
--
fs/xfs/xfs_bmap_util.c=984=int
fs/xfs/xfs_bmap_util.c:985:xfs_collapse_file_space(
fs/xfs/xfs_bmap_util.c-986- struct xfs_inode *ip,
--
fs/xfs/xfs_bmap_util.c-999-
fs/xfs/xfs_bmap_util.c:1000: trace_xfs_collapse_file_space(ip);
fs/xfs/xfs_bmap_util.c-1001-
--
fs/xfs/xfs_bmap_util.h=60=int xfs_free_file_space(struct xfs_inode *ip, xfs_off_t offset,
fs/xfs/xfs_bmap_util.h-61- xfs_off_t len, struct xfs_zone_alloc_ctx *ac);
fs/xfs/xfs_bmap_util.h:62:int xfs_collapse_file_space(struct xfs_inode *, xfs_off_t offset,
fs/xfs/xfs_bmap_util.h-63- xfs_off_t len, struct xfs_zone_alloc_ctx *ac);
--
fs/xfs/xfs_file.c=1259=xfs_falloc_collapse_range(
--
fs/xfs/xfs_file.c-1278-
fs/xfs/xfs_file.c:1279: error = xfs_collapse_file_space(XFS_I(inode), offset, len, ac);
fs/xfs/xfs_file.c-1280- if (error)
--
fs/xfs/xfs_trace.h=1080=DEFINE_INODE_EVENT(xfs_zero_file_space);
fs/xfs/xfs_trace.h:1081:DEFINE_INODE_EVENT(xfs_collapse_file_space);
fs/xfs/xfs_trace.h-1082-DEFINE_INODE_EVENT(xfs_insert_file_space);
--
include/trace/events/huge_memory.h=179=TRACE_EVENT(mm_khugepaged_scan_file,
--
include/trace/events/huge_memory.h-212-
include/trace/events/huge_memory.h:213:TRACE_EVENT(mm_khugepaged_collapse_file,
include/trace/events/huge_memory.h-214- TP_PROTO(struct mm_struct *mm, struct folio *new_folio, pgoff_t index,
--
kernel/bpf/btf.c=6656=static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {
--
kernel/bpf/btf.c-6708- { "mm_khugepaged_scan_file", 0x10 },
kernel/bpf/btf.c:6709: { "mm_khugepaged_collapse_file", 0x10 },
kernel/bpf/btf.c-6710- /* kmem */
--
mm/khugepaged.c=2134=static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
--
mm/khugepaged.c-2217-/**
mm/khugepaged.c:2218: * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
mm/khugepaged.c-2219- *
--
mm/khugepaged.c-2241- */
mm/khugepaged.c:2242:static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
mm/khugepaged.c-2243- struct file *file, pgoff_t start, struct collapse_control *cc)
--
mm/khugepaged.c-2669- VM_BUG_ON(!list_empty(&pagelist));
mm/khugepaged.c:2670: trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
mm/khugepaged.c-2671- return result;
--
mm/khugepaged.c=2674=static enum scan_result collapse_scan_file(struct mm_struct *mm,
--
mm/khugepaged.c-2772- } else {
mm/khugepaged.c:2773: result = collapse_file(mm, addr, file, start, cc);
mm/khugepaged.c-2774- }
]
|
| 8/2 |
2026/08/04 01:28 |
llm |
expert |
0m
Model:
Tokens:
input: 23000
output: 35
thoughts: 21
Thoughts: Here's my analysis of the situation, tailored for my fellow kernel experts:
**Diving into khugepaged.c**
Alright, let's zero in on `collapse_file` within `mm/khugepaged.c`. My immediate thought is, "Okay, this function is critical. We're talking about file-backed huge page collapsing, so this is where the rubber meets the road for performance in file I/O contexts that leverage transparent huge pages." I'm mentally parsing the implications: file mapping, potential copy-on-write complications, and the overhead considerations involved with combining multiple smaller pages into a larger one. This is likely handling the mechanics of consolidating pages. I need to understand how it interacts with the VM subsystem, the page tables, and how it deals with potential issues like page faults and locking. I'm keen to see if it's optimized for different storage scenarios (SSD vs. HDD, etc.) and what its error handling looks like. Any potential for deadlocks or performance bottlenecks is something I want to check for. Gotta see what happens when the page allocation fails, and what other error returns may occur.
|
| 9/2 |
2026/08/04 01:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/khugepaged.c Name:collapse_file]
Results: map[SourceCode:2217: /**
2218: * collapse_file - collapse filemap/tmpfs/shmem pages into huge one.
2219: *
2220: * @mm: process address space where collapse happens
2221: * @addr: virtual collapse start address
2222: * @file: file that collapse on
2223: * @start: collapse start address
2224: * @cc: collapse context and scratchpad
2225: *
2226: * Basic scheme is simple, details are more complex:
2227: * - allocate and lock a new huge page;
2228: * - scan page cache, locking old pages
2229: * + swap/gup in pages if necessary;
2230: * - copy data to new page
2231: * - handle shmem holes
2232: * + re-validate that holes weren't filled by someone else
2233: * + check for userfaultfd
2234: * - finalize updates to the page cache;
2235: * - if replacing succeeds:
2236: * + unlock huge page;
2237: * + free old pages;
2238: * - if replacing failed;
2239: * + unlock old pages
2240: * + unlock and free huge page;
2241: */
2242: static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
2243: struct file *file, pgoff_t start, struct collapse_control *cc)
2244: {
2245: struct address_space *mapping = file->f_mapping;
2246: struct page *dst;
2247: struct folio *folio, *tmp, *new_folio;
2248: pgoff_t index = 0, end = start + HPAGE_PMD_NR;
2249: LIST_HEAD(pagelist);
2250: XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
2251: enum scan_result result = SCAN_SUCCEED;
2252: int nr_none = 0;
2253: bool is_shmem = shmem_file(file);
2254:
2255: /*
2256: * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
2257: *
2258: * TODO: once shmem always calls mapping_set_large_folios() on its
2259: * mapping, the shmem check can be removed.
2260: */
2261: VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
2262: VM_WARN_ON_ONCE(start & (HPAGE_PMD_NR - 1));
2263:
2264: result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
2265: if (result != SCAN_SUCCEED)
2266: goto out;
2267:
2268: mapping_set_update(&xas, mapping);
2269:
2270: __folio_set_locked(new_folio);
2271: if (is_shmem)
2272: __folio_set_swapbacked(new_folio);
2273: new_folio->index = start;
2274: new_folio->mapping = mapping;
2275:
2276: /*
2277: * Ensure we have slots for all the pages in the range. This is
2278: * almost certainly a no-op because most of the pages must be present
2279: */
2280: do {
2281: xas_lock_irq(&xas);
2282: xas_create_range(&xas);
2283: if (!xas_error(&xas))
2284: break;
2285: xas_unlock_irq(&xas);
2286: if (!xas_nomem(&xas, GFP_KERNEL)) {
2287: result = SCAN_FAIL;
2288: goto rollback;
2289: }
2290: } while (1);
2291:
2292: for (index = start; index < end;) {
2293: xas_set(&xas, index);
2294: folio = xas_load(&xas);
2295:
2296: VM_BUG_ON(index != xas.xa_index);
2297: if (is_shmem) {
2298: if (!folio) {
2299: /*
2300: * Stop if extent has been truncated or
2301: * hole-punched, and is now completely
2302: * empty.
2303: */
2304: if (index == start) {
2305: if (!xas_next_entry(&xas, end - 1)) {
2306: result = SCAN_TRUNCATED;
2307: goto xa_locked;
2308: }
2309: }
2310: nr_none++;
2311: index++;
2312: continue;
2313: }
2314:
2315: if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
2316: xas_unlock_irq(&xas);
2317: /* swap in or instantiate fallocated page */
2318: if (shmem_get_folio(mapping->host, index, 0,
2319: &folio, SGP_NOALLOC)) {
2320: result = SCAN_FAIL;
2321: goto xa_unlocked;
2322: }
2323: /* drain lru cache to help folio_isolate_lru() */
2324: lru_add_drain();
2325: } else if (folio_trylock(folio)) {
2326: folio_get(folio);
2327: xas_unlock_irq(&xas);
2328: } else {
2329: result = SCAN_PAGE_LOCK;
2330: goto xa_locked;
2331: }
2332: } else { /* !is_shmem */
2333: if (!folio || xa_is_value(folio)) {
2334: xas_unlock_irq(&xas);
2335: page_cache_sync_readahead(mapping, &file->f_ra,
2336: file, index,
2337: end - index);
2338: /* drain lru cache to help folio_isolate_lru() */
2339: lru_add_drain();
2340: folio = filemap_lock_folio(mapping, index);
2341: if (IS_ERR(folio)) {
2342: result = SCAN_FAIL;
2343: goto xa_unlocked;
2344: }
2345: } else if (folio_test_dirty(folio)) {
2346: /*
2347: * This page is dirty because it hasn't
2348: * been flushed since first write.
2349: *
2350: * Trigger async flush for read-only files and
2351: * hope the writeback is done when khugepaged
2352: * revisits this page. Writable files can have
2353: * their folios dirty at any time; blindly
2354: * flushing them would cause undesirable
2355: * system-wide writeback.
2356: *
2357: * This is a one-off situation. We are not
2358: * forcing writeback in loop.
2359: */
2360: xas_unlock_irq(&xas);
2361: if (!inode_is_open_for_write(mapping->host))
2362: filemap_flush(mapping);
2363: result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
2364: goto xa_unlocked;
2365: } else if (folio_test_writeback(folio)) {
2366: xas_unlock_irq(&xas);
2367: result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
2368: goto xa_unlocked;
2369: } else if (folio_trylock(folio)) {
2370: folio_get(folio);
2371: xas_unlock_irq(&xas);
2372: } else {
2373: result = SCAN_PAGE_LOCK;
2374: goto xa_locked;
2375: }
2376: }
2377:
2378: /*
2379: * The folio must be locked, so we can drop the i_pages lock
2380: * without racing with truncate.
2381: */
2382: VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
2383:
2384: /* make sure the folio is up to date */
2385: if (unlikely(!folio_test_uptodate(folio))) {
2386: result = SCAN_FAIL;
2387: goto out_unlock;
2388: }
2389:
2390: /*
2391: * If file was truncated then extended, or hole-punched, before
2392: * we locked the first folio, then a THP might be there already.
2393: * This will be discovered on the first iteration.
2394: */
2395: if (is_pmd_order(folio_order(folio))) {
2396: result = SCAN_PTE_MAPPED_HUGEPAGE;
2397: goto out_unlock;
2398: }
2399:
2400: if (folio_mapping(folio) != mapping) {
2401: result = SCAN_TRUNCATED;
2402: goto out_unlock;
2403: }
2404:
2405: if (!is_shmem && (folio_test_dirty(folio) ||
2406: folio_test_writeback(folio))) {
2407: /*
2408: * khugepaged only works on clean file-backed folios,
2409: * so this folio is dirty because it hasn't been flushed
2410: * since first write.
2411: */
2412: result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
2413: goto out_unlock;
2414: }
2415:
2416: if (!folio_isolate_lru(folio)) {
2417: result = SCAN_DEL_PAGE_LRU;
2418: goto out_unlock;
2419: }
2420:
2421: if (!filemap_release_folio(folio, GFP_KERNEL)) {
2422: result = SCAN_PAGE_HAS_PRIVATE;
2423: folio_putback_lru(folio);
2424: goto out_unlock;
2425: }
2426:
2427: if (folio_mapped(folio))
2428: try_to_unmap(folio,
2429: TTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);
2430:
2431: xas_lock_irq(&xas);
2432:
2433: VM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio);
2434:
2435: /*
2436: * We control 2 + nr_pages references to the folio:
2437: * - we hold a pin on it;
2438: * - nr_pages reference from page cache;
2439: * - one from lru_isolate_folio;
2440: * If those are the only references, then any new usage
2441: * of the folio will have to fetch it from the page
2442: * cache. That requires locking the folio to handle
2443: * truncate, so any new usage will be blocked until we
2444: * unlock folio after collapse/during rollback.
2445: */
2446: if (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) {
2447: result = SCAN_PAGE_COUNT;
2448: xas_unlock_irq(&xas);
2449: folio_putback_lru(folio);
2450: goto out_unlock;
2451: }
2452:
2453: /*
2454: * At this point, the folio is locked and unmapped. If the PTE
2455: * was dirty, try_to_unmap() has transferred the dirty bit to
2456: * the folio and we must not collapse it into a clean
2457: * file-backed folio.
2458: *
2459: * If the folio is clean here, no one can write it until we
2460: * drop the folio lock. A write through a stale TLB entry came
2461: * from a clean PTE and must fault because the PTE has been
2462: * cleared; the fault path has to take the folio lock before
2463: * installing a writable mapping. Buffered write paths also
2464: * have to take the folio lock before modifying file contents
2465: * without a mapping, typically via write_begin_get_folio().
2466: */
2467: if (!is_shmem && folio_test_dirty(folio)) {
2468: result = SCAN_PAGE_DIRTY_OR_WRITEBACK;
2469: xas_unlock_irq(&xas);
2470: folio_putback_lru(folio);
2471: goto out_unlock;
2472: }
2473:
2474: /*
2475: * Accumulate the folios that are being collapsed.
2476: */
2477: list_add_tail(&folio->lru, &pagelist);
2478: index += folio_nr_pages(folio);
2479: continue;
2480: out_unlock:
2481: folio_unlock(folio);
2482: folio_put(folio);
2483: goto xa_unlocked;
2484: }
2485:
2486: xa_locked:
2487: xas_unlock_irq(&xas);
2488: xa_unlocked:
2489:
2490: /*
2491: * If collapse is successful, flush must be done now before copying.
2492: * If collapse is unsuccessful, does flush actually need to be done?
2493: * Do it anyway, to clear the state.
2494: */
2495: try_to_unmap_flush();
2496:
2497: if (result == SCAN_SUCCEED && nr_none &&
2498: !shmem_charge(mapping->host, nr_none))
2499: result = SCAN_FAIL;
2500: if (result != SCAN_SUCCEED) {
2501: nr_none = 0;
2502: goto rollback;
2503: }
2504:
2505: /*
2506: * The old folios are locked, so they won't change anymore.
2507: */
2508: index = start;
2509: dst = folio_page(new_folio, 0);
2510: list_for_each_entry(folio, &pagelist, lru) {
2511: int i, nr_pages = folio_nr_pages(folio);
2512:
2513: while (index < folio->index) {
2514: clear_highpage(dst);
2515: index++;
2516: dst++;
2517: }
2518:
2519: for (i = 0; i < nr_pages; i++) {
2520: if (copy_mc_highpage(dst, folio_page(folio, i)) > 0) {
2521: result = SCAN_COPY_MC;
2522: goto rollback;
2523: }
2524: index++;
2525: dst++;
2526: }
2527: }
2528: while (index < end) {
2529: clear_highpage(dst);
2530: index++;
2531: dst++;
2532: }
2533:
2534: if (nr_none) {
2535: struct vm_area_struct *vma;
2536: int nr_none_check = 0;
2537:
2538: i_mmap_lock_read(mapping);
2539: xas_lock_irq(&xas);
2540:
2541: xas_set(&xas, start);
2542: for (index = start; index < end; index++) {
2543: if (!xas_next(&xas)) {
2544: xas_store(&xas, XA_RETRY_ENTRY);
2545: if (xas_error(&xas)) {
2546: result = SCAN_STORE_FAILED;
2547: goto immap_locked;
2548: }
2549: nr_none_check++;
2550: }
2551: }
2552:
2553: if (nr_none != nr_none_check) {
2554: result = SCAN_PAGE_FILLED;
2555: goto immap_locked;
2556: }
2557:
2558: /*
2559: * If userspace observed a missing page in a VMA with
2560: * a MODE_MISSING userfaultfd, then it might expect a
2561: * UFFD_EVENT_PAGEFAULT for that page. If so, we need to
2562: * roll back to avoid suppressing such an event. Since
2563: * wp/minor userfaultfds don't give userspace any
2564: * guarantees that the kernel doesn't fill a missing
2565: * page with a zero page, so they don't matter here.
2566: *
2567: * Any userfaultfds registered after this point will
2568: * not be able to observe any missing pages due to the
2569: * previously inserted retry entries.
2570: */
2571: vma_interval_tree_foreach(vma, &mapping->i_mmap, start, end) {
2572: if (userfaultfd_missing(vma)) {
2573: result = SCAN_EXCEED_NONE_PTE;
2574: goto immap_locked;
2575: }
2576: }
2577:
2578: immap_locked:
2579: i_mmap_unlock_read(mapping);
2580: if (result != SCAN_SUCCEED) {
2581: xas_set(&xas, start);
2582: for (index = start; index < end; index++) {
2583: if (xas_next(&xas) == XA_RETRY_ENTRY)
2584: xas_store(&xas, NULL);
2585: }
2586:
2587: xas_unlock_irq(&xas);
2588: goto rollback;
2589: }
2590: } else {
2591: xas_lock_irq(&xas);
2592: }
2593:
2594: if (is_shmem) {
2595: lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR);
2596: lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
2597: } else {
2598: lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
2599: }
2600: lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR);
2601:
2602: /*
2603: * Mark new_folio as uptodate before inserting it into the
2604: * page cache so that it isn't mistaken for an fallocated but
2605: * unwritten page.
2606: */
2607: folio_mark_uptodate(new_folio);
2608: folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
2609:
2610: if (is_shmem)
2611: folio_mark_dirty(new_folio);
2612: folio_add_lru(new_folio);
2613:
2614: /* Join all the small entries into a single multi-index entry. */
2615: xas_set_order(&xas, start, HPAGE_PMD_ORDER);
2616: xas_store(&xas, new_folio);
2617: WARN_ON_ONCE(xas_error(&xas));
2618: xas_unlock_irq(&xas);
2619:
2620: /*
2621: * Remove pte page tables, so we can re-fault the page as huge.
2622: * If MADV_COLLAPSE, adjust result to call try_collapse_pte_mapped_thp().
2623: */
2624: retract_page_tables(mapping, start);
2625: if (cc && !cc->is_khugepaged)
2626: result = SCAN_PTE_MAPPED_HUGEPAGE;
2627: folio_unlock(new_folio);
2628:
2629: /*
2630: * The collapse has succeeded, so free the old folios.
2631: */
2632: list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2633: list_del(&folio->lru);
2634: lruvec_stat_mod_folio(folio, NR_FILE_PAGES,
2635: -folio_nr_pages(folio));
2636: if (is_shmem)
2637: lruvec_stat_mod_folio(folio, NR_SHMEM,
2638: -folio_nr_pages(folio));
2639: folio->mapping = NULL;
2640: folio_clear_active(folio);
2641: folio_clear_unevictable(folio);
2642: folio_unlock(folio);
2643: folio_put_refs(folio, 2 + folio_nr_pages(folio));
2644: }
2645:
2646: goto out;
2647:
2648: rollback:
2649: /* Something went wrong: roll back page cache changes */
2650: if (nr_none) {
2651: xas_lock_irq(&xas);
2652: mapping->nrpages -= nr_none;
2653: xas_unlock_irq(&xas);
2654: shmem_uncharge(mapping->host, nr_none);
2655: }
2656:
2657: list_for_each_entry_safe(folio, tmp, &pagelist, lru) {
2658: list_del(&folio->lru);
2659: folio_unlock(folio);
2660: folio_putback_lru(folio);
2661: folio_put(folio);
2662: }
2663:
2664: new_folio->mapping = NULL;
2665:
2666: folio_unlock(new_folio);
2667: folio_put(new_folio);
2668: out:
2669: VM_BUG_ON(!list_empty(&pagelist));
2670: trace_mm_khugepaged_collapse_file(mm, new_folio, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
2671: return result;
2672: }
SourceFile:mm/khugepaged.c]
|
| 10/2 |
2026/08/04 01:28 |
llm |
expert |
0m
Model:
Tokens:
input: 30109
output: 35
thoughts: 2483
Thoughts: **Analyzing a Read-Ahead/Truncate Concurrency Issue**
Okay, so I'm diving into a deadlock scenario, specifically related to how file truncation interacts with read-ahead operations, as triggered by the `madvise_collapse` system call. The goal is to figure out the lock ordering and how it relates to the existing code.
First, `collapse_file` seems to be the critical point. It appears to iterate over folios within a file range. The code locks folios one by one, adds them to a list (`pagelist`), and proceeds to the next folio index. If the current index has no folio, it calls `page_cache_sync_readahead`, which in turn, calls `page_cache_ra_order`. It is at this point that things get interesting. `page_cache_ra_order` attempts to acquire `filemap_invalidate_lock_shared`.
Crucially, `collapse_file` *does* hold folio locks when calling `page_cache_sync_readahead`! This is because it locks the folios one by one and adds them to `pagelist` before moving to the next index, which causes the subsequent call to `page_cache_sync_readahead` to call `page_cache_ra_order`.
The core of the problem seems to be the lock order. I know that `filemap_invalidate_lock` (or `filemap_invalidate_lock_shared` in this case) is usually acquired *before* folio locks. However, here, `collapse_file` holds folio locks *while* `page_cache_sync_readahead` attempts to acquire `filemap_invalidate_lock_shared` in `page_cache_ra_order`.
Now, the lockdep output shows multiple tasks involved: multiple pairs of tasks:
* Task 1 is in `ext4_write_end` -> `ext4_truncate_failed_write` holding `mapping.invalidate_lock` exclusively.
* Task 2 is in `page_cache_ra_order` trying to acquire `mapping.invalidate_lock` shared.
Each of the tasks are trying to acquire the `mapping.invalidate_lock`, and this is where the deadlock arises.
So, `ext4_write_end` calls `ext4_truncate_failed_write`, which tries to acquire `filemap_invalidate_lock(mapping)`. Meanwhile, `collapse_file` is still working, holding the folio lock, then calling `page_cache_sync_readahead`, which then calls `page_cache_ra_order`, which is trying to acquire the shared version of the same lock.
The issue stems from `ext4_truncate_failed_write` acquiring `filemap_invalidate_lock` while `collapse_file` holds folio locks on that same file. This lock order violation causes the deadlock.
|
| 11/2 |
2026/08/04 01:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/filemap.c Name:generic_perform_write]
Results: map[SourceCode:4330: ssize_t generic_perform_write(struct kiocb *iocb, struct iov_iter *i)
4331: {
4332: struct file *file = iocb->ki_filp;
4333: loff_t pos = iocb->ki_pos;
4334: struct address_space *mapping = file->f_mapping;
4335: const struct address_space_operations *a_ops = mapping->a_ops;
4336: size_t chunk = mapping_max_folio_size(mapping);
4337: long status = 0;
4338: ssize_t written = 0;
4339:
4340: do {
4341: struct folio *folio;
4342: size_t offset; /* Offset into folio */
4343: size_t bytes; /* Bytes to write to folio */
4344: size_t copied; /* Bytes copied from user */
4345: void *fsdata = NULL;
4346:
4347: bytes = iov_iter_count(i);
4348: retry:
4349: offset = pos & (chunk - 1);
4350: bytes = min(chunk - offset, bytes);
4351: balance_dirty_pages_ratelimited(mapping);
4352:
4353: if (fatal_signal_pending(current)) {
4354: status = -EINTR;
4355: break;
4356: }
4357:
4358: status = a_ops->write_begin(iocb, mapping, pos, bytes,
4359: &folio, &fsdata);
4360: if (unlikely(status < 0))
4361: break;
4362:
4363: offset = offset_in_folio(folio, pos);
4364: if (bytes > folio_size(folio) - offset)
4365: bytes = folio_size(folio) - offset;
4366:
4367: if (mapping_writably_mapped(mapping))
4368: flush_dcache_folio(folio);
4369:
4370: /*
4371: * Faults here on mmap()s can recurse into arbitrary
4372: * filesystem code. Lots of locks are held that can
4373: * deadlock. Use an atomic copy to avoid deadlocking
4374: * in page fault handling.
4375: */
4376: copied = copy_folio_from_iter_atomic(folio, offset, bytes, i);
4377: flush_dcache_folio(folio);
4378:
4379: status = a_ops->write_end(iocb, mapping, pos, bytes, copied,
4380: folio, fsdata);
4381: if (unlikely(status != copied)) {
4382: iov_iter_revert(i, copied - max(status, 0L));
4383: if (unlikely(status < 0))
4384: break;
4385: }
4386: cond_resched();
4387:
4388: if (unlikely(status == 0)) {
4389: /*
4390: * A short copy made ->write_end() reject the
4391: * thing entirely. Might be memory poisoning
4392: * halfway through, might be a race with munmap,
4393: * might be severe memory pressure.
4394: */
4395: if (chunk > PAGE_SIZE)
4396: chunk /= 2;
4397: if (copied) {
4398: bytes = copied;
4399: goto retry;
4400: }
4401:
4402: /*
4403: * 'folio' is now unlocked and faults on it can be
4404: * handled. Ensure forward progress by trying to
4405: * fault it in now.
4406: */
4407: if (fault_in_iov_iter_readable(i, bytes) == bytes) {
4408: status = -EFAULT;
4409: break;
4410: }
4411: } else {
4412: pos += status;
4413: written += status;
4414: }
4415: } while (iov_iter_count(i));
4416:
4417: if (!written)
4418: return status;
4419: iocb->ki_pos += written;
4420: return written;
4421: }
SourceFile:mm/filemap.c]
|
| 12/2 |
2026/08/04 01:28 |
llm |
expert |
0m
Model:
Tokens:
input: 34564
output: 38
thoughts: 105
Thoughts: **Concurrence Conundrum: `ext4_write_end`'s Lock Acquisition**
Okay, hold on a second. This is making my head spin a bit. I need to make sure I've got this right. I'm seeing that `a_ops->write_begin` is responsible for locking the folio, right? And then, confirming my initial instinct, `a_ops->write_end` is predictably called *while* that very same folio is still locked. Perfect, that's what I'd expect.
But here's the kicker, and this is where I need to be absolutely precise. `ext4_write_end` calls `ext4_truncate_failed_write`, and *that* function, if triggered, will acquire `filemap_invalidate_lock(mapping)`. So, the path I'm seeing here is that `ext4_write_end` is, in effect, trying to get `filemap_invalidate_lock` while *already* holding the folio lock. That could lead to some nasty concurrency issues, potential deadlocks, you name it, and I am not a fan of undefined behavior.
I've got to investigate this further. I need to dive into `ext4_write_end` to fully understand what's going on with these locks. There's a possible contention issue brewing here, and it demands immediate attention.
|
| 13/2 |
2026/08/04 01:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/ext4/inode.c Name:ext4_write_end]
Results: map[SourceCode:1435: /*
1436: * We need to pick up the new inode size which generic_commit_write gave us
1437: * `iocb` can be NULL - eg, when called from page_symlink().
1438: */
1439: static int ext4_write_end(const struct kiocb *iocb,
1440: struct address_space *mapping,
1441: loff_t pos, unsigned len, unsigned copied,
1442: struct folio *folio, void *fsdata)
1443: {
1444: handle_t *handle = ext4_journal_current_handle();
1445: struct inode *inode = mapping->host;
1446: loff_t old_size = inode->i_size;
1447: int ret = 0, ret2;
1448: int i_size_changed = 0;
1449: bool verity = ext4_verity_in_progress(inode);
1450:
1451: trace_ext4_write_end(inode, pos, len, copied);
1452:
1453: if (ext4_has_inline_data(inode) &&
1454: ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1455: return ext4_write_inline_data_end(inode, pos, len, copied,
1456: folio);
1457:
1458: copied = block_write_end(pos, len, copied, folio);
1459: /*
1460: * it's important to update i_size while still holding folio lock:
1461: * page writeout could otherwise come in and zero beyond i_size.
1462: *
1463: * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
1464: * blocks are being written past EOF, so skip the i_size update.
1465: */
1466: if (!verity)
1467: i_size_changed = ext4_update_inode_size(inode, pos + copied);
1468: folio_unlock(folio);
1469: folio_put(folio);
1470:
1471: if (old_size < pos && !verity)
1472: pagecache_isize_extended(inode, old_size, pos);
1473:
1474: /*
1475: * Don't mark the inode dirty under folio lock. First, it unnecessarily
1476: * makes the holding time of folio lock longer. Second, it forces lock
1477: * ordering of folio lock and transaction start for journaling
1478: * filesystems.
1479: */
1480: if (i_size_changed)
1481: ret = ext4_mark_inode_dirty(handle, inode);
1482:
1483: if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1484: /* if we have allocated more blocks and copied
1485: * less. We will have blocks allocated outside
1486: * inode->i_size. So truncate them
1487: */
1488: ext4_orphan_add(handle, inode);
1489:
1490: ret2 = ext4_journal_stop(handle);
1491: if (!ret)
1492: ret = ret2;
1493:
1494: if (pos + len > inode->i_size && !verity) {
1495: ext4_truncate_failed_write(inode);
1496: /*
1497: * If truncate failed early the inode might still be
1498: * on the orphan list; we need to make sure the inode
1499: * is removed from the orphan list in that case.
1500: */
1501: if (inode->i_nlink)
1502: ext4_orphan_del(NULL, inode);
1503: }
1504:
1505: return ret ? ret : copied;
1506: }
SourceFile:fs/ext4/inode.c]
|
| 14/2 |
2026/08/04 01:28 |
llm |
expert |
0m
Model:
Tokens:
input: 36180
output: 37
thoughts: 1040
Thoughts: **Deadlock Analysis in ext4 File System Write Path**
Okay, let's break this down. My initial thought was: hold on a second, `ext4_write_end` *unlocks* the folio! This means it doesn't have the folio lock when it potentially calls `ext4_truncate_failed_write`. But then, why is Task 1 waiting for a folio lock within that function? We're looking at a potential race condition and I need to understand the control flow.
Tracing `ext4_truncate_failed_write` reveals the problem lies in `ext4_load_tail_bh` through the use of `__filemap_get_folio`, which ultimately attempts to grab a folio lock. So, we've got Task 1 attempting to grab a folio lock *within* a function triggered after a failed write. Crucially, it is also holding the `filemap_invalidate_lock(mapping)` exclusively!
Meanwhile, Task 2 is sitting in `collapse_file`. It's *already* holding a folio lock and calls `page_cache_sync_readahead`, which in turn attempts to acquire `filemap_invalidate_lock_shared(mapping)`. That's it! That's the ABBA deadlock right there: Task 1 grabs the filemap lock, tries to grab folio; Task 2 grabs folio, tries to grab the shared filemap lock.
I've seen this pattern before, but now let's confirm the details. `collapse_file` seems to be the culprit. It locks folios and then calls `page_cache_sync_readahead`, a function which, as we know, needs to acquire `filemap_invalidate_lock_shared`. The lock ordering dictates that `filemap_invalidate_lock` should be held *before* folio locks.
Let's verify what `collapse_file` does. It accumulates folios in a `pagelist` and then *conditionally* calls `page_cache_sync_readahead` if it encounters a missing folio. Now here's the kicker: it calls `page_cache_sync_readahead` WHILE holding those other folio locks! It doesn't unlock the folios in the `pagelist` before making the `page_cache_sync_readahead` call.
Therefore, if `collapse_file` managed to lock some folios (e.g. index 0), and then at index 1 finds a missing folio, the call to `page_cache_sync_readahead` will be made *while still holding* the lock on folio 0!
Now we need to confirm the assumption that `page_cache_sync_readahead` is actually the function acquiring the shared lock. Yes, the function `page_cache_ra_order` calls `filemap_invalidate_lock_shared(mapping)`.
Now, is this a recent change? We should verify the modification history of the function `page_cache_ra_order` in `mm/readahead.c`.
|
| 15/2 |
2026/08/04 01:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/readahead.c Name:page_cache_ra_order]
Results: map[SourceCode: 481: void page_cache_ra_order(struct readahead_control *ractl,
482: struct file_ra_state *ra)
483: {
484: struct address_space *mapping = ractl->mapping;
485: pgoff_t start = readahead_index(ractl);
486: pgoff_t index = start;
487: unsigned int min_order = mapping_min_folio_order(mapping);
488: pgoff_t limit = (i_size_read(mapping->host) - 1) >> PAGE_SHIFT;
489: pgoff_t mark;
490: unsigned int nofs;
491: int err = 0;
492: gfp_t gfp = readahead_gfp_mask(mapping);
493: unsigned int new_order = ra->order;
494:
495: trace_page_cache_ra_order(mapping->host, start, ra);
496: if (!mapping_large_folio_support(mapping)) {
497: ra->order = 0;
498: goto fallback;
499: }
500:
501: if (limit > index + ra->size - 1) {
502: limit = index + ra->size - 1;
503: mark = index + ra->size - ra->async_size;
504: } else {
505: /* We've reached the end, so don't set a readahead marker. */
506: mark = ULONG_MAX;
507: }
508:
509: new_order = min(mapping_max_folio_order(mapping), new_order);
510: new_order = min_t(unsigned int, new_order, ilog2(ra->size));
511: new_order = max(new_order, min_order);
512:
513: ra->order = new_order;
514:
515: /* See comment in page_cache_ra_unbounded() */
516: nofs = memalloc_nofs_save();
517: filemap_invalidate_lock_shared(mapping);
518: /*
519: * If the new_order is greater than min_order and index is
520: * already aligned to new_order, then this will be noop as index
521: * aligned to new_order should also be aligned to min_order.
522: */
523: ractl->_index = mapping_align_index(mapping, index);
524: index = readahead_index(ractl);
525:
526: while (index <= limit) {
527: unsigned int order = new_order;
528:
529: /* Align with smaller pages if needed */
530: if (index & ((1UL << order) - 1))
531: order = __ffs(index);
532: /* Don't allocate pages past EOF */
533: while (order > min_order && index + (1UL << order) - 1 > limit)
534: order--;
535: err = ra_alloc_folio(ractl, index, mark, order, gfp);
536: if (err)
537: break;
538: index += 1UL << order;
539: }
540:
541: read_pages(ractl);
542: filemap_invalidate_unlock_shared(mapping);
543: memalloc_nofs_restore(nofs);
544:
545: /*
546: * If there were already pages in the page cache, then we may have
547: * left some gaps. Let the regular readahead code take care of this
548: * situation below.
549: */
550: if (!err)
551: return;
552: fallback:
553: /*
554: * ->readahead() may have updated readahead window size so we have to
555: * check there's still something to read.
556: */
557: if (ra->size > index - start)
558: do_page_cache_ra(ractl, ra->size - (index - start),
559: ra->async_size);
560: }
SourceFile:mm/readahead.c]
|
| 16/2 |
2026/08/04 01:29 |
llm |
expert |
0m
Model:
Tokens:
input: 39193
output: 37
thoughts: 162
Thoughts: **Deadlock Discovered in Page Cache Synchronization**
Okay, so I've spotted a nasty one. It looks like `page_cache_ra_order` is grabbing the `filemap_invalidate_lock_shared(mapping)`. At the same time, `collapse_file` has held folio locks when it calls `page_cache_sync_readahead`. Bingo! Potential deadlock.
Now, the real question is, can an unprivileged user trigger this? Let's trace it back. `collapse_file` is called by `madvise_collapse`, which handles the `MADV_COLLAPSE` operation. `MADV_COLLAPSE` *is* available to unprivileged users, isn't it? Hold on... isn't there a `CAP_SYS_ADMIN` requirement for that? Let's double-check the `madvise_collapse` implementation. Where is that... ah, in `mm/khugepaged.c`. Let me take a look there.
|
| 17/2 |
2026/08/04 01:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/khugepaged.c Name:madvise_collapse]
Results: map[SourceCode:3185: int madvise_collapse(struct vm_area_struct *vma, unsigned long start,
3186: unsigned long end, bool *lock_dropped)
3187: {
3188: struct collapse_control *cc;
3189: struct mm_struct *mm = vma->vm_mm;
3190: unsigned long hstart, hend, addr;
3191: enum scan_result last_fail = SCAN_FAIL;
3192: int thps = 0;
3193: bool mmap_unlocked = false;
3194:
3195: BUG_ON(vma->vm_start > start);
3196: BUG_ON(vma->vm_end < end);
3197:
3198: if (!collapse_possible(vma, vma->vm_flags, TVA_FORCED_COLLAPSE))
3199: return -EINVAL;
3200:
3201: hstart = ALIGN(start, HPAGE_PMD_SIZE);
3202: hend = ALIGN_DOWN(end, HPAGE_PMD_SIZE);
3203:
3204: if (hstart >= hend)
3205: return 0;
3206:
3207: cc = kmalloc_obj(*cc);
3208: if (!cc)
3209: return -ENOMEM;
3210: cc->is_khugepaged = false;
3211: cc->progress = 0;
3212:
3213: mmgrab(mm);
3214: lru_add_drain_all();
3215:
3216: for (addr = hstart; addr < hend; addr += HPAGE_PMD_SIZE) {
3217: enum scan_result result = SCAN_FAIL;
3218:
3219: if (mmap_unlocked) {
3220: cond_resched();
3221: mmap_read_lock(mm);
3222: mmap_unlocked = false;
3223: *lock_dropped = true;
3224: result = hugepage_vma_revalidate(mm, addr, false, &vma,
3225: cc, HPAGE_PMD_ORDER);
3226: if (result != SCAN_SUCCEED) {
3227: last_fail = result;
3228: goto out_nolock;
3229: }
3230:
3231: hend = min(hend, vma->vm_end & HPAGE_PMD_MASK);
3232: }
3233:
3234: result = collapse_single_pmd(addr, vma, &mmap_unlocked, cc);
3235:
3236: switch (result) {
3237: case SCAN_SUCCEED:
3238: case SCAN_PMD_MAPPED:
3239: ++thps;
3240: break;
3241: /* Whitelisted set of results where continuing OK */
3242: case SCAN_NO_PTE_TABLE:
3243: case SCAN_PTE_NON_PRESENT:
3244: case SCAN_PTE_UFFD_WP:
3245: case SCAN_LACK_REFERENCED_PAGE:
3246: case SCAN_PAGE_NULL:
3247: case SCAN_PAGE_COUNT:
3248: case SCAN_PAGE_LOCK:
3249: case SCAN_PAGE_COMPOUND:
3250: case SCAN_PAGE_LRU:
3251: case SCAN_DEL_PAGE_LRU:
3252: last_fail = result;
3253: break;
3254: default:
3255: last_fail = result;
3256: /* Other error, exit */
3257: goto out_maybelock;
3258: }
3259: }
3260:
3261: out_maybelock:
3262: /* Caller expects us to hold mmap_lock on return */
3263: if (mmap_unlocked) {
3264: *lock_dropped = true;
3265: mmap_read_lock(mm);
3266: }
3267: out_nolock:
3268: mmap_assert_locked(mm);
3269: mmdrop(mm);
3270: kfree(cc);
3271:
3272: return thps == ((hend - hstart) >> HPAGE_PMD_SHIFT) ? 0
3273: : madvise_collapse_errno(last_fail);
3274: }
SourceFile:mm/khugepaged.c]
|
| 18/2 |
2026/08/04 01:29 |
llm |
expert |
0m
Model:
Tokens:
input: 40941
output: 35
thoughts: 41
Thoughts: Okay, let me think this through.
**Analyzing `madvise_collapse` Implementation**
Hmm, so `madvise_collapse`... I was under the impression it had some sort of privilege check, perhaps involving `CAP_SYS_ADMIN` or something similar, but that doesn't seem to be the case. It appears the only control on its execution is `collapse_possible`. That's a critical detail. Now, I need to understand what exactly determines if `collapse_possible` is true or false. That's where the real logic is buried. I need to investigate what's behind `collapse_possible`. That's the key.
|
| 19/2 |
2026/08/04 01:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/khugepaged.c Name:collapse_possible]
Results: map[SourceCode: 586: static bool collapse_possible(struct vm_area_struct *vma,
587: vm_flags_t vm_flags, enum tva_type tva_flags)
588: {
589: return collapse_possible_orders(vma, vm_flags, tva_flags);
590: }
SourceFile:mm/khugepaged.c]
|
| 20/2 |
2026/08/04 01:29 |
llm |
expert |
0m
Model:
Tokens:
input: 41279
output: 42
thoughts: 408
Thoughts: **Analyzing a Potential Deadlock in File System Operations**
Okay, so what I'm looking at here is a potential deadlock scenario. Basically, it boils down to the interaction of `MADV_COLLAPSE` with file system operations. My initial thought is it's checking if the Virtual Memory Area (VMA) can be collapsed. This `MADV_COLLAPSE` is available to unprivileged users, that's important to keep in mind.
The key is that `MADV_COLLAPSE` can trigger `collapse_file`. The concern is that `collapse_file` could then trigger a deadlock. The deadlock's circumstances are specific: it requires a write operation from another thread that extends the file size, and this write has to fail, leading to `ext4_truncate_failed_write`. Or, in a more general sense, any operation that grabs `filemap_invalidate_lock` exclusively and *then* tries to lock a folio is in the danger zone.
Hold on, let me refine that. For example, `ext4_punch_hole` grabs `filemap_invalidate_lock` exclusively, and then calls `truncate_pagecache_range`, which *also* locks folios. Damn, `truncate_pagecache_range` indeed locks folios! So `ext4_punch_hole` also exhibits that dangerous lock order. This is a pretty common pattern I'm noticing: `filemap_invalidate_lock` is the outer lock, and `folio_lock` is the inner lock.
But here's the kicker: `collapse_file` acquires `folio_lock` and *then* tries to acquire `filemap_invalidate_lock_shared` (specifically via `page_cache_sync_readahead`). Bingo! That's a clear ABBA deadlock scenario: `folio_lock` then `filemap_invalidate_lock_shared`, while other code paths may be the reverse.
Now I need to confirm whether `page_cache_ra_order` is the only function that acquires `filemap_invalidate_lock_shared` in the readahead path. Yes, it looks like `page_cache_ra_order` was introduced in this specific commit. Good.
Okay, let's see. `page_cache_ra_order` acquires `filemap_invalidate_lock_shared` to guard against concurrent truncations while allocating large folios. Now, let's dig into the commit that added `filemap_invalidate_lock_shared` to that function and look at the specifics.
|
| 21/2 |
2026/08/04 01:29 |
tool |
git-log |
8m
Args: map[CodeRegexp:filemap_invalidate_lock_shared Count:10 SourcePath:mm/readahead.c]
Results: map[Output:82a81a7352bc exfat: add iomap buffered I/O support
00608e34167f btrfs: use mapping shared locking for reading super block
f6fce9f17d9c ext2: Remove deprecated DAX support
f1a6cf44b344 fsverity: kick off hash readahead at data I/O submission time
b244c89a70b3 readahead: push invalidate_lock out of page_cache_ra_unbounded
777a8560fd29 lib/buildid: use __kernel_read() for sleepable context
ad41251c290d lib/buildid: implement sleepable build_id_parse() API
a7800aa80ea4 KVM: Add KVM_CREATE_GUEST_MEMFD ioctl() for guest-specific backing memory
3c21204818ae udf: Allocate blocks on write page fault
4008e2a0b01a zonefs: Reorganize code
]
|
| 22/2 |
2026/08/04 01:37 |
llm |
expert |
0m
Model:
Tokens:
input: 42542
output: 27
thoughts: 43
Thoughts: Okay, let's see what's going on here.
**Analyzing a Kernel Patch: `b244c89a70b3 readahead: push invalidate_lock out of page_cache_ra_unbounded`**
Hmm, this commit message, `b244c89a70b3 readahead: push invalidate_lock out of page_cache_ra_unbounded`, immediately piques my interest. It sounds like a change related to read-ahead functionality and, potentially, how it interacts with the page cache. The phrase "push invalidate_lock out of page_cache_ra_unbounded" strongly suggests a refactoring or optimization, perhaps moving a locking operation outside a particular function. I need to dive deeper. My gut tells me this could be significant, potentially addressing a performance bottleneck or a subtle concurrency issue. Time to dig into the commit itself and understand the motivations and ramifications of this change. Let's start by examining the code.
|
| 23/2 |
2026/08/04 01:37 |
tool |
git-show |
0m
Args:
Results: map[Output:commit b244c89a70b306e5a91852e00fd8cdd289714505
Author: Christoph Hellwig <hch@lst.de>
Date: Mon Feb 2 07:06:31 2026 +0100
readahead: push invalidate_lock out of page_cache_ra_unbounded
Require the invalidate_lock to be held over calls to
page_cache_ra_unbounded instead of acquiring it in this function.
This prepares for calling page_cache_ra_unbounded from ->readahead for
fsverity read-ahead.
Signed-off-by: Christoph Hellwig <hch@lst.de>
Reviewed-by: Jan Kara <jack@suse.cz>
Link: https://lore.kernel.org/r/20260202060754.270269-3-hch@lst.de
Signed-off-by: Eric Biggers <ebiggers@kernel.org>
diff --git a/fs/f2fs/file.c b/fs/f2fs/file.c
index da029fed4e5a..c9b9fcdd0cae 100644
--- a/fs/f2fs/file.c
+++ b/fs/f2fs/file.c
@@ -4418,7 +4418,9 @@ static int redirty_blocks(struct inode *inode, pgoff_t page_idx, int len)
pgoff_t redirty_idx = page_idx;
int page_len = 0, ret = 0;
+ filemap_invalidate_lock_shared(mapping);
page_cache_ra_unbounded(&ractl, len, 0);
+ filemap_invalidate_unlock_shared(mapping);
do {
folio = read_cache_folio(mapping, page_idx, NULL, NULL);
diff --git a/fs/verity/pagecache.c b/fs/verity/pagecache.c
index 1a88decace53..8e0d6fde802f 100644
--- a/fs/verity/pagecache.c
+++ b/fs/verity/pagecache.c
@@ -26,10 +26,13 @@ struct page *generic_read_merkle_tree_page(struct inode *inode, pgoff_t index,
(!IS_ERR(folio) && !folio_test_uptodate(folio))) {
DEFINE_READAHEAD(ractl, NULL, NULL, inode->i_mapping, index);
- if (!IS_ERR(folio))
+ if (!IS_ERR(folio)) {
folio_put(folio);
- else if (num_ra_pages > 1)
+ } else if (num_ra_pages > 1) {
+ filemap_invalidate_lock_shared(inode->i_mapping);
page_cache_ra_unbounded(&ractl, num_ra_pages, 0);
+ filemap_invalidate_unlock_shared(inode->i_mapping);
+ }
folio = read_mapping_folio(inode->i_mapping, index, NULL);
}
if (IS_ERR(folio))
diff --git a/mm/readahead.c b/mm/readahead.c
index b415c9969176..f43d03558e62 100644
--- a/mm/readahead.c
+++ b/mm/readahead.c
@@ -204,8 +204,9 @@ static struct folio *ractl_alloc_folio(struct readahead_control *ractl,
* not the function you want to call. Use page_cache_async_readahead()
* or page_cache_sync_readahead() instead.
*
- * Context: File is referenced by caller. Mutexes may be held by caller.
- * May sleep, but will not reenter filesystem to reclaim memory.
+ * Context: File is referenced by caller, and ractl->mapping->invalidate_lock
+ * must be held by the caller at least in shared mode. Mutexes may be held by
+ * caller. May sleep, but will not reenter filesystem to reclaim memory.
*/
void page_cache_ra_unbounded(struct readahead_control *ractl,
unsigned long nr_to_read, unsigned long lookahead_size)
@@ -228,9 +229,10 @@ void page_cache_ra_unbounded(struct readahead_control *ractl,
*/
unsigned int nofs = memalloc_nofs_save();
+ lockdep_assert_held(&mapping->invalidate_lock);
+
trace_page_cache_ra_unbounded(mapping->host, index, nr_to_read,
lookahead_size);
- filemap_invalidate_lock_shared(mapping);
index = mapping_align_index(mapping, index);
/*
@@ -300,7 +302,6 @@ void page_cache_ra_unbounded(struct readahead_control *ractl,
* will then handle the error.
*/
read_pages(ractl);
- filemap_invalidate_unlock_shared(mapping);
memalloc_nofs_restore(nofs);
}
EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
@@ -314,9 +315,9 @@ EXPORT_SYMBOL_GPL(page_cache_ra_unbounded);
static void do_page_cache_ra(struct readahead_control *ractl,
unsigned long nr_to_read, unsigned long lookahead_size)
{
- struct inode *inode = ractl->mapping->host;
+ struct address_space *mapping = ractl->mapping;
unsigned long index = readahead_index(ractl);
- loff_t isize = i_size_read(inode);
+ loff_t isize = i_size_read(mapping->host);
pgoff_t end_index; /* The last page we want to read */
if (isize == 0)
@@ -329,7 +330,9 @@ static void do_page_cache_ra(struct readahead_control *ractl,
if (nr_to_read > end_index - index)
nr_to_read = end_index - index + 1;
+ filemap_invalidate_lock_shared(mapping);
page_cache_ra_unbounded(ractl, nr_to_read, lookahead_size);
+ filemap_invalidate_unlock_shared(mapping);
}
/*
]
|
| 24/2 |
2026/08/04 01:37 |
llm |
expert |
0m
Model:
Tokens:
input: 44534
output: 21
thoughts: 367
Thoughts: **Analyzing the Implications of Commit `b244c89a70b3`**
Okay, so this commit, `b244c89a70b3 readahead: push invalidate_lock out of page_cache_ra_unbounded`, shifted `invalidate_lock` from `page_cache_ra_unbounded` to `do_page_cache_ra` and `page_cache_ra_order`. That's interesting, but wait a second⦠didn't `page_cache_ra_order` already have a lock related to invalidation, specifically `filemap_invalidate_lock_shared`, before this change? I should double-check that in `mm/readahead.c`.
Yep, there it is in `mm/readahead.c`:
```c
nofs = memalloc_nofs_save();
filemap_invalidate_lock_shared(mapping);
...
read_pages(ractl);
filemap_invalidate_unlock_shared(mapping);
memalloc_nofs_restore(nofs);
```
So `page_cache_ra_order` *does* grab `filemap_invalidate_lock_shared`, and `do_page_cache_ra` does as well. Now, thinking this through, `collapse_file` calls `page_cache_sync_readahead`, which in turn calls either `page_cache_ra_order` or `do_page_cache_ra`. That means `collapse_file` will acquire `filemap_invalidate_lock_shared` while holding folio locks! That could be a problem, given the potential for contention.
Now, where is `collapse_file` being called from? It's called from `madvise_collapse`. Is that the only caller of collapse_file? I'd better check for other callers of `collapse_file` to be sure.
|
| 25/2 |
2026/08/04 01:37 |
tool |
codesearch-find-references |
0m
Args:
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:collapse_scan_file SourceFile:mm/khugepaged.c SourceLine:2773]] TruncatedOutput:false]
|
| 26/2 |
2026/08/04 01:37 |
llm |
expert |
0m
Model:
Tokens:
input: 45414
output: 23
thoughts: 26
Thoughts: Here's a summary of my thought process:
**Focusing on Callers to Collapse_Scan_File**
Alright, so `collapse_scan_file` is the only function that's calling this particular piece of code. That's a key observation. Now, I need to understand what's happening within `collapse_scan_file`, as that's the sole point of interaction with this function. Time to investigate the context surrounding that function call and see what's going on! Knowing the callers of a method, especially when there's only one, can give a good hint about the code's intended use case.
|
| 27/2 |
2026/08/04 01:38 |
tool |
codesearch-find-references |
0m
Args: map[Name:collapse_scan_file]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:collapse_single_pmd SourceFile:mm/khugepaged.c SourceLine:2808]] TruncatedOutput:false]
|
| 28/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 45669
output: 24
thoughts: 10
Thoughts: Okay, here's my attempt at summarizing the thought process, tailored for an expert audience, and written in the first person:
**Analyzing `collapse_single_pmd` Callers**
Alright, let's break down this `collapse_single_pmd` situation. I need to understand where this function is being called from, what the context is, and what the potential implications are for performance or correctness. My immediate questions are:
* **Why are we collapsing a single PMD?** Typically, this hints at optimizing memory access or simplifying page table structures. What's the specific goal here? Is it for coalescing memory regions, dealing with huge pages, or something else entirely?
* **What's the caller's responsibility *before* calling?** Are there any preconditions that *must* be met? For instance, do we have to lock anything, ensure atomicity of certain operations, or have a specific page table structure set up beforehand? Understanding the setup is critical to ensuring the code path is safe.
* **What assumptions are being made by the caller about what `collapse_single_pmd` does?** If we are making any assumptions, they must be tested and reviewed. Are there any implicit dependencies?
* **What are the performance implications?** Collapsing PMDs can be time-consuming, especially if it involves moving data around or updating page table entries. I need to consider the overhead in this specific call site's use case to ensure itβs acceptable, and ideally, test it to find performance bottle necks.
* **Could this introduce any race conditions or concurrency issues?** If multiple threads might be interacting with the same memory regions, I need to thoroughly analyze the locking and synchronization mechanisms used around this call to prevent corruption. Deadlocks are also a concern.
* **What about error handling?** What happens if the collapse fails? Is the failure handled gracefully, or does it lead to a more severe problem? I need to ensure a robust error recovery process.
* **Is this caller the only place where we collapse single PMDs?** Looking at the codebase, I need to compare this call to similar call sites and see if there is any overlap in function or any possible improvement.
* **Are we dealing with any unusual architectures or memory management configurations?** Different architectures might have different page table layouts or hardware-specific considerations that could impact the correctness or efficiency of this operation.
* **Are there any potential side effects on other memory regions or page table entries?** Collapsing a PMD *could* affect other areas of the page table hierarchy, so I need to carefully consider the scope of the operation.
I'll start by tracing the call stack, examining the surrounding code in each caller, and looking for comments or documentation that sheds light on these questions. I'll probably also want to run some test cases to check that everything is acting as it should. Time to dig in!
|
| 29/2 |
2026/08/04 01:38 |
tool |
codesearch-find-references |
0m
Args: map[Name:collapse_single_pmd]
Results: map[References:[map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:collapse_scan_mm_slot SourceFile:mm/khugepaged.c SourceLine:2913] map[ReferenceKind:calls ReferencingEntityKind:function ReferencingEntityName:madvise_collapse SourceFile:mm/khugepaged.c SourceLine:3234]] TruncatedOutput:false]
|
| 30/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 46446
output: 39
thoughts: 1139
Thoughts: **Deadlock Analysis in the Linux Kernel: A Deep Dive**
Okay, let's break this down. My analysis starts with `collapse_single_pmd`. I've figured out it's called from both `madvise_collapse` and `collapse_scan_mm_slot`. Interesting... `collapse_scan_mm_slot` itself is triggered by `khugepaged_scan_mm_slot`, which feeds into `khugepaged_do_scan`, the core loop of the `khugepaged` kernel thread. So, this deadlock isn't just a simple isolated issue; the background memory management process, `khugepaged`, can cause it.
The process goes like this. `khugepaged` is continuously scanning memory, trying to coalesce smaller pages into huge pages, in the background. If it encounters a file-backed VMA during this scan, it calls `collapse_file`, which gets folio locks and acquires `filemap_invalidate_lock_shared`. That's where it gets interesting...
If *another* thread is busy with something like `ext4_truncate_failed_write` (or `ext4_punch_hole`, similar actions), it will hold `filemap_invalidate_lock` exclusively and will be waiting for a folio lock that `khugepaged` holds. We have a deadlock!
It looks like simply having `khugepaged` enabled, combined with standard file operations, creates a deadlock vulnerability.
However, `khugepaged` normally only scans VMAs marked with `MADV_HUGEPAGE`, or if configured to scan all VMAs. But `MADV_COLLAPSE` might be the direct trigger.
And, bingo! The syzkaller reproducer uses `MADV_COLLAPSE`!
```c
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x600000ul, /*advice=MADV_COLLAPSE*/0x19ul);
```
So, any unprivileged user can trigger this: map a file, call `MADV_COLLAPSE`, and concurrently do a write that fails due to space issues, or use `fallocate(PUNCH_HOLE)`. That triggers `ext4_truncate_failed_write`.
Wait, the reproducer uses an mmap, `MADV_HUGEPAGE`, then `MADV_COLLAPSE`:
```c
syscall(__NR_mmap, /*addr=*/0x20000000ul, /*len=*/0xb36000, /*prot=PROT_WRITE*/2ul, /*flags=MAP_STACK|MAP_POPULATE|MAP_FIXED|MAP_SHARED*/0x28011ul, /*fd=*/r[0], /*offset=*/0ul);
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x800000ul, /*advice=MADV_HUGEPAGE*/0xeul);
syscall(__NR_madvise, /*addr=*/0x20000000ul, /*len=*/0x600000ul, /*advice=MADV_COLLAPSE*/0x19ul);
```
And then writes to...`cgroup.controllers`? Oh, wait, the reproducer mounts an ext4 image using `syz_mount_image`.
```c
syz_mount_image(/*fs=*/0x200001c0, /*dir=*/0x20000340, /*flags=MS_POSIXACL|MS_RELATIME|MS_NOEXEC*/0x210008, /*opts=*/0x20000000, /*chdir=*/0xfc, /*size=*/0x56f, /*img=*/0x20003780);
```
`syz_mount_image` requires `CAP_SYS_ADMIN` in the initial user namespace, or in a user namespace.
Wait, is the bug specific to `ext4` or file systems? The core issue is this: `khugepaged` vs. `ext4_write_end`. Does it *require* a malicious image? The syzkaller reproducer *does* use one, to make triggering `ext4_truncate_failed_write` easier.
The write fails in the malicious ext4, which triggers `ext4_truncate_failed_write`.
Why does the write
|
| 31/2 |
2026/08/04 01:38 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/ext4/extents.c Name:ext4_punch_hole]
Results: map[SourceCode:4428: int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
4429: {
4430: struct inode *inode = file_inode(file);
4431: struct super_block *sb = inode->i_sb;
4432: ext4_lblk_t start_lblk, end_lblk;
4433: loff_t max_end = sb->s_maxbytes;
4434: loff_t end = offset + length;
4435: handle_t *handle;
4436: unsigned int credits;
4437: bool partial_zeroed = false;
4438: int ret;
4439:
4440: trace_ext4_punch_hole(inode, offset, length, 0);
4441: WARN_ON_ONCE(!inode_is_locked(inode));
4442:
4443: /*
4444: * For indirect-block based inodes, make sure that the hole within
4445: * one block before last range.
4446: */
4447: if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4448: max_end = EXT4_SB(sb)->s_bitmap_maxbytes - sb->s_blocksize;
4449:
4450: /* No need to punch hole beyond i_size */
4451: if (offset >= inode->i_size || offset >= max_end)
4452: return 0;
4453:
4454: /*
4455: * If the hole extends beyond i_size, set the hole to end after
4456: * the block that contains i_size to save pointless tail block zeroing.
4457: */
4458: if (end >= inode->i_size)
4459: end = round_up(inode->i_size, sb->s_blocksize);
4460: if (end > max_end)
4461: end = max_end;
4462: length = end - offset;
4463:
4464: ret = ext4_update_disksize_before_punch(inode, offset, length);
4465: if (ret)
4466: return ret;
4467:
4468: /* Now release the pages and zero block aligned part of pages*/
4469: ret = ext4_truncate_page_cache_block_range(inode, offset, end);
4470: if (ret)
4471: return ret;
4472:
4473: ret = ext4_zero_partial_blocks(inode, offset, length, &partial_zeroed);
4474: if (ret)
4475: return ret;
4476: if (((file->f_flags & O_SYNC) || IS_SYNC(inode)) && partial_zeroed) {
4477: ret = filemap_write_and_wait_range(inode->i_mapping, offset,
4478: end - 1);
4479: if (ret)
4480: return ret;
4481: }
4482:
4483: if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4484: credits = ext4_chunk_trans_extent(inode, 0);
4485: else
4486: credits = ext4_blocks_for_truncate(inode);
4487: handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4488: if (IS_ERR(handle)) {
4489: ret = PTR_ERR(handle);
4490: ext4_std_error(sb, ret);
4491: return ret;
4492: }
4493:
4494: /* If there are blocks to remove, do it */
4495: start_lblk = EXT4_B_TO_LBLK(inode, offset);
4496: end_lblk = end >> inode->i_blkbits;
4497:
4498: if (end_lblk > start_lblk) {
4499: ext4_lblk_t hole_len = end_lblk - start_lblk;
4500:
4501: ext4_fc_track_inode(handle, inode);
4502: ext4_check_map_extents_env(inode);
4503: down_write(&EXT4_I(inode)->i_data_sem);
4504: ext4_discard_preallocations(inode);
4505:
4506: ext4_es_remove_extent(inode, start_lblk, hole_len);
4507:
4508: if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4509: ret = ext4_ext_remove_space(inode, start_lblk,
4510: end_lblk - 1);
4511: else
4512: ret = ext4_ind_remove_space(handle, inode, start_lblk,
4513: end_lblk);
4514: if (ret) {
4515: up_write(&EXT4_I(inode)->i_data_sem);
4516: goto out_handle;
4517: }
4518:
4519: ext4_es_insert_extent(inode, start_lblk, hole_len, ~0,
4520: EXTENT_STATUS_HOLE, 0);
4521: up_write(&EXT4_I(inode)->i_data_sem);
4522: }
4523: ext4_fc_track_range(handle, inode, start_lblk, end_lblk);
4524:
4525: ret = ext4_mark_inode_dirty(handle, inode);
4526: if (unlikely(ret))
4527: goto out_handle;
4528:
4529: ext4_update_inode_fsync_trans(handle, inode, 1);
4530: if ((file->f_flags & O_SYNC) || IS_SYNC(inode))
4531: ext4_handle_sync(handle);
4532: out_handle:
4533: ext4_journal_stop(handle);
4534: return ret;
4535: }
SourceFile:fs/ext4/inode.c]
|
| 32/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 50453
output: 38
thoughts: 32
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**Tracing the Fallocate Call**
Right, so `ext4_punch_hole`... that's interesting. I know it's a key function for creating holes in a file's data. Now, the context is calling it from `ext4_fallocate`. That's not entirely surprising, but it's important to be explicit. Fallocate, of course, covers the general case for preallocating/deallocating file space, and punching holes is a major component of deallocating it, so it makes total sense. We need to follow the chain. Let's dig into `ext4_fallocate`. It's where the real logic is implemented, so we need to see how it's coordinating the hole punching operation, what the conditions are, and what other error handling is done during that call, etc. This is where the intricacies of the file system's block allocation and deallocation strategies are likely defined.
|
| 33/2 |
2026/08/04 01:38 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/ext4/extents.c Name:ext4_fallocate]
Results: map[SourceCode:4847: /*
4848: * preallocate space for a file. This implements ext4's fallocate file
4849: * operation, which gets called from sys_fallocate system call.
4850: * For block-mapped files, posix_fallocate should fall back to the method
4851: * of writing zeroes to the required new blocks (the same behavior which is
4852: * expected for file systems which do not support fallocate() system call).
4853: */
4854: long ext4_fallocate(struct file *file, int mode, loff_t offset, loff_t len)
4855: {
4856: struct inode *inode = file_inode(file);
4857: struct address_space *mapping = file->f_mapping;
4858: int ret;
4859:
4860: /*
4861: * Encrypted inodes can't handle collapse range or insert
4862: * range since we would need to re-encrypt blocks with a
4863: * different IV or XTS tweak (which are based on the logical
4864: * block number).
4865: */
4866: if (IS_ENCRYPTED(inode) &&
4867: (mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
4868: return -EOPNOTSUPP;
4869: /*
4870: * Don't allow writing zeroes if the underlying device does not
4871: * enable the unmap write zeroes operation.
4872: */
4873: if ((mode & FALLOC_FL_WRITE_ZEROES) &&
4874: !bdev_write_zeroes_unmap_sectors(inode->i_sb->s_bdev))
4875: return -EOPNOTSUPP;
4876:
4877: /* Return error if mode is not supported */
4878: if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
4879: FALLOC_FL_ZERO_RANGE | FALLOC_FL_COLLAPSE_RANGE |
4880: FALLOC_FL_INSERT_RANGE | FALLOC_FL_WRITE_ZEROES))
4881: return -EOPNOTSUPP;
4882:
4883: inode_lock(inode);
4884: ret = ext4_convert_inline_data(inode);
4885: if (ret)
4886: goto out_inode_lock;
4887:
4888: /* Wait all existing dio workers, newcomers will block on i_rwsem */
4889: inode_dio_wait(inode);
4890:
4891: ret = file_modified(file);
4892: if (ret)
4893: goto out_inode_lock;
4894:
4895: if ((mode & FALLOC_FL_MODE_MASK) == FALLOC_FL_ALLOCATE_RANGE) {
4896: ret = ext4_do_fallocate(file, offset, len, mode);
4897: goto out_inode_lock;
4898: }
4899:
4900: /*
4901: * Follow-up operations will drop page cache, hold invalidate lock
4902: * to prevent page faults from reinstantiating pages we have
4903: * released from page cache.
4904: */
4905: filemap_invalidate_lock(mapping);
4906:
4907: ret = ext4_break_layouts(inode);
4908: if (ret)
4909: goto out_invalidate_lock;
4910:
4911: switch (mode & FALLOC_FL_MODE_MASK) {
4912: case FALLOC_FL_PUNCH_HOLE:
4913: ret = ext4_punch_hole(file, offset, len);
4914: break;
4915: case FALLOC_FL_COLLAPSE_RANGE:
4916: ret = ext4_collapse_range(file, offset, len);
4917: break;
4918: case FALLOC_FL_INSERT_RANGE:
4919: ret = ext4_insert_range(file, offset, len);
4920: break;
4921: case FALLOC_FL_ZERO_RANGE:
4922: case FALLOC_FL_WRITE_ZEROES:
4923: ret = ext4_zero_range(file, offset, len, mode);
4924: break;
4925: default:
4926: ret = -EOPNOTSUPP;
4927: }
4928:
4929: out_invalidate_lock:
4930: filemap_invalidate_unlock(mapping);
4931: out_inode_lock:
4932: inode_unlock(inode);
4933: return ret;
4934: }
SourceFile:fs/ext4/extents.c]
|
| 34/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 52141
output: 41
thoughts: 449
Thoughts: **Deadlock Discovery in ext4 and MADV_COLLAPSE**
Alright, I've got it! `ext4_fallocate`'s `PUNCH_HOLE` operation acquires the `filemap_invalidate_lock(mapping)` exclusively, no question. Then, it dives into `ext4_punch_hole`, cascading down to `ext4_truncate_page_cache_block_range`, then `truncate_pagecache_range`, ultimately locking folios. Meanwhile, `madvise(MADV_COLLAPSE)` also locks folios and *then* tries to grab `filemap_invalidate_lock_shared`. Bingo β we've got a classic ABBA deadlock situation brewing!
The real question is, can an unprivileged user trigger this mess? Absolutely. Here's the recipe:
1. Open a file on an ext4 filesystem.
2. `mmap` that file.
3. Thread 1: Execute `madvise(MADV_COLLAPSE)` on the mapped region.
4. Thread 2: Call `fallocate(PUNCH_HOLE)` on the same file.
Deadlock, guaranteed!
Now, does `MADV_COLLAPSE` have any pre-conditions? Does it require `CONFIG_TRANSPARENT_HUGEPAGE`? Yes, it does. Thankfully, THP is a default setting on most recent Linux systems. And yep, `MADV_COLLAPSE` is available to unprivileged users. I need to make sure I am correct, does it require `CONFIG_READ_ONLY_THP_FOR_FS`? Let's check `mapping_pmd_folio_support(mapping)` in `collapse_file`.
```c
VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
```
Aha! `mapping_pmd_folio_support` checks if the filesystem supports THP. With a little poking around, I see ext4 supports THP for read-only files if `CONFIG_READ_ONLY_THP_FOR_FS` is enabled. Wait, does ext4 support THP for read-write files now? Let me double-check `mapping_pmd_folio_support`.
|
| 35/2 |
2026/08/04 01:38 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:include/linux/pagemap.h Name:mapping_pmd_folio_support]
Results: map[SourceCode: 528: static inline bool mapping_pmd_folio_support(const struct address_space *mapping)
529: {
530: /* AS_FOLIO_ORDER is only reasonable for pagecache folios */
531: VM_WARN_ON_ONCE((unsigned long)mapping & FOLIO_MAPPING_ANON);
532:
533: return mapping_min_folio_order(mapping) <= PMD_ORDER &&
534: mapping_max_folio_order(mapping) >= PMD_ORDER;
535: }
SourceFile:include/linux/pagemap.h]
|
| 36/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 53310
output: 21
thoughts: 64
Thoughts: **Investigating Ext4 and Large Folios**
Okay, so I'm looking at this `mapping_max_folio_order(mapping)` function, and it's suddenly clear that it depends on the results from the `mapping_set_large_folios(mapping)` function. My intuition tells me this probably has to do with how the filesystem handles memory allocation and I need to figure out how `mapping_set_large_folios` is being used.
The question then becomes, does the ext4 filesystem even *support* large folios? Let me do a quick mental check... yes, it does, I'm pretty sure that's supported. Time to verify.
Now, where exactly is that function called within the ext4 code? I need to track down all the instances where `mapping_set_large_folios` is invoked. It looks like I need to dive deeper into the code to trace the call paths in order to see how large folios are set.
|
| 37/2 |
2026/08/04 01:38 |
tool |
grepper |
0m
Args: map[Expression:mapping_set_large_folios]
Results: map[Output:Documentation/filesystems/iomap/operations.rst=193=Filesystems wishing to turn on large folios in the pagecache should call
Documentation/filesystems/iomap/operations.rst:194:``mapping_set_large_folios`` when initializing the incore inode.
Documentation/filesystems/iomap/operations.rst-195-
--
fs/afs/inode.c=63=static int afs_inode_init_from_status(struct afs_operation *op,
--
fs/afs/inode.c-101- inode->i_mapping->a_ops = &afs_file_aops;
fs/afs/inode.c:102: mapping_set_large_folios(inode->i_mapping);
fs/afs/inode.c-103- break;
--
fs/erofs/inode.c=224=static int erofs_fill_inode(struct inode *inode)
--
fs/erofs/inode.c-257-
fs/erofs/inode.c:258: mapping_set_large_folios(inode->i_mapping);
fs/erofs/inode.c-259- aops = erofs_get_aops(inode);
--
fs/nfs/inode.c=430=nfs_fhget(struct super_block *sb, struct nfs_fh *fh, struct nfs_fattr *fattr)
--
fs/nfs/inode.c-475- nfs_inode_init_regular(nfsi);
fs/nfs/inode.c:476: mapping_set_large_folios(inode->i_mapping);
fs/nfs/inode.c-477- } else if (S_ISDIR(inode->i_mode)) {
--
fs/smb/client/inode.c=58=static void cifs_set_ops(struct inode *inode)
--
fs/smb/client/inode.c-89- inode->i_data.a_ops = &cifs_addr_ops;
fs/smb/client/inode.c:90: mapping_set_large_folios(inode->i_mapping);
fs/smb/client/inode.c-91- break;
--
fs/zonefs/super.c=627=static struct inode *zonefs_get_file_inode(struct inode *dir,
--
fs/zonefs/super.c-668- inode->i_mapping->a_ops = &zonefs_file_aops;
fs/zonefs/super.c:669: mapping_set_large_folios(inode->i_mapping);
fs/zonefs/super.c-670-
--
include/linux/pagemap.h=438=static inline void mapping_set_folio_min_order(struct address_space *mapping,
--
include/linux/pagemap.h-444-/**
include/linux/pagemap.h:445: * mapping_set_large_folios() - Indicate the file supports large folios.
include/linux/pagemap.h-446- * @mapping: The address space of the file.
--
include/linux/pagemap.h-454- */
include/linux/pagemap.h:455:static inline void mapping_set_large_folios(struct address_space *mapping)
include/linux/pagemap.h-456-{
--
mm/khugepaged.c=2242=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
--
mm/khugepaged.c-2257- *
mm/khugepaged.c:2258: * TODO: once shmem always calls mapping_set_large_folios() on its
mm/khugepaged.c-2259- * mapping, the shmem check can be removed.
--
mm/shmem.c=2999=static struct inode *__shmem_get_inode(struct mnt_idmap *idmap,
--
mm/shmem.c-3042- mapping_set_unevictable(inode->i_mapping);
mm/shmem.c:3043: mapping_set_large_folios(inode->i_mapping);
mm/shmem.c-3044-
]
|
| 38/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 54684
output: 23
thoughts: 41
Thoughts: Okay, here's my take on those thoughts, framed as my own:
**Ext4 and Folio Management - A Quick Check**
Hold on a second... Did I just read that ext4 *doesn't* leverage `mapping_set_large_folios`? That's unexpected. My understanding was that they were pretty aggressive about folio usage for performance. I need to double-check that immediately. It seems like it's a critical component of modern filesystem performance.
Okay, let's see...if not `mapping_set_large_folios`, then what are they *actually* using? Are they employing `mapping_set_folio_order_range` or a comparable mechanism to achieve large folio allocations and management within ext4? I need to dig into the code and see what their actual strategies are. I'm sure there's a reason for their approach and need to understand it fully. This may change my entire perspective on how to tackle the project I am currently assigned to.
|
| 39/2 |
2026/08/04 01:38 |
tool |
grepper |
0m
Args: map[Expression:mapping_set_folio_order_range]
Results: map[Output:fs/btrfs/btrfs_inode.h=498=static inline void btrfs_set_inode_mapping_order(struct btrfs_inode *inode)
--
fs/btrfs/btrfs_inode.h-502-
fs/btrfs/btrfs_inode.h:503: mapping_set_folio_order_range(inode->vfs_inode.i_mapping,
fs/btrfs/btrfs_inode.h-504- inode->root->fs_info->block_min_order,
--
fs/ext4/inode.c=5254=void ext4_set_inode_mapping_order(struct inode *inode)
--
fs/ext4/inode.c-5269-
fs/ext4/inode.c:5270: mapping_set_folio_order_range(inode->i_mapping, min_order, max_order);
fs/ext4/inode.c-5271-}
--
include/linux/pagemap.h=395=static inline size_t mapping_max_folio_size_supported(void)
--
include/linux/pagemap.h-402-/*
include/linux/pagemap.h:403: * mapping_set_folio_order_range() - Set the orders supported by a file.
include/linux/pagemap.h-404- * @mapping: The address space of the file.
--
include/linux/pagemap.h-417- */
include/linux/pagemap.h:418:static inline void mapping_set_folio_order_range(struct address_space *mapping,
include/linux/pagemap.h-419- unsigned int min,
--
include/linux/pagemap.h=438=static inline void mapping_set_folio_min_order(struct address_space *mapping,
--
include/linux/pagemap.h-440-{
include/linux/pagemap.h:441: mapping_set_folio_order_range(mapping, min, MAX_PAGECACHE_ORDER);
include/linux/pagemap.h-442-}
--
include/linux/pagemap.h=455=static inline void mapping_set_large_folios(struct address_space *mapping)
include/linux/pagemap.h-456-{
include/linux/pagemap.h:457: mapping_set_folio_order_range(mapping, 0, MAX_PAGECACHE_ORDER);
include/linux/pagemap.h-458-}
]
|
| 40/2 |
2026/08/04 01:38 |
llm |
expert |
0m
Model:
Tokens:
input: 55611
output: 36
thoughts: 1790
Thoughts: **Deadlock Analysis: khugepaged, MADV_COLLAPSE, and File Truncation**
Okay, here's what I've got. I've confirmed that Ext4, and by implication, other filesystems supporting large folios, call `mapping_set_folio_order_range` β so they *can* use large folios, and `mapping_pmd_folio_support` will confirm support for PMD_ORDER folios. This means `MADV_COLLAPSE` *can* call `collapse_file` on Ext4 (and similar filesystems).
The deadlock scenario boils down to this:
* **Thread 1 (Truncating Thread - e.g., `fallocate(PUNCH_HOLE)` or during `ext4_write_end` -> `ext4_truncate_failed_write`)**: This thread exclusively grabs `filemap_invalidate_lock(mapping)` and *then* attempts to acquire `folio_lock(folio)`.
* **Thread 2 (`MADV_COLLAPSE` or `khugepaged`)**: This thread first grabs `folio_lock(folio)` (within `collapse_file`) and *then* tries to get `filemap_invalidate_lock_shared(mapping)` (within `page_cache_sync_readahead` -> `page_cache_ra_order`).
This is a classic ABBA deadlock. And the implications are significant.
This deadlock *can* be triggered by an unprivileged user. A user just needs to open a file, mmap it, and then run `madvise(MADV_COLLAPSE)` concurrently with `fallocate(PUNCH_HOLE)`. Because `fallocate(PUNCH_HOLE)` is unprivileged, this represents a local Denial of Service (DoS) vulnerability. Now, is there any possibility of privilege escalation or memory corruption? Not really, deadlocks are typically just DoS, leading to threads hanging.
Specifically, if the hung threads hold critical locks (like `inode_lock` or `filemap_invalidate_lock`), other processes trying to access that file will also hang. The `filemap_invalidate_lock` is per-mapping (per-inode), so it will only hang operations on *that* inode. But there is a worse scenario - `khugepaged` can get involved, and this is where things get really bad!
If `khugepaged` (which is a single, global kernel thread, or one per NUMA node) deadlocks, then *the entire system's* THP collapsing stops working! This means no more huge pages will be collapsed for *any* process. This is a severe system-wide performance degradation, and it's a permanent hang of the `khugepaged` thread. User tasks will also hang in the D state (uninterruptible sleep). This leads to the hung task detector firing, printing warnings, and if `kernel.hung_task_panic` is enabled, the system will *panic*! Many production systems set `kernel.hung_task_panic = 1` to recover from these situations. So, at best, this leads to a permanent hang, at worst, a reliable system crash (DoS).
My analysis now confirms `khugepaged` *can* trigger this. It scans memory, calls `collapse_file`, and if it encounters a file mapping being concurrently truncated or hole-punched, it deadlocks with the truncating thread. The truncating thread *could* be a normal user process. So an unprivileged user can intentionally deadlock `khugepaged` by:
1. Creating a file.
2. Mapping it with `MAP_SHARED`.
3. Advising it with `MADV_HUGEPAGE`.
4. Continuously doing `fallocate(PUNCH_HOLE)` on it.
When `khugepaged` scans the VMA, it will lock a folio and call `page_cache_sync_readahead`, deadlocking with the `fallocate` thread. This permanently hangs `khugepaged`.
My check confirmed `collapse_file` *does* call `page_cache_sync_readahead`, exactly as used by `MADV_COLLAPSE`. And `page_cache_sync_readahead` calls `page_cache_sync_ra`, which eventually calls `page_cache_ra_order` *or* `do_page_cache_ra`. The critical thing is, `do_page_cache_ra` *also* grabs `filemap_invalidate_lock_shared`. It doesn't matter if we're using large folios or not!
Therefore, this deadlock applies to *any* filesystem using `filemap_invalidate_lock`
|
| 41/2 |
2026/08/04 01:39 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/truncate.c Name:truncate_inode_pages_range]
Results: map[SourceCode: 342: /**
343: * truncate_inode_pages_range - truncate range of pages specified by start & end byte offsets
344: * @mapping: mapping to truncate
345: * @lstart: offset from which to truncate
346: * @lend: offset to which to truncate (inclusive)
347: *
348: * Truncate the page cache, removing the pages that are between
349: * specified offsets (and zeroing out partial pages
350: * if lstart or lend + 1 is not page aligned).
351: *
352: * Truncate takes two passes - the first pass is nonblocking. It will not
353: * block on page locks and it will not block on writeback. The second pass
354: * will wait. This is to prevent as much IO as possible in the affected region.
355: * The first pass will remove most pages, so the search cost of the second pass
356: * is low.
357: *
358: * We pass down the cache-hot hint to the page freeing code. Even if the
359: * mapping is large, it is probably the case that the final pages are the most
360: * recently touched, and freeing happens in ascending file offset order.
361: *
362: * Note that since ->invalidate_folio() accepts range to invalidate
363: * truncate_inode_pages_range is able to handle cases where lend + 1 is not
364: * page aligned properly.
365: */
366: void truncate_inode_pages_range(struct address_space *mapping,
367: loff_t lstart, uoff_t lend)
368: {
369: pgoff_t start; /* inclusive */
370: pgoff_t end; /* exclusive */
371: struct folio_batch fbatch;
372: pgoff_t indices[FOLIO_BATCH_SIZE];
373: pgoff_t index;
374: int i;
375: struct folio *folio;
376: bool same_folio;
377:
378: if (mapping_empty(mapping))
379: return;
380:
381: /*
382: * 'start' and 'end' always covers the range of pages to be fully
383: * truncated. Partial pages are covered with 'partial_start' at the
384: * start of the range and 'partial_end' at the end of the range.
385: * Note that 'end' is exclusive while 'lend' is inclusive.
386: */
387: start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
388: if (lend == -1)
389: /*
390: * lend == -1 indicates end-of-file so we have to set 'end'
391: * to the highest possible pgoff_t and since the type is
392: * unsigned we're using -1.
393: */
394: end = -1;
395: else
396: end = (lend + 1) >> PAGE_SHIFT;
397:
398: folio_batch_init(&fbatch);
399: index = start;
400: while (index < end && find_lock_entries(mapping, &index, end - 1,
401: &fbatch, indices)) {
402: truncate_folio_batch_exceptionals(mapping, &fbatch, indices);
403: for (i = 0; i < folio_batch_count(&fbatch); i++)
404: truncate_cleanup_folio(fbatch.folios[i]);
405: delete_from_page_cache_batch(mapping, &fbatch);
406: for (i = 0; i < folio_batch_count(&fbatch); i++)
407: folio_unlock(fbatch.folios[i]);
408: folio_batch_release(&fbatch);
409: cond_resched();
410: }
411:
412: same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
413: folio = __filemap_get_folio(mapping, lstart >> PAGE_SHIFT, FGP_LOCK, 0);
414: if (!IS_ERR(folio)) {
415: same_folio = lend < folio_next_pos(folio);
416: if (!truncate_inode_partial_folio(folio, lstart, lend)) {
417: start = folio_next_index(folio);
418: if (same_folio)
419: end = folio->index;
420: }
421: folio_unlock(folio);
422: folio_put(folio);
423: folio = NULL;
424: }
425:
426: if (!same_folio) {
427: folio = __filemap_get_folio(mapping, lend >> PAGE_SHIFT,
428: FGP_LOCK, 0);
429: if (!IS_ERR(folio)) {
430: if (!truncate_inode_partial_folio(folio, lstart, lend))
431: end = folio->index;
432: folio_unlock(folio);
433: folio_put(folio);
434: }
435: }
436:
437: index = start;
438: while (index < end) {
439: cond_resched();
440: if (!find_get_entries(mapping, &index, end - 1, &fbatch,
441: indices)) {
442: /* If all gone from start onwards, we're done */
443: if (index == start)
444: break;
445: /* Otherwise restart to make sure all gone */
446: index = start;
447: continue;
448: }
449:
450: for (i = 0; i < folio_batch_count(&fbatch); i++) {
451: struct folio *folio = fbatch.folios[i];
452:
453: /* We rely upon deletion not changing folio->index */
454:
455: if (xa_is_value(folio))
456: continue;
457:
458: folio_lock(folio);
459: VM_BUG_ON_FOLIO(!folio_contains(folio, indices[i]), folio);
460: folio_wait_writeback(folio);
461: truncate_inode_folio(mapping, folio);
462: folio_unlock(folio);
463: }
464: truncate_folio_batch_exceptionals(mapping, &fbatch, indices);
465: folio_batch_release(&fbatch);
466: }
467: }
SourceFile:mm/truncate.c]
|
| 42/2 |
2026/08/04 01:39 |
llm |
expert |
0m
Model:
Tokens:
input: 60470
output: 35
thoughts: 395
Thoughts: **My Analysis of a Potential Deadlock Vulnerability**
Okay, so `truncate_inode_pages_range` is calling `find_lock_entries`, which, as I understand it, locks folios, and then it also calls `__filemap_get_folio` with the `FGP_LOCK` flag, locking folios *again*. The critical thing here is that `truncate_inode_pages_range` is called while holding `filemap_invalidate_lock(mapping)` exclusively!
This means the intended lock ordering is pretty clear: `filemap_invalidate_lock` must come *before* the `folio_lock`. The problem is that `collapse_file` seems to be violating this order. It's holding the `folio_lock` and then calling `page_cache_sync_readahead`, which *acquires* the `filemap_invalidate_lock_shared`. That's a classic lock-ordering violation, a deadlock just waiting to happen.
So, it's a local DoS, which means it can be triggered without network access. Is there anything else that can be done from this? No, it's just a deadlock. Could it be triggered from within a user namespace? Yes, and it's even worse than I thought. This doesn't require any capabilities, meaning an unprivileged process can trigger it directly. And, it's a host kernel bug, so it can't be triggered from a VM guest. I can rule out network-based exploitation too, since it depends on local execution using `mmap`, `madvise`, or `fallocate`.
Now, could this be triggered by a malicious filesystem? Yes, a malicious filesystem could easily craft a situation to trigger `ext4_truncate_failed_write` and thus trigger the deadlock. But it's not strictly necessary. `fallocate(PUNCH_HOLE)` would work on any normal filesystem, making the "Malicious Filesystem Trigger" a potential vector but not the primary one. And I should remember, this is a core MM problem, in `khugepaged.c` or `readahead.c`, not specifically an ext4 bug. Ext4 is just *one* filesystem that uses `filemap_invalidate_lock` and also supports THP.
Wait a second... does `shmem` also use `filemap_invalidate_lock`? I need to check `shmem_punch_hole`. This could be a much broader issue than I initially thought.
|
| 43/2 |
2026/08/04 01:39 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:mm/shmem.c Name:shmem_fallocate]
Results: map[SourceCode:3597: static long shmem_fallocate(struct file *file, int mode, loff_t offset,
3598: loff_t len)
3599: {
3600: struct inode *inode = file_inode(file);
3601: struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
3602: struct shmem_inode_info *info = SHMEM_I(inode);
3603: struct shmem_falloc shmem_falloc;
3604: pgoff_t start, index, end, undo_fallocend;
3605: int error;
3606:
3607: if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
3608: return -EOPNOTSUPP;
3609:
3610: inode_lock(inode);
3611:
3612: if (info->flags & SHMEM_F_MAPPING_FROZEN) {
3613: error = -EPERM;
3614: goto out;
3615: }
3616:
3617: if (mode & FALLOC_FL_PUNCH_HOLE) {
3618: struct address_space *mapping = file->f_mapping;
3619: loff_t unmap_start = round_up(offset, PAGE_SIZE);
3620: loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
3621: DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
3622:
3623: /* protected by i_rwsem */
3624: if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
3625: error = -EPERM;
3626: goto out;
3627: }
3628:
3629: shmem_falloc.waitq = &shmem_falloc_waitq;
3630: shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
3631: shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
3632: spin_lock(&inode->i_lock);
3633: inode->i_private = &shmem_falloc;
3634: spin_unlock(&inode->i_lock);
3635:
3636: if ((u64)unmap_end > (u64)unmap_start)
3637: unmap_mapping_range(mapping, unmap_start,
3638: 1 + unmap_end - unmap_start, 0);
3639: shmem_truncate_range(inode, offset, offset + len - 1);
3640: /* No need to unmap again: hole-punching leaves COWed pages */
3641:
3642: spin_lock(&inode->i_lock);
3643: inode->i_private = NULL;
3644: wake_up_all(&shmem_falloc_waitq);
3645: WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
3646: spin_unlock(&inode->i_lock);
3647: error = 0;
3648: goto out;
3649: }
3650:
3651: /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
3652: error = inode_newsize_ok(inode, offset + len);
3653: if (error)
3654: goto out;
3655:
3656: if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
3657: error = -EPERM;
3658: goto out;
3659: }
3660:
3661: start = offset >> PAGE_SHIFT;
3662: end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
3663: /* Try to avoid a swapstorm if len is impossible to satisfy */
3664: if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
3665: error = -ENOSPC;
3666: goto out;
3667: }
3668:
3669: shmem_falloc.waitq = NULL;
3670: shmem_falloc.start = start;
3671: shmem_falloc.next = start;
3672: shmem_falloc.nr_falloced = 0;
3673: shmem_falloc.nr_unswapped = 0;
3674: spin_lock(&inode->i_lock);
3675: inode->i_private = &shmem_falloc;
3676: spin_unlock(&inode->i_lock);
3677:
3678: /*
3679: * info->fallocend is only relevant when huge pages might be
3680: * involved: to prevent split_huge_page() freeing fallocated
3681: * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
3682: */
3683: undo_fallocend = info->fallocend;
3684: if (info->fallocend < end)
3685: info->fallocend = end;
3686:
3687: for (index = start; index < end; ) {
3688: struct folio *folio;
3689:
3690: /*
3691: * Check for fatal signal so that we abort early in OOM
3692: * situations. We don't want to abort in case of non-fatal
3693: * signals as large fallocate can take noticeable time and
3694: * e.g. periodic timers may result in fallocate constantly
3695: * restarting.
3696: */
3697: if (fatal_signal_pending(current))
3698: error = -EINTR;
3699: else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
3700: error = -ENOMEM;
3701: else
3702: error = shmem_get_folio(inode, index, offset + len,
3703: &folio, SGP_FALLOC);
3704: if (error) {
3705: info->fallocend = undo_fallocend;
3706: /* Remove the !uptodate folios we added */
3707: if (index > start) {
3708: shmem_undo_range(inode,
3709: (loff_t)start << PAGE_SHIFT,
3710: ((loff_t)index << PAGE_SHIFT) - 1, true);
3711: }
3712: goto undone;
3713: }
3714:
3715: /*
3716: * Here is a more important optimization than it appears:
3717: * a second SGP_FALLOC on the same large folio will clear it,
3718: * making it uptodate and un-undoable if we fail later.
3719: */
3720: index = folio_next_index(folio);
3721: /* Beware 32-bit wraparound */
3722: if (!index)
3723: index--;
3724:
3725: /*
3726: * Inform shmem_writeout() how far we have reached.
3727: * No need for lock or barrier: we have the page lock.
3728: */
3729: if (!folio_test_uptodate(folio))
3730: shmem_falloc.nr_falloced += index - shmem_falloc.next;
3731: shmem_falloc.next = index;
3732:
3733: /*
3734: * If !uptodate, leave it that way so that freeable folios
3735: * can be recognized if we need to rollback on error later.
3736: * But mark it dirty so that memory pressure will swap rather
3737: * than free the folios we are allocating (and SGP_CACHE folios
3738: * might still be clean: we now need to mark those dirty too).
3739: */
3740: folio_mark_dirty(folio);
3741: folio_unlock(folio);
3742: folio_put(folio);
3743: cond_resched();
3744: }
3745:
3746: if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
3747: i_size_write(inode, offset + len);
3748: undone:
3749: spin_lock(&inode->i_lock);
3750: inode->i_private = NULL;
3751: spin_unlock(&inode->i_lock);
3752: out:
3753: if (!error)
3754: file_modified(file);
3755: inode_unlock(inode);
3756: return error;
3757: }
SourceFile:mm/shmem.c]
|
| 44/2 |
2026/08/04 01:39 |
llm |
expert |
0m
Model:
Tokens:
input: 64048
output: 66
thoughts: 1314
Thoughts: **Deadlock Analysis in `collapse_file` and Filesystem Operations**
Okay, so initially I was thinking this deadlock might involve `shmem_fallocate`, but wait, no, `shmem_fallocate` doesn't use `filemap_invalidate_lock`. It just uses `inode_lock`. So this specific deadlock isn't relevant there. This is a problem for filesystems that use `filemap_invalidate_lock` during truncation or hole-punching. That's ext4, XFS, Btrfs, and F2FS, among others. `collapse_file` *does* check `mapping_pmd_folio_support` for non-shmem files, so the vulnerability exists on these common filesystems.
Let me double-check how `collapse_file` handles folio locks and `page_cache_sync_readahead`. I need to be sure it *doesn't* release the folio locks before the readahead. Nope. It doesn't. It adds folios to the `pagelist` and *keeps* the locks held. If it hits a missing folio, the code directly calls `page_cache_sync_readahead` *while holding those locks*.
So the deadlock is real, and potentially, it's very easy to trigger by unprivileged users.
My analysis dimensions are:
* **Exploitable:** This isn't exploitable for privilege escalation or memory corruption. It's a straight-up deadlock, a Denial of Service (DoS) vulnerability.
* **Denial of Service:** Yes. It permanently hangs the `khugepaged` thread and any threads trying to access the affected file. If the system is configured with `kernel.hung_task_panic`, it results in a system crash.
* **Accessible From Unprivileged Processes:** Yes, both `MADV_COLLAPSE` and `fallocate` are accessible to unprivileged users, making this significantly more concerning.
* **Accessible From User Namespaces:** Yes, same as above.
* **VM Guest Trigger:** No, this is a host kernel issue.
* **VM Host Trigger in The Confidential Computing Context:** No.
* **Ethernet Network Trigger:** No.
* **Other Remote Trigger:** No.
* **Peripheral Trigger:** No.
* **Malicious Filesystem Trigger:** Actually, the syzkaller reproducer uses a malicious filesystem image, but `fallocate` is sufficient to trigger this. I will keep this as false, as the primary trigger is local syscalls and is not a bug in filesystem parsing.
Can this be triggered over a network with a network service writing to a file, and a user calls `MADV_COLLAPSE`? No, because `madvise` requires local code execution.
Let's review the lock ordering. First, `filemap_invalidate_lock`, then `folio_lock`. `collapse_file` does it backward, grabbing `folio_lock` for the folios it's collapsing, *then* calling `page_cache_sync_readahead`, which wants `filemap_invalidate_lock_shared`. This is a clear lock inversion.
Okay, final assessment: The bug is a deadlock between `collapse_file` (handling `MADV_COLLAPSE` and THP collapsing) and filesystem operations that modify the file size, like `fallocate` with `PUNCH_HOLE`, `truncate`, or failed writes. `collapse_file` locks folios sequentially and adds them to a list. If a missing folio is found, it calls `page_cache_sync_readahead`, which needs the shared `filemap_invalidate_lock`. However, filesystem operations like `fallocate(PUNCH_HOLE)` or `truncate` get the exclusive `filemap_invalidate_lock` first and then try to lock the folios. This causes an ABBA deadlock: a thread holding `filemap_invalidate_lock` waiting for a folio lock and another thread holding a folio lock, waiting for the shared `filemap_invalidate_lock`.
An unprivileged user can trigger this. Map a file. `madvise(MADV_COLLAPSE)` on it. Concurrently, call `fallocate(PUNCH_HOLE)` or cause a write to fail.
The impact is local DoS. It hangs tasks and the `khugepaged` thread. If `kernel.hung_task_panic` is enabled, it crashes the system. No privilege escalation, just DoS.
I am ready to `set-results`.
|
| 45/2 |
2026/08/04 01:39 |
tool |
set-results |
0m
Args: map[DenialOfService:true Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:true UserNamespace:true VMGuestTrigger:false VMHostTrigger:false]
Results: map[DenialOfService:true Exploitable:false FilesystemTrigger:false NetworkTrigger:false PeripheralTrigger:false RemoteTrigger:false Unprivileged:true UserNamespace:true VMGuestTrigger:false VMHostTrigger:false]
|
| 46/2 |
2026/08/04 01:39 |
llm |
expert |
0m
Model:
Tokens:
input: 66469
output: 776
thoughts: 381
Thoughts: **Final Response Generation: Thoughts**
Okay, the results are in, and it's time to craft the final response. My analysis of the bug is complete, and I've got a clear picture of what's going on.
Here's the gist of it: We've got an ABBA deadlock scenario, a classic, really. The core issue is the conflict between `filemap_invalidate_lock` and `folio_lock`. I've broken down the key players:
* **Bug Mechanism:** The problem boils down to a classic ABBA deadlock between `filemap_invalidate_lock` and `folio_lock`.
* **Thread 1 (Filesystem Operation):** This thread is running some typical filesystem operation like `fallocate` or `truncate`. It grabs the `filemap_invalidate_lock` in exclusive mode first, then iterates through folios, locking each `folio_lock` as it goes. Think `truncate_inode_pages_range`.
* **Thread 2 (Memory Management):** This is where it gets interesting. We've got something like `MADV_COLLAPSE` or `khugepaged` operations, and they're going through `collapse_file()`. This thread locks folios in the THP range individually. The kicker is, if it hits a missing folio, it kicks off `page_cache_sync_readahead()`, and that's the trouble. That call tries to acquire `filemap_invalidate_lock_shared` (via `page_cache_ra_order()` or `do_page_cache_ra()`).
* **Deadlock:** The perfect storm. Thread 2 is holding a `folio_lock` and is waiting for `filemap_invalidate_lock_shared`. At the same time, Thread 1 is holding the `filemap_invalidate_lock` exclusively and is stuck waiting for the *same* `folio_lock`. Boom - deadlock.
* **Impact:** This isn't just a theoretical issue. This leads to a local Denial of Service (DoS). Unprivileged users can hit this by running concurrent `madvise(MADV_COLLAPSE)` and `fallocate(PUNCH_HOLE)` operations on a file. This locks up those specific tasks indefinitely, and it even takes down the global `khugepaged` kernel thread. If `kernel.hung_task_panic` is enabled, we're talking a full-blown system crash.
* **Exploitability:** The good news (if you can call it that) is that this isn't a memory corruption vulnerability. This is a deadlock, meaning no privilege escalation or arbitrary code execution here. But the DoS is a serious concern.
Everything checks out. I've got a clear, concise understanding of this problem. Time to generate the response.
|
| 47/1 |
2026/08/04 01:39 |
action |
format-explanation |
0m
Results: map[Explanation:**Bug Analysis:**
The bug report describes a deadlock (hung tasks) involving two threads. The
lockdep output and stack traces reveal a classic ABBA lock inversion between the
`filemap_invalidate_lock` and the `folio_lock` (page lock).
1. **Thread 1 (Filesystem operation, e.g., `ext4_truncate_failed_write` or
`fallocate`)**:
Filesystem operations that truncate a file or punch a hole (like
`fallocate(PUNCH_HOLE)`) must serialize against page faults and other
operations. They do this by first acquiring the `filemap_invalidate_lock`
exclusively. Then, they iterate over the affected folios in the page cache
and acquire the `folio_lock` for each one (e.g., inside
`truncate_inode_pages_range()`).
*Lock order: `filemap_invalidate_lock` -> `folio_lock`*
2. **Thread 2 (`MADV_COLLAPSE` or `khugepaged` background thread)**:
When collapsing file-backed pages into a Transparent Huge Page (THP),
`collapse_file()` in `mm/khugepaged.c` iterates over the PMD-sized range,
locking folios one by one and adding them to a local list (`pagelist`). If it
encounters a missing folio (a hole), it attempts to read it in by calling
`page_cache_sync_readahead()`.
To protect against concurrent truncation during readahead, the readahead code
(`page_cache_ra_order()` or `do_page_cache_ra()`) acquires the
`filemap_invalidate_lock` in shared mode.
*Lock order: `folio_lock` (held from previous iterations) ->
`filemap_invalidate_lock`*
**The Deadlock:**
If Thread 2 successfully locks a folio at index `N` and then finds that the
folio at index `N+1` is missing, it will call into the readahead code and block
trying to acquire `filemap_invalidate_lock_shared` (because Thread 1 holds it
exclusively). Meanwhile, Thread 1 is trying to truncate the file and blocks
trying to acquire the `folio_lock` for the folio at index `N` (which is held by
Thread 2). Both threads wait on each other indefinitely.
**Security Impact:**
* **Exploitable:** No. This is a pure concurrency logic bug (deadlock). It does
not cause memory corruption, use-after-free, or out-of-bounds accesses, and
therefore cannot be exploited for privilege escalation or information leaks.
* **Denial of Service (DoS):** Yes. An unprivileged local user can easily
trigger this deadlock by mapping a file, calling `madvise(..., MADV_COLLAPSE)`
on the mapping, and concurrently calling `fallocate(..., FALLOC_FL_PUNCH_HOLE,
...)` on the same file.
This will permanently hang the user's tasks. More importantly, if the background
`khugepaged` kernel thread scans the file while it is being truncated,
`khugepaged` itself will deadlock, permanently breaking THP collapsing for the
entire system. Furthermore, on production systems where `kernel.hung_task_panic
= 1` is configured, this deadlock will reliably trigger a kernel panic and crash
the system.
* **Accessible From Unprivileged Processes / User Namespaces:** Yes. The
`madvise(MADV_COLLAPSE)` and `fallocate()` system calls are available to
unprivileged users and do not require any special capabilities.]
|