| 0/0 |
2026/02/24 21:20 |
flow |
assessment-kcsan |
10m
Results: map[Benign:true Confident:true Explanation:The data race occurs between `__fat_write_inode()` and `copy_folio_from_iter_atomic()`.
### Analysis
**Task 6570 (Write):**
This task is executing `__fat_write_inode()`, which updates a FAT directory entry in a `buffer_head`. Specifically, it writes to fields like `raw_entry->size`. The stack trace shows this is happening during a `fat_write_end()` call, which triggered a `fat_truncate_blocks()` due to a failed write, eventually leading to an inode sync.
**Task 2196 (Read):**
This task is a loop driver worker (`loop_workfn`) processing a write request for the loop device. The loop device is backed by a shmem file. To fulfill the write request, the loop driver reads from the loop device's page cache (via an iterator) and writes to the shmem file using `shmem_file_write_iter()`. The `copy_folio_from_iter_atomic()` function is performing a `memcpy` from the loop device's page.
**The Race:**
The two tasks are accessing the same memory location: a page in the block device's (loop device's) page cache. Task 6570 is modifying a directory entry in that page, while Task 2196 is reading the same page to write it out to the backing file.
### Why the race is benign:
1. **Filesystem Design:** FAT (and other older filesystems like ext2) does not use `lock_buffer()` when modifying metadata in a `buffer_head`. Instead, it relies on internal filesystem locks (like `sbi->inode_hash_lock`) to serialize modifications to the same inode. It does not synchronize with the block layer's writeback mechanism at the buffer level.
2. **Eventual Consistency:** When `__fat_write_inode()` finishes modifying the buffer, it calls `mark_buffer_dirty(bh)`. If the buffer was already under writeback (which is why the loop driver was reading it), this re-dirtying ensures that a *subsequent* writeback will be scheduled. Even if the current writeback (Task 2196) picks up an inconsistent/torn state of the directory entry, the next writeback will write the correct, final state.
3. **No Memory Corruption:** The race involves a simple `memcpy` from a valid memory range. It cannot cause a kernel crash or memory corruption. At worst, it results in "unstable" data being written to the backing file temporarily.
4. **Standard Practice:** This behavior is common in several Linux filesystems. They accept that metadata buffers can be modified while under writeback, as long as they are marked dirty again after the modification. For non-journaling filesystems like FAT, this small window of inconsistency is not considered a significant regression in robustness, as the filesystem is already vulnerable to inconsistencies if a crash occurs during metadata updates.
5. **Hardware/Architecture:** On the reported x86-64 architecture, the 4-byte write to a 4-byte aligned address (`raw_entry->size`) is atomic at the CPU level. While `memcpy` might still see a torn value if it reads byte-by-byte, the eventual consistency mechanism handles this.
In conclusion, the data race is a known and accepted property of the FAT filesystem's interaction with the block layer and does not lead to any harmful consequences beyond a transient inconsistency on the storage medium, which is corrected by design.
Final verdict: **Benign**]
|
| 1/1 |
2026/02/24 21:20 |
action |
kernel-checkouter |
0m
Results: map[KernelSrc:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/src/abb886c0c39beb4d1e7f5feabbfdd329d87de199]
|
| 2/1 |
2026/02/24 21:21 |
action |
kernel-builder |
3m
Results: map[KernelObj:/usr/local/google/home/dvyukov/syzkaller/agent/workdir/cache/build/aa9548292bbb3c057fae0996445ca122c1280056]
|
| 3/1 |
2026/02/24 21:25 |
action |
codesearch-prepare |
2m
Results: map[Index:codesearch-index]
|
| 4/1 |
2026/02/24 21:28 |
agent |
expert |
3m
Model:
Results: map[Benign:true Confident:true]
Instruction:
You are an experienced Linux kernel developer tasked with determining if the given kernel
data race is benign or not. The data race report is from KCSAN tool.
It contains 2 stack traces of the memory accesses that constitute a data race.
A "benign" data races are on a simple int/bool variable or similar field,
and the accesses are not supposed to be protected by any mutual exclusion primitives.
Common examples of such "benign" data races are accesses to various flags fields,
statistics counters, and similar. A "benign" data race does not lead to memory corruption/crash
with a conservative compiler that compiles memory accesses to primitive types
effectively as atomic.
A non-benign (or "harmful" data race) can lead to corruption/crash even with
a conservative compiler that compiles memory accesses to primitive types
effectively as atomic. A common example of a "harmful" data races is race on
a complex container (list/hashmap/etc), where accesses are supposed to be protected
by a mutual exclusion primitive.
Also consider races that happen at the same time with the given one.
If there is no synchronization in between, other memory accesses in the involved threads
race with each other if they access the same memory. For example, if both threads execute:
some_struct->have_elements = true;
list_add(new_node, &some_struct->list_head);
the race on some_struct->have_elements may appear benign, however it also implies there
is a race on some_struct->list_head which is not benign, since the list is not thread-safe.
Take into account that on 32-bit systems 64-bit memory accesses may be split into two accesses,
and thus even with a conservative compiler may not be fully atomic. However, such races may
still be benign depending on how writes are done, and how read data is used.
In the final reply explain why you think the given data race is benign or is harmful.
Use the provided tools to confirm any assumptions, variables/fields being accessed, etc.
In particular, don't make assumptions about the kernel source code,
use codesearch tools to read the actual source code.
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 data race report is:
==================================================================
BUG: KCSAN: data-race in __fat_write_inode / copy_folio_from_iter_atomic
write to 0xffff8881234c6c1c of 4 bytes by task 6570 on cpu 1:
__fat_write_inode+0x236/0x530 fs/fat/inode.c:-1
fat_sync_inode+0x1a/0x30 fs/fat/inode.c:932
fat_free fs/fat/file.c:332 [inline]
fat_truncate_blocks+0x1cc/0x5a0 fs/fat/file.c:394
fat_write_failed fs/fat/inode.c:219 [inline]
fat_write_end+0xba/0x160 fs/fat/inode.c:247
generic_perform_write+0x311/0x490 mm/filemap.c:4335
__generic_file_write_iter+0x9e/0x120 mm/filemap.c:4431
generic_file_write_iter+0x8d/0x310 mm/filemap.c:4457
do_iter_readv_writev+0x4fd/0x5a0 fs/read_write.c:-1
vfs_writev+0x2e1/0x900 fs/read_write.c:1057
do_pwritev fs/read_write.c:1153 [inline]
__do_sys_pwritev2 fs/read_write.c:1211 [inline]
__se_sys_pwritev2+0xfc/0x1c0 fs/read_write.c:1202
__x64_sys_pwritev2+0x67/0x80 fs/read_write.c:1202
x64_sys_call+0x2c9e/0x3000 arch/x86/include/generated/asm/syscalls_64.h:329
do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
do_syscall_64+0xc0/0x2a0 arch/x86/entry/syscall_64.c:94
entry_SYSCALL_64_after_hwframe+0x77/0x7f
read to 0xffff8881234c6c00 of 1024 bytes by task 2196 on cpu 0:
memcpy_from_iter lib/iov_iter.c:85 [inline]
iterate_bvec include/linux/iov_iter.h:123 [inline]
iterate_and_advance2 include/linux/iov_iter.h:306 [inline]
iterate_and_advance include/linux/iov_iter.h:330 [inline]
__copy_from_iter lib/iov_iter.c:261 [inline]
copy_folio_from_iter_atomic+0x75f/0x1170 lib/iov_iter.c:491
generic_perform_write+0x2c1/0x490 mm/filemap.c:4332
shmem_file_write_iter+0xc5/0xf0 mm/shmem.c:3513
lo_rw_aio+0x67d/0x730 drivers/block/loop.c:-1
do_req_filebacked drivers/block/loop.c:-1 [inline]
loop_handle_cmd drivers/block/loop.c:1947 [inline]
loop_process_work+0x56c/0xac0 drivers/block/loop.c:1982
loop_workfn+0x31/0x40 drivers/block/loop.c:2006
process_one_work kernel/workqueue.c:3257 [inline]
process_scheduled_works+0x4cd/0x9d0 kernel/workqueue.c:3340
worker_thread+0x6bc/0x8b0 kernel/workqueue.c:3421
kthread+0x488/0x510 kernel/kthread.c:463
ret_from_fork+0x148/0x280 arch/x86/kernel/process.c:158
ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:246
Reported by Kernel Concurrency Sanitizer on:
CPU: 0 UID: 0 PID: 2196 Comm: kworker/u8:6 Not tainted syzkaller #0 PREEMPT(voluntary)
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/25/2025
Workqueue: loop3 loop_workfn
==================================================================
Reply: The data race occurs between `__fat_write_inode()` and `copy_folio_from_iter_atomic()`.
### Analysis
**Task 6570 (Write):**
This task is executing `__fat_write_inode()`, which updates a FAT directory entry in a `buffer_head`. Specifically, it writes to fields like `raw_entry->size`. The stack trace shows this is happening during a `fat_write_end()` call, which triggered a `fat_truncate_blocks()` due to a failed write, eventually leading to an inode sync.
**Task 2196 (Read):**
This task is a loop driver worker (`loop_workfn`) processing a write request for the loop device. The loop device is backed by a shmem file. To fulfill the write request, the loop driver reads from the loop device's page cache (via an iterator) and writes to the shmem file using `shmem_file_write_iter()`. The `copy_folio_from_iter_atomic()` function is performing a `memcpy` from the loop device's page.
**The Race:**
The two tasks are accessing the same memory location: a page in the block device's (loop device's) page cache. Task 6570 is modifying a directory entry in that page, while Task 2196 is reading the same page to write it out to the backing file.
### Why the race is benign:
1. **Filesystem Design:** FAT (and other older filesystems like ext2) does not use `lock_buffer()` when modifying metadata in a `buffer_head`. Instead, it relies on internal filesystem locks (like `sbi->inode_hash_lock`) to serialize modifications to the same inode. It does not synchronize with the block layer's writeback mechanism at the buffer level.
2. **Eventual Consistency:** When `__fat_write_inode()` finishes modifying the buffer, it calls `mark_buffer_dirty(bh)`. If the buffer was already under writeback (which is why the loop driver was reading it), this re-dirtying ensures that a *subsequent* writeback will be scheduled. Even if the current writeback (Task 2196) picks up an inconsistent/torn state of the directory entry, the next writeback will write the correct, final state.
3. **No Memory Corruption:** The race involves a simple `memcpy` from a valid memory range. It cannot cause a kernel crash or memory corruption. At worst, it results in "unstable" data being written to the backing file temporarily.
4. **Standard Practice:** This behavior is common in several Linux filesystems. They accept that metadata buffers can be modified while under writeback, as long as they are marked dirty again after the modification. For non-journaling filesystems like FAT, this small window of inconsistency is not considered a significant regression in robustness, as the filesystem is already vulnerable to inconsistencies if a crash occurs during metadata updates.
5. **Hardware/Architecture:** On the reported x86-64 architecture, the 4-byte write to a 4-byte aligned address (`raw_entry->size`) is atomic at the CPU level. While `memcpy` might still see a torn value if it reads byte-by-byte, the eventual consistency mechanism handles this.
In conclusion, the data race is a known and accepted property of the FAT filesystem's interaction with the block layer and does not lead to any harmful consequences beyond a transient inconsistency on the storage medium, which is corrected by design.
Final verdict: **Benign**
|
| 5/2 |
2026/02/24 21:28 |
llm |
expert |
0m
Model:
Tokens:
input: 4288
output: 42
thoughts: 408
Thoughts: **Data Race Deep Dive**
Okay, here's what's running through my mind. This report screams data race, and it's pretty clear where. I've got `__fat_write_inode`, which is a write operation, and `copy_folio_from_iter_atomic`, which is a read operation, both clashing on memory. The report pinpoints the address `0xffff8881234c6c1c` as the culprit, and it's definitely within the region that the read operation is accessing.
The write operation, running under Task 6570, is diligently writing 4 bytes to `0xffff8881234c6c1c`. The stack trace shows it's making its way through the FAT filesystem with `__fat_write_inode` leading into the `fat_sync_inode`, and then down to `fat_truncate_blocks` and `fat_write_end`. This strongly indicates the write is part of flushing inode metadata, probably related to a file system change.
Meanwhile, Task 2196 is the read side. `copy_folio_from_iter_atomic` is attempting to read 1024 bytes starting from `0xffff8881234c6c00`. The stack trace reveals this read is coming from an iterator and is involved in a `generic_perform_write` call, which is likely part of handling I/O to a shared memory region, possibly via a loop device. It looks like it could be writing to the device, or reading from the device.
The most important part is the memory addresses involved. The address being written to is absolutely *within* the range of the read operation's memory access. This is classic data race territory. So `__fat_write_inode` is writing to the disk, presumably through a page cache write, while the read operation is simultaneously attempting to access a memory location within the same page.
Now, I need to understand the relationship between these two. My initial thought is that the write operation within `__fat_write_inode` is updating inode data, which could be anything from file size to modification timestamps. The read operation is coming from an iterator, so the question becomes what's being written and read. I need to refresh myself on how `__fat_write_inode` works within `fs/fat/inode.c`. That should give me the full context to understand how the two tasks are overlapping, and how to fix this data race.
|
| 6/2 |
2026/02/24 21:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/inode.c IncludeLines:true Name:__fat_write_inode]
Results: map[SourceCode: 854: static int __fat_write_inode(struct inode *inode, int wait)
855: {
856: struct super_block *sb = inode->i_sb;
857: struct msdos_sb_info *sbi = MSDOS_SB(sb);
858: struct buffer_head *bh;
859: struct msdos_dir_entry *raw_entry;
860: struct timespec64 mtime;
861: loff_t i_pos;
862: sector_t blocknr;
863: int err, offset;
864:
865: if (inode->i_ino == MSDOS_ROOT_INO)
866: return 0;
867:
868: retry:
869: i_pos = fat_i_pos_read(sbi, inode);
870: if (!i_pos)
871: return 0;
872:
873: fat_get_blknr_offset(sbi, i_pos, &blocknr, &offset);
874: bh = sb_bread(sb, blocknr);
875: if (!bh) {
876: fat_msg(sb, KERN_ERR, "unable to read inode block "
877: "for updating (i_pos %lld)", i_pos);
878: return -EIO;
879: }
880: spin_lock(&sbi->inode_hash_lock);
881: if (i_pos != MSDOS_I(inode)->i_pos) {
882: spin_unlock(&sbi->inode_hash_lock);
883: brelse(bh);
884: goto retry;
885: }
886:
887: raw_entry = &((struct msdos_dir_entry *) (bh->b_data))[offset];
888: if (S_ISDIR(inode->i_mode))
889: raw_entry->size = 0;
890: else
891: raw_entry->size = cpu_to_le32(inode->i_size);
892: raw_entry->attr = fat_make_attrs(inode);
893: fat_set_start(raw_entry, MSDOS_I(inode)->i_logstart);
894: mtime = inode_get_mtime(inode);
895: fat_time_unix2fat(sbi, &mtime, &raw_entry->time,
896: &raw_entry->date, NULL);
897: if (sbi->options.isvfat) {
898: struct timespec64 ts = inode_get_atime(inode);
899: __le16 atime;
900:
901: fat_time_unix2fat(sbi, &ts, &atime, &raw_entry->adate, NULL);
902: fat_time_unix2fat(sbi, &MSDOS_I(inode)->i_crtime, &raw_entry->ctime,
903: &raw_entry->cdate, &raw_entry->ctime_cs);
904: }
905: spin_unlock(&sbi->inode_hash_lock);
906: mark_buffer_dirty(bh);
907: err = 0;
908: if (wait)
909: err = sync_dirty_buffer(bh);
910: brelse(bh);
911: return err;
912: }
SourceFile:fs/fat/inode.c]
|
| 7/2 |
2026/02/24 21:28 |
llm |
expert |
0m
Model:
Tokens:
input: 6306
output: 37
thoughts: 92
Thoughts: **Analyzing a File System Write**
Okay, so I'm looking at this report that describes a write operation. It seems we're writing to a specific memory location, `0xffff8881234c6c1c`, and the write is for 4 bytes. The report indicates this location is probably linked to an `msdos_dir_entry` struct. I immediately recognize the likely target is a write to a field inside that struct – specifically, `raw_entry->size`. Now, I need to confirm my hunch. `__le32`, which I know is the type of the `size` field, means it's a 4-byte little-endian integer. That fits the reported size perfectly. My next step is to quickly determine the offset of the `size` field within the `msdos_dir_entry` structure to see if the reported write location matches. This confirmation is crucial to properly interpret the context of this write.
|
| 8/2 |
2026/02/24 21:28 |
tool |
codesearch-struct-layout |
0m
Args: map[ContextFile:fs/fat/inode.c Name:msdos_dir_entry]
Results: map[Fields:[map[Name:name OffsetBits:0 SizeBits:88] map[Name:attr OffsetBits:88 SizeBits:8] map[Name:lcase OffsetBits:96 SizeBits:8] map[Name:ctime_cs OffsetBits:104 SizeBits:8] map[Name:ctime OffsetBits:112 SizeBits:16] map[Name:cdate OffsetBits:128 SizeBits:16] map[Name:adate OffsetBits:144 SizeBits:16] map[Name:starthi OffsetBits:160 SizeBits:16] map[Name:time OffsetBits:176 SizeBits:16] map[Name:date OffsetBits:192 SizeBits:16] map[Name:start OffsetBits:208 SizeBits:16] map[Name:size OffsetBits:224 SizeBits:32]]]
|
| 9/2 |
2026/02/24 21:28 |
llm |
expert |
0m
Model:
Tokens:
input: 6880
output: 41
thoughts: 2466
Thoughts: **Data Race Analysis: FAT Filesystem on Loop Device**
Okay, here's what I've got. It looks like we've got a classic data race, and here's how it's playing out. The core issue is the interaction between a FAT filesystem mounted on a loop device and the underlying shmem file that backs that loop device.
The trace suggests a write to the FAT filesystem's metadata is colliding with a read operation performed by the loop driver. Specifically, a write is occurring within `__fat_write_inode`, which is part of the FAT filesystem's write path. This write is modifying a `buffer_head`'s data (`bh->b_data`). This buffer is a page from the loop device.
Meanwhile, a separate process is trying to write to the shmem backing file of the loop device. This write operation is happening through the loop driver (via `lo_rw_aio` -> `shmem_file_write_iter` -> `copy_folio_from_iter_atomic`). The crucial point is that `copy_folio_from_iter_atomic` is reading data from an iterator built from the write request (`bio`). Because the loop driver *is* the block device, and the FAT filesystem *is on the loop device*, the bio/iterator for the write request points to the *same* memory region (`bh->b_data`) that `__fat_write_inode` is actively modifying!
Here's the scenario: the FAT filesystem needs to update its metadata (e.g., a directory entry). It obtains a buffer head using `sb_bread`, which pulls the data from the block device's page cache. The block device is the loop device. The FAT filesystem modifies this buffer and eventually calls `mark_buffer_dirty`. This marks the buffer for writeback.
However, *before* this writeback completes, the loop driver receives a write request that happens to involve the same data. The loop driver, in fulfilling this request, reads from the bio (whose pages are *the same* as the block device's pages), copies the page to its shmem backing store through the use of `copy_folio_from_iter_atomic`.
This read operation happens concurrently with the write by the FAT filesystem's `__fat_write_inode`. So, while the directory entry is being modified, the loop driver's read potentially copies inconsistent data, which is now inconsistent in the shmem backing store.
The potential race is there, even though `__fat_write_inode` is operating under a filesystem lock. That filesystem lock doesn't protect the page cache. `sb_bread` seems to return a buffer without explicit synchronization. While modifying a block in the page cache is allowed, modifying a block under writeback, or when the loop driver is already reading from it, can be a serious data race.
Now, whether this is a full-blown *problem* depends on the guarantees we expect. While the FAT filesystem will eventually call `mark_buffer_dirty` again, triggering another write, the window of inconsistency exists *during* the loop driver's shmem write. If the inconsistent data is a critical piece of metadata, it could lead to corruption and this is likely the reason KCSAN has reported it as a race.
|
| 10/2 |
2026/02/24 21:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/inode.c IncludeLines:true Name:fat_write_end]
Results: map[SourceCode: 238: static int fat_write_end(const struct kiocb *iocb,
239: struct address_space *mapping,
240: loff_t pos, unsigned len, unsigned copied,
241: struct folio *folio, void *fsdata)
242: {
243: struct inode *inode = mapping->host;
244: int err;
245: err = generic_write_end(iocb, mapping, pos, len, copied, folio, fsdata);
246: if (err < len)
247: fat_write_failed(mapping, pos + len);
248: if (!(err < 0) && !(MSDOS_I(inode)->i_attrs & ATTR_ARCH)) {
249: fat_truncate_time(inode, NULL, S_CTIME|S_MTIME);
250: MSDOS_I(inode)->i_attrs |= ATTR_ARCH;
251: mark_inode_dirty(inode);
252: }
253: return err;
254: }
SourceFile:fs/fat/inode.c]
|
| 11/2 |
2026/02/24 21:28 |
llm |
expert |
0m
Model:
Tokens:
input: 10410
output: 41
thoughts: 8
Thoughts: Okay, here's my interpretation of that:
**My Brain's Take on `fat_write_failed`**
Alright, let's break this down. When I see `fat_write_failed`, my immediate thought is "Oh, the FAT file system – that's a whole different level of potential headache." My expert instincts kick in immediately. This isn't just a generic write error; it's a specific problem within the FAT file system, meaning I need to start thinking about block allocation, cluster size, file fragmentation, and the integrity of the File Allocation Table itself.
I'm thinking: is this a hardware issue masked as a software problem? A failing drive can start exhibiting signs like this, corrupting data subtly and leading to write failures. Is there a power supply issue? A sudden power interruption while writing could corrupt the FAT or a cluster, and cause this specific error.
Then I move to software: Is the file system corrupted? Was the drive unmounted improperly? Did a previous write operation fail and leave the filesystem in an inconsistent state? I'd immediately want to check the `fsck` output or whatever the equivalent tool is for this specific system, because `fsck` tries to fix the filesystem problems, so if it's got an issue, `fsck` could find it.
My mind then flashes to the context. Where did this error originate? What were we trying to write? The size of the file is important to understand: is it exceeding a cluster size limit, or running into some kind of file size limit?
And, most importantly, *why* did it fail? Was the disk full? Did a write operation fail, or was the file system corrupted and is now stopping write operations? The logs are going to be key here. I'll need to dig into the logs to find any related errors, and to see what was happening right before the error was thrown. This could mean a memory issue, a disk driver bug, an attempted write to a read-only partition, even an exhausted inode table, especially on older systems with smaller inode tables.
I need a systematic approach, so I'm thinking: Check hardware first (SMART data, error counters). Verify the disk integrity. Inspect the partition table. Review the logs. Analyze the code that's writing to the file system. And then, I can start forming a hypothesis about the root cause and a plan to fix it. This is going to be interesting.
|
| 12/2 |
2026/02/24 21:28 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/inode.c IncludeLines:true Name:fat_write_failed]
Results: map[SourceCode: 213: static void fat_write_failed(struct address_space *mapping, loff_t to)
214: {
215: struct inode *inode = mapping->host;
216:
217: if (to > inode->i_size) {
218: truncate_pagecache(inode, inode->i_size);
219: fat_truncate_blocks(inode, inode->i_size);
220: }
221: }
SourceFile:fs/fat/inode.c]
|
| 13/2 |
2026/02/24 21:28 |
llm |
expert |
0m
Model:
Tokens:
input: 11138
output: 17
thoughts: 2165
Thoughts: **Analyzing a Potential Data Race in the FAT Filesystem**
Okay, here's what I'm thinking about this FAT filesystem issue. It looks like `fat_truncate_blocks` calls `fat_free`, which in turn calls `fat_sync_inode`, and ultimately, `__fat_write_inode`. Now, the crucial thing is `fat_sync_inode` is called with `wait=0`, so `__fat_write_inode` uses `mark_buffer_dirty(bh)` but *not* `sync_dirty_buffer(bh)`. This sets up a race condition.
The potential race is between a write operation in `__fat_write_inode` and a read happening in the loop driver, specifically during a write request to the block device. Because a write request is in progress, there's been a previous `mark_buffer_dirty` call. This indicates a writeback is underway.
If `__fat_write_inode` is modifying the same directory entry that the loop driver is currently writing, the loop driver could read a partially updated entry. `__fat_write_inode` updates several fields like size, attributes, start cluster, and timestamps. If the loop driver reads these during the update, the data could be inconsistent. However, `__fat_write_inode` then calls `mark_buffer_dirty(bh)` again. This means another writeback will be scheduled, eventually correcting the data.
The question is, is this a problem? In the kernel, it's generally accepted that pages can be modified during writeback unless the filesystem takes specific measures to prevent it, like `wait_on_page_writeback`. However, KCSAN flagged this. If the system crashes between writebacks, we could have inconsistent metadata. FAT isn't a journaling filesystem anyway, so it's already prone to such inconsistencies.
If the loop driver uses `shmem_file_write_iter`, it copies data from the loop device's pages to shmem pages. `copy_folio_from_iter_atomic` does the copy. If the source data changes during the copy, the shmem destination will have inconsistent data. But again, the subsequent writeback fixes it.
Now, what about synchronization? `__fat_write_inode` holds `sbi->inode_hash_lock`. This doesn't help with the loop driver race. The buffer head `bh` isn't locked by `__fat_write_inode`. `sb_bread` returns a buffer head, but doesn't lock it. Typically, if you want exclusive access for modification, you'd `lock_buffer(bh)`. Does `__fat_write_inode` do that? Nope. Looking at the code, it doesn't.
If it doesn't lock the buffer, multiple threads could call `__fat_write_inode` on different inodes within the same block. The `sbi->inode_hash_lock` protects this, but only on a per-superblock basis, serializing those calls. This prevents races between concurrent calls *within* the same filesystem. But it doesn't prevent races with the loop driver, or any other block device consumer.
Is it a bug that `__fat_write_inode` doesn't lock the buffer? Most filesystems *do* lock the buffer when modifying it to ensure atomicity relative to writeback. But FAT is old. If `__fat_write_inode` is the *only* modifier of the directory entries, `inode_hash_lock` is enough for internal consistency. However, for consistency on disk, avoiding writeback races might be desirable. Many filesystems allow "dirtying" a buffer without locking, if a subsequent `mark_buffer_dirty` will eventually sync the final state.
If the loop driver is reading the page, it's because a write request was submitted, usually while the buffer is synced. So the buffer should be locked. If `__fat_write_inode` doesn't check `buffer_locked(bh)`, it'll just write to it. Let's see if `__fat_write_inode` should be locking the buffer.
Now, looking at `fat_write_inode` (the VFS export), it just calls `__fat_write_inode`, so it's not adding any additional locking. Let's check other filesystems for comparison. Looking at `ext2_write_inode` won't tell me much because FAT is an older filesystem and might not follow modern practices.
So, is the race harmful? The read uses `copy_folio_from_iter_atomic`, part of a shmem file write. If the shmem file gets inconsistent data, but it's immediately overwritten by "correct" data, is it okay? The loop driver is processing a request. The
|
| 14/2 |
2026/02/24 21:29 |
tool |
grepper |
0m
Args: map[Expression:lock_buffer]
Results: map[Output:
Full output is too long, showing 500 out of 1826 lines.
Use more precise expression if possible.
[Documentation/trace/ftrace.rst=2714=Flags::
--
Documentation/trace/ftrace.rst-2767- 360.774528 | 1) | reiserfs_prepare_for_journal() {
Documentation/trace/ftrace.rst:2768: 360.774528 | 1) | unlock_buffer() {
Documentation/trace/ftrace.rst-2769- 360.774529 | 1) | wake_up_bit() {
--
drivers/hwmon/lineage-pem.c=130=static int pem_read_block(struct i2c_client *client, u8 command, u8 *data,
--
drivers/hwmon/lineage-pem.c-132-{
drivers/hwmon/lineage-pem.c:133: u8 block_buffer[I2C_SMBUS_BLOCK_MAX];
drivers/hwmon/lineage-pem.c-134- int result;
drivers/hwmon/lineage-pem.c-135-
drivers/hwmon/lineage-pem.c:136: result = i2c_smbus_read_block_data(client, command, block_buffer);
drivers/hwmon/lineage-pem.c-137- if (unlikely(result < 0))
--
drivers/hwmon/lineage-pem.c-142- }
drivers/hwmon/lineage-pem.c:143: memcpy(data, block_buffer, data_len);
drivers/hwmon/lineage-pem.c-144- result = 0;
--
drivers/hwmon/lm93.c=859=static int lm93_write_word(struct i2c_client *client, u8 reg, u16 value)
--
drivers/hwmon/lm93.c-873-
drivers/hwmon/lm93.c:874:static u8 lm93_block_buffer[I2C_SMBUS_BLOCK_MAX];
drivers/hwmon/lm93.c-875-
--
drivers/hwmon/lm93.c=881=static void lm93_read_block(struct i2c_client *client, u8 fbn, u8 *values)
--
drivers/hwmon/lm93.c-886- result = i2c_smbus_read_block_data(client,
drivers/hwmon/lm93.c:887: lm93_block_read_cmds[fbn].cmd, lm93_block_buffer);
drivers/hwmon/lm93.c-888-
--
drivers/hwmon/lm93.c-899- if (result == lm93_block_read_cmds[fbn].len) {
drivers/hwmon/lm93.c:900: memcpy(values, lm93_block_buffer,
drivers/hwmon/lm93.c-901- lm93_block_read_cmds[fbn].len);
--
drivers/hwmon/pmbus/adm1275.c=512=static int adm1275_probe(struct i2c_client *client)
--
drivers/hwmon/pmbus/adm1275.c-514- s32 (*config_read_fn)(const struct i2c_client *client, u8 reg);
drivers/hwmon/pmbus/adm1275.c:515: u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
drivers/hwmon/pmbus/adm1275.c-516- int config, device_config;
--
drivers/hwmon/pmbus/adm1275.c-531-
drivers/hwmon/pmbus/adm1275.c:532: ret = i2c_smbus_read_block_data(client, PMBUS_MFR_ID, block_buffer);
drivers/hwmon/pmbus/adm1275.c-533- if (ret < 0) {
--
drivers/hwmon/pmbus/adm1275.c-536- }
drivers/hwmon/pmbus/adm1275.c:537: if ((ret != 3 || strncmp(block_buffer, "ADI", 3)) &&
drivers/hwmon/pmbus/adm1275.c:538: (ret != 2 || strncmp(block_buffer, "SY", 2))) {
drivers/hwmon/pmbus/adm1275.c-539- dev_err(&client->dev, "Unsupported Manufacturer ID\n");
--
drivers/hwmon/pmbus/adm1275.c-542-
drivers/hwmon/pmbus/adm1275.c:543: ret = i2c_smbus_read_block_data(client, PMBUS_MFR_MODEL, block_buffer);
drivers/hwmon/pmbus/adm1275.c-544- if (ret < 0) {
--
drivers/hwmon/pmbus/adm1275.c-548- for (mid = adm1275_id; mid->name[0]; mid++) {
drivers/hwmon/pmbus/adm1275.c:549: if (!strncasecmp(mid->name, block_buffer, strlen(mid->name)))
drivers/hwmon/pmbus/adm1275.c-550- break;
--
drivers/hwmon/pmbus/ltc4286.c=67=static int ltc4286_probe(struct i2c_client *client)
--
drivers/hwmon/pmbus/ltc4286.c-70- const struct i2c_device_id *mid;
drivers/hwmon/pmbus/ltc4286.c:71: u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
drivers/hwmon/pmbus/ltc4286.c-72- struct pmbus_driver_info *info;
--
drivers/hwmon/pmbus/ltc4286.c-75-
drivers/hwmon/pmbus/ltc4286.c:76: ret = i2c_smbus_read_block_data(client, PMBUS_MFR_ID, block_buffer);
drivers/hwmon/pmbus/ltc4286.c-77- if (ret < 0) {
--
drivers/hwmon/pmbus/ltc4286.c-86- if (ret != LTC4286_MFR_ID_SIZE ||
drivers/hwmon/pmbus/ltc4286.c:87: strncmp(block_buffer, "LTC", LTC4286_MFR_ID_SIZE)) {
drivers/hwmon/pmbus/ltc4286.c-88- return dev_err_probe(&client->dev, -ENODEV,
--
drivers/hwmon/pmbus/ltc4286.c-91-
drivers/hwmon/pmbus/ltc4286.c:92: ret = i2c_smbus_read_block_data(client, PMBUS_MFR_MODEL, block_buffer);
drivers/hwmon/pmbus/ltc4286.c-93- if (ret < 0) {
--
drivers/hwmon/pmbus/ltc4286.c-98- for (mid = ltc4286_id; mid->name[0]; mid++) {
drivers/hwmon/pmbus/ltc4286.c:99: if (!strncasecmp(mid->name, block_buffer, strlen(mid->name)))
drivers/hwmon/pmbus/ltc4286.c-100- break;
--
drivers/hwmon/pmbus/ucd9000.c=502=static int ucd9000_probe(struct i2c_client *client)
drivers/hwmon/pmbus/ucd9000.c-503-{
drivers/hwmon/pmbus/ucd9000.c:504: u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
drivers/hwmon/pmbus/ucd9000.c-505- struct ucd9000_data *data;
--
drivers/hwmon/pmbus/ucd9000.c-516- ret = i2c_smbus_read_block_data(client, UCD9000_DEVICE_ID,
drivers/hwmon/pmbus/ucd9000.c:517: block_buffer);
drivers/hwmon/pmbus/ucd9000.c-518- if (ret < 0) {
--
drivers/hwmon/pmbus/ucd9000.c-521- }
drivers/hwmon/pmbus/ucd9000.c:522: block_buffer[ret] = '\0';
drivers/hwmon/pmbus/ucd9000.c:523: dev_info(&client->dev, "Device ID %s\n", block_buffer);
drivers/hwmon/pmbus/ucd9000.c-524-
drivers/hwmon/pmbus/ucd9000.c-525- for (mid = ucd9000_id; mid->name[0]; mid++) {
drivers/hwmon/pmbus/ucd9000.c:526: if (!strncasecmp(mid->name, block_buffer, strlen(mid->name)))
drivers/hwmon/pmbus/ucd9000.c-527- break;
--
drivers/hwmon/pmbus/ucd9000.c-566- ret = i2c_smbus_read_block_data(client, UCD9000_MONITOR_CONFIG,
drivers/hwmon/pmbus/ucd9000.c:567: block_buffer);
drivers/hwmon/pmbus/ucd9000.c-568- if (ret <= 0) {
--
drivers/hwmon/pmbus/ucd9000.c-572- for (i = 0; i < ret; i++) {
drivers/hwmon/pmbus/ucd9000.c:573: int page = UCD9000_MON_PAGE(block_buffer[i]);
drivers/hwmon/pmbus/ucd9000.c-574-
--
drivers/hwmon/pmbus/ucd9000.c-577-
drivers/hwmon/pmbus/ucd9000.c:578: switch (UCD9000_MON_TYPE(block_buffer[i])) {
drivers/hwmon/pmbus/ucd9000.c-579- case UCD9000_MON_VOLTAGE:
--
drivers/hwmon/pmbus/ucd9200.c=74=static int ucd9200_probe(struct i2c_client *client)
drivers/hwmon/pmbus/ucd9200.c-75-{
drivers/hwmon/pmbus/ucd9200.c:76: u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
drivers/hwmon/pmbus/ucd9200.c-77- struct pmbus_driver_info *info;
--
drivers/hwmon/pmbus/ucd9200.c-87- ret = i2c_smbus_read_block_data(client, UCD9200_DEVICE_ID,
drivers/hwmon/pmbus/ucd9200.c:88: block_buffer);
drivers/hwmon/pmbus/ucd9200.c-89- if (ret < 0) {
--
drivers/hwmon/pmbus/ucd9200.c-92- }
drivers/hwmon/pmbus/ucd9200.c:93: block_buffer[ret] = '\0';
drivers/hwmon/pmbus/ucd9200.c:94: dev_info(&client->dev, "Device ID %s\n", block_buffer);
drivers/hwmon/pmbus/ucd9200.c-95-
drivers/hwmon/pmbus/ucd9200.c-96- for (mid = ucd9200_id; mid->name[0]; mid++) {
drivers/hwmon/pmbus/ucd9200.c:97: if (!strncasecmp(mid->name, block_buffer, strlen(mid->name)))
drivers/hwmon/pmbus/ucd9200.c-98- break;
--
drivers/hwmon/pmbus/ucd9200.c-120- ret = i2c_smbus_read_block_data(client, UCD9200_PHASE_INFO,
drivers/hwmon/pmbus/ucd9200.c:121: block_buffer);
drivers/hwmon/pmbus/ucd9200.c-122- if (ret < 0) {
--
drivers/hwmon/pmbus/ucd9200.c-134- for (i = 0; i < ret; i++) {
drivers/hwmon/pmbus/ucd9200.c:135: if (!block_buffer[i])
drivers/hwmon/pmbus/ucd9200.c-136- break;
--
drivers/memstick/core/ms_block.c=976=static int msb_verify_block(struct msb_data *msb, u16 pba,
--
drivers/memstick/core/ms_block.c-981-
drivers/memstick/core/ms_block.c:982: sg_init_one(&sg, msb->block_buffer, msb->block_size);
drivers/memstick/core/ms_block.c-983-
--
drivers/memstick/core/ms_block.c-993- if (msb_sg_compare_to_buffer(orig_sg, offset,
drivers/memstick/core/ms_block.c:994: msb->block_buffer, msb->block_size))
drivers/memstick/core/ms_block.c-995- return -EIO;
--
drivers/memstick/core/ms_block.c=1698=static int msb_init_card(struct memstick_dev *card)
--
drivers/memstick/core/ms_block.c-1744-
drivers/memstick/core/ms_block.c:1745: msb->block_buffer = kzalloc(msb->block_size, GFP_KERNEL);
drivers/memstick/core/ms_block.c:1746: if (!msb->block_buffer)
drivers/memstick/core/ms_block.c-1747- return -ENOMEM;
--
drivers/memstick/core/ms_block.h=145=struct msb_data {
--
drivers/memstick/core/ms_block.h-190- /* Preallocated buffers */
drivers/memstick/core/ms_block.h:191: unsigned char *block_buffer;
drivers/memstick/core/ms_block.h-192- struct scatterlist prealloc_sg[MS_BLOCK_MAX_SEGS+1];
--
drivers/net/ethernet/broadcom/tg3.c=3373=static int tg3_nvram_write_block_unbuffered(struct tg3 *tp, u32 offset, u32 len,
--
drivers/net/ethernet/broadcom/tg3.c-3471-/* offset and length are dword aligned */
drivers/net/ethernet/broadcom/tg3.c:3472:static int tg3_nvram_write_block_buffered(struct tg3 *tp, u32 offset, u32 len,
drivers/net/ethernet/broadcom/tg3.c-3473- u8 *buf)
--
drivers/net/ethernet/broadcom/tg3.c=3527=static int tg3_nvram_write_block(struct tg3 *tp, u32 offset, u32 len, u8 *buf)
--
drivers/net/ethernet/broadcom/tg3.c-3553- if (tg3_flag(tp, NVRAM_BUFFERED) || !tg3_flag(tp, FLASH)) {
drivers/net/ethernet/broadcom/tg3.c:3554: ret = tg3_nvram_write_block_buffered(tp, offset, len,
drivers/net/ethernet/broadcom/tg3.c-3555- buf);
--
drivers/power/supply/sbs-battery.c=358=static int sbs_read_string_data_fallback(struct i2c_client *client, u8 address, char *values)
--
drivers/power/supply/sbs-battery.c-362- int retries_length, retries_block;
drivers/power/supply/sbs-battery.c:363: u8 block_buffer[I2C_SMBUS_BLOCK_MAX + 1];
drivers/power/supply/sbs-battery.c-364-
--
drivers/power/supply/sbs-battery.c-405- client, address,
drivers/power/supply/sbs-battery.c:406: block_length + 1, block_buffer);
drivers/power/supply/sbs-battery.c-407- if (ret >= 0)
--
drivers/power/supply/sbs-battery.c-418-
drivers/power/supply/sbs-battery.c:419: /* block_buffer[0] == block_length */
drivers/power/supply/sbs-battery.c:420: memcpy(values, block_buffer + 1, block_length);
drivers/power/supply/sbs-battery.c-421- values[block_length] = '\0';
--
fs/affs/affs.h=250=affs_getzeroblk(struct super_block *sb, int block)
--
fs/affs/affs.h-255- bh = sb_getblk(sb, block);
fs/affs/affs.h:256: lock_buffer(bh);
fs/affs/affs.h-257- memset(bh->b_data, 0 , sb->s_blocksize);
fs/affs/affs.h-258- set_buffer_uptodate(bh);
fs/affs/affs.h:259: unlock_buffer(bh);
fs/affs/affs.h-260- return bh;
--
fs/affs/super.c=33=affs_commit_super(struct super_block *sb, int wait)
--
fs/affs/super.c-38-
fs/affs/super.c:39: lock_buffer(bh);
fs/affs/super.c-40- affs_secs_to_datestamp(ktime_get_real_seconds(), &tail->disk_change);
fs/affs/super.c-41- affs_fix_checksum(sb, bh);
fs/affs/super.c:42: unlock_buffer(bh);
fs/affs/super.c-43-
--
fs/buffer.c=67=EXPORT_SYMBOL(touch_buffer);
fs/buffer.c-68-
fs/buffer.c:69:void __lock_buffer(struct buffer_head *bh)
fs/buffer.c-70-{
--
fs/buffer.c-72-}
fs/buffer.c:73:EXPORT_SYMBOL(__lock_buffer);
fs/buffer.c-74-
fs/buffer.c:75:void unlock_buffer(struct buffer_head *bh)
fs/buffer.c-76-{
--
fs/buffer.c-80-}
fs/buffer.c:81:EXPORT_SYMBOL(unlock_buffer);
fs/buffer.c-82-
--
fs/buffer.c=127=static void buffer_io_error(struct buffer_head *bh, char *msg)
--
fs/buffer.c-137- * unlocking it.
fs/buffer.c:138: * Note: unlock_buffer() sort-of does touch the bh after unlocking it, but
fs/buffer.c:139: * a race there is benign: unlock_buffer() only use the bh's address for
fs/buffer.c-140- * hashing after unlocking the buffer, so it doesn't actually touch the bh
--
fs/buffer.c=143=static void __end_buffer_read_notouch(struct buffer_head *bh, int uptodate)
--
fs/buffer.c-150- }
fs/buffer.c:151: unlock_buffer(bh);
fs/buffer.c-152-}
--
fs/buffer.c=165=void end_buffer_write_sync(struct buffer_head *bh, int uptodate)
--
fs/buffer.c-173- }
fs/buffer.c:174: unlock_buffer(bh);
fs/buffer.c-175- put_bh(bh);
--
fs/buffer.c=256=static void end_buffer_async_read(struct buffer_head *bh, int uptodate)
--
fs/buffer.c-281- clear_buffer_async_read(bh);
fs/buffer.c:282: unlock_buffer(bh);
fs/buffer.c-283- tmp = bh;
--
fs/buffer.c=387=static void end_buffer_async_write(struct buffer_head *bh, int uptodate)
--
fs/buffer.c-408- clear_buffer_async_write(bh);
fs/buffer.c:409: unlock_buffer(bh);
fs/buffer.c-410- tmp = bh->b_this_page;
--
fs/buffer.c=1263=static struct buffer_head *__bread_slow(struct buffer_head *bh)
fs/buffer.c-1264-{
fs/buffer.c:1265: lock_buffer(bh);
fs/buffer.c-1266- if (buffer_uptodate(bh)) {
fs/buffer.c:1267: unlock_buffer(bh);
fs/buffer.c-1268- return bh;
--
fs/buffer.c=1602=static void discard_buffer(struct buffer_head * bh)
--
fs/buffer.c-1605-
fs/buffer.c:1606: lock_buffer(bh);
fs/buffer.c-1607- clear_buffer_dirty(bh);
--
fs/buffer.c-1612- b_state & ~BUFFER_FLAGS_DISCARD));
fs/buffer.c:1613: unlock_buffer(bh);
fs/buffer.c-1614-}
--
fs/buffer.c=1792=static struct buffer_head *folio_create_buffers(struct folio *folio,
--
fs/buffer.c-1823- * again at any time. We handle that by only looking at the buffer
fs/buffer.c:1824: * state inside lock_buffer().
fs/buffer.c-1825- *
--
fs/buffer.c=1836=int __block_write_full_folio(struct inode *inode, struct folio *folio,
--
fs/buffer.c-1909- if (wbc->sync_mode != WB_SYNC_NONE) {
fs/buffer.c:1910: lock_buffer(bh);
fs/buffer.c:1911: } else if (!trylock_buffer(bh)) {
fs/buffer.c-1912- folio_redirty_for_writepage(wbc, folio);
--
fs/buffer.c-1918- } else {
fs/buffer.c:1919: unlock_buffer(bh);
fs/buffer.c-1920- }
--
fs/buffer.c-1969- !buffer_delay(bh)) {
fs/buffer.c:1970: lock_buffer(bh);
fs/buffer.c-1971- mark_buffer_async_write_endio(bh,
--
fs/buffer.c=2380=EXPORT_SYMBOL(block_is_partially_uptodate);
--
fs/buffer.c-2384- * get_block functionality. This is most of the block device filesystems.
fs/buffer.c:2385: * Reads the folio asynchronously --- the unlock_buffer() and
fs/buffer.c-2386- * set/clear_buffer_uptodate() functions propagate buffer state into the
--
fs/buffer.c=2389=int block_read_full_folio(struct folio *folio, get_block_t *get_block)
--
fs/buffer.c-2438-
fs/buffer.c:2439: lock_buffer(bh);
fs/buffer.c-2440- if (buffer_uptodate(bh)) {
fs/buffer.c:2441: unlock_buffer(bh);
fs/buffer.c-2442- continue;
--
fs/buffer.c=2833=void write_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
fs/buffer.c-2834-{
fs/buffer.c:2835: lock_buffer(bh);
fs/buffer.c-2836- if (!test_clear_buffer_dirty(bh)) {
fs/buffer.c:2837: unlock_buffer(bh);
fs/buffer.c-2838- return;
--
fs/buffer.c=2851=int __sync_dirty_buffer(struct buffer_head *bh, blk_opf_t op_flags)
--
fs/buffer.c-2853- WARN_ON(atomic_read(&bh->b_count) < 1);
fs/buffer.c:2854: lock_buffer(bh);
fs/buffer.c-2855- if (test_clear_buffer_dirty(bh)) {
--
fs/buffer.c-2860- if (!buffer_mapped(bh)) {
fs/buffer.c:2861: unlock_buffer(bh);
fs/buffer.c-2862- return -EIO;
--
fs/buffer.c-2871- } else {
fs/buffer.c:2872: unlock_buffer(bh);
fs/buffer.c-2873- }
--
fs/buffer.c=3070=int bh_uptodate_or_lock(struct buffer_head *bh)
--
fs/buffer.c-3072- if (!buffer_uptodate(bh)) {
fs/buffer.c:3073: lock_buffer(bh);
fs/buffer.c-3074- if (!buffer_uptodate(bh))
fs/buffer.c-3075- return 0;
fs/buffer.c:3076: unlock_buffer(bh);
fs/buffer.c-3077- }
--
fs/buffer.c=3118=void __bh_read_batch(int nr, struct buffer_head *bhs[],
--
fs/buffer.c-3129- if (force_lock)
fs/buffer.c:3130: lock_buffer(bh);
fs/buffer.c-3131- else
fs/buffer.c:3132: if (!trylock_buffer(bh))
fs/buffer.c-3133- continue;
--
fs/buffer.c-3135- if (buffer_uptodate(bh)) {
fs/buffer.c:3136: unlock_buffer(bh);
fs/buffer.c-3137- continue;
--
fs/ceph/io.c=126=ceph_end_io_write(struct inode *inode)
--
fs/ceph/io.c-131-/* Call with exclusively locked inode->i_rwsem */
fs/ceph/io.c:132:static void ceph_block_buffered(struct ceph_inode_info *ci, struct inode *inode)
fs/ceph/io.c-133-{
--
fs/ceph/io.c=171=int ceph_start_io_direct(struct inode *inode)
--
fs/ceph/io.c-195-
fs/ceph/io.c:196: ceph_block_buffered(ci, inode);
fs/ceph/io.c-197- downgrade_write(&inode->i_rwsem);
--
fs/ext2/inode.c=479=static int ext2_alloc_branch(struct inode *inode,
--
fs/ext2/inode.c-511- branch[n].bh = bh;
fs/ext2/inode.c:512: lock_buffer(bh);
fs/ext2/inode.c-513- memset(bh->b_data, 0, blocksize);
--
fs/ext2/inode.c-527- set_buffer_uptodate(bh);
fs/ext2/inode.c:528: unlock_buffer(bh);
fs/ext2/inode.c-529- mark_buffer_dirty_inode(bh, inode);
--
fs/ext2/super.c=1564=static ssize_t ext2_quota_write(struct super_block *sb, int type,
--
fs/ext2/super.c-1591- }
fs/ext2/super.c:1592: lock_buffer(bh);
fs/ext2/super.c-1593- memcpy(bh->b_data+offset, data, tocopy);
--
fs/ext2/super.c-1596- mark_buffer_dirty(bh);
fs/ext2/super.c:1597: unlock_buffer(bh);
fs/ext2/super.c-1598- brelse(bh);
--
fs/ext2/xattr.c=406=ext2_xattr_set(struct inode *inode, int name_index, const char *name,
--
fs/ext2/xattr.c-520-
fs/ext2/xattr.c:521: lock_buffer(bh);
fs/ext2/xattr.c-522- if (header->h_refcount == cpu_to_le32(1)) {
--
fs/ext2/xattr.c-536- }
fs/ext2/xattr.c:537: unlock_buffer(bh);
fs/ext2/xattr.c-538- ea_bdebug(bh, "cloning");
--
fs/ext2/xattr.c-634- if (bh && header == HDR(bh))
fs/ext2/xattr.c:635: unlock_buffer(bh); /* we were modifying in-place. */
fs/ext2/xattr.c-636- error = ext2_xattr_set2(inode, bh, NULL);
--
fs/ext2/xattr.c-639- if (bh && header == HDR(bh))
fs/ext2/xattr.c:640: unlock_buffer(bh); /* we were modifying in-place. */
fs/ext2/xattr.c-641- error = ext2_xattr_set2(inode, bh, header);
--
fs/ext2/xattr.c=653=static void ext2_xattr_release_block(struct inode *inode,
--
fs/ext2/xattr.c-658-retry_ref:
fs/ext2/xattr.c:659: lock_buffer(bh);
fs/ext2/xattr.c-660- if (HDR(bh)->h_refcount == cpu_to_le32(1)) {
--
fs/ext2/xattr.c-674- */
fs/ext2/xattr.c:675: unlock_buffer(bh);
fs/ext2/xattr.c-676- mb_cache_entry_wait_unused(oe);
--
fs/ext2/xattr.c-687- bforget(bh);
fs/ext2/xattr.c:688: unlock_buffer(bh);
fs/ext2/xattr.c-689- } else {
--
fs/ext2/xattr.c-693- mark_buffer_dirty(bh);
fs/ext2/xattr.c:694: unlock_buffer(bh);
fs/ext2/xattr.c-695- ea_bdebug(bh, "refcount now=%d",
--
fs/ext2/xattr.c=706=ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh,
--
fs/ext2/xattr.c-726- if (error) {
fs/ext2/xattr.c:727: unlock_buffer(new_bh);
fs/ext2/xattr.c-728- goto cleanup;
--
fs/ext2/xattr.c-733- }
fs/ext2/xattr.c:734: unlock_buffer(new_bh);
fs/ext2/xattr.c-735- } else if (old_bh && header == HDR(old_bh)) {
--
fs/ext2/xattr.c-759- }
fs/ext2/xattr.c:760: lock_buffer(new_bh);
fs/ext2/xattr.c-761- memcpy(new_bh->b_data, header, new_bh->b_size);
fs/ext2/xattr.c-762- set_buffer_uptodate(new_bh);
fs/ext2/xattr.c:763: unlock_buffer(new_bh);
fs/ext2/xattr.c-764- ext2_xattr_cache_insert(ea_block_cache, new_bh);
--
fs/ext2/xattr.c=938=ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header)
--
fs/ext2/xattr.c-957- } else {
fs/ext2/xattr.c:958: lock_buffer(bh);
fs/ext2/xattr.c-959- if (le32_to_cpu(HDR(bh)->h_refcount) >
--
fs/ext2/xattr.c-971- }
fs/ext2/xattr.c:972: unlock_buffer(bh);
fs/ext2/xattr.c-973- brelse(bh);
--
fs/ext4/balloc.c=464=ext4_read_block_bitmap_nowait(struct super_block *sb, ext4_group_t block_group,
--
fs/ext4/balloc.c-504-
fs/ext4/balloc.c:505: lock_buffer(bh);
fs/ext4/balloc.c-506- if (bitmap_uptodate(bh)) {
fs/ext4/balloc.c:507: unlock_buffer(bh);
fs/ext4/balloc.c-508- goto verify;
--
fs/ext4/balloc.c-514- ext4_unlock_group(sb, block_group);
fs/ext4/balloc.c:515: unlock_buffer(bh);
fs/ext4/balloc.c-516- ext4_error(sb, "Block bitmap for bg 0 marked "
--
fs/ext4/balloc.c-523- ext4_unlock_group(sb, block_group);
fs/ext4/balloc.c:524: unlock_buffer(bh);
fs/ext4/balloc.c-525- ext4_error(sb, "Failed to init block bitmap for group "
--
fs/ext4/balloc.c-532- ext4_unlock_group(sb, block_group);
fs/ext4/balloc.c:533: unlock_buffer(bh);
fs/ext4/balloc.c-534- return bh;
--
fs/ext4/balloc.c-542- set_bitmap_uptodate(bh);
fs/ext4/balloc.c:543: unlock_buffer(bh);
fs/ext4/balloc.c-544- goto verify;
--
fs/ext4/crypto.c=83=int ext4_ioctl_get_encryption_pwsalt(struct file *filp, void __user *arg)
--
fs/ext4/crypto.c-105- goto pwsalt_err_journal;
fs/ext4/crypto.c:106: lock_buffer(sbi->s_sbh);
fs/ext4/crypto.c-107- generate_random_uuid(sbi->s_es->s_encrypt_pw_salt);
fs/ext4/crypto.c-108- ext4_superblock_csum_set(sb);
fs/ext4/crypto.c:109: unlock_buffer(sbi->s_sbh);
fs/ext4/crypto.c-110- err = ext4_handle_dirty_metadata(handle, NULL, sbi->s_sbh);
--
fs/ext4/extents.c=1053=static int ext4_ext_split(handle_t *handle, struct inode *inode,
--
fs/ext4/extents.c-1131- }
fs/ext4/extents.c:1132: lock_buffer(bh);
fs/ext4/extents.c-1133-
--
fs/ext4/extents.c-1170- set_buffer_uptodate(bh);
fs/ext4/extents.c:1171: unlock_buffer(bh);
fs/ext4/extents.c-1172-
--
fs/ext4/extents.c-1210- }
fs/ext4/extents.c:1211: lock_buffer(bh);
fs/ext4/extents.c-1212-
--
fs/ext4/extents.c-1256- set_buffer_uptodate(bh);
fs/ext4/extents.c:1257: unlock_buffer(bh);
fs/ext4/extents.c-1258-
--
fs/ext4/extents.c-1285- if (buffer_locked(bh))
fs/ext4/extents.c:1286: unlock_buffer(bh);
fs/ext4/extents.c-1287- brelse(bh);
--
fs/ext4/extents.c=1312=static int ext4_ext_grow_indepth(handle_t *handle, struct inode *inode,
--
fs/ext4/extents.c-1337- return -ENOMEM;
fs/ext4/extents.c:1338: lock_buffer(bh);
fs/ext4/extents.c-1339-
--
fs/ext4/extents.c-1342- if (err) {
fs/ext4/extents.c:1343: unlock_buffer(bh);
]
]
|
| 15/2 |
2026/02/24 21:29 |
llm |
expert |
0m
Model:
Tokens:
input: 24625
output: 22
thoughts: 27
Thoughts: Okay, here's my take on those thoughts, framed for an expert audience:
**Investigating Buffer Locking in Filesystem Modifications**
Right, the `grep` results are pointing towards a pretty wide use of `lock_buffer` across a bunch of different filesystems whenever they're touching a buffer. My immediate thought is, "Okay, that's expected, but let's drill down." Specifically, let's see if FAT, which has always been a bit…well, let's just say simpler in its design, actually leverages that locking mechanism for buffer modifications. It wouldn't be surprising if it went a different route, maybe with more coarse-grained locking or relying more heavily on the underlying block device directly in some instances. I'm curious to see if it's following the more modern pattern. Let me go check the relevant FAT code and see what they are up to.
|
| 16/2 |
2026/02/24 21:29 |
tool |
grepper |
0m
Error:
Args: map[Expression:lock_buffer.*fs/fat/]
Results:
|
| 17/2 |
2026/02/24 21:29 |
llm |
expert |
0m
Model:
Tokens:
input: 24876
output: 26
thoughts: 37
Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue:
**FAT Buffer Locking - A Quick Check**
Hmm, it *appears* FAT isn't using `lock_buffer` anywhere. That's a little unusual, or perhaps I'm missing something subtle. I need to be absolutely sure about this before I make any assumptions. Let's drill down into the core of the FAT implementation – specifically, `fs/fat/inode.c`. That's where I'd expect to find any buffer locking routines related to the inode management within the FAT filesystem. Gotta verify this to ensure proper data integrity, of course. Need to see if anything in that file directly interacts with buffer locking to be sure.
|
| 18/2 |
2026/02/24 21:29 |
tool |
codesearch-file-index |
0m
Args: map[SourceFile:fs/fat/inode.c]
Results: map[Entities:[map[Kind:function Name:__fat_get_block] map[Kind:function Name:__fat_write_inode] map[Kind:function Name:_fat_bmap] map[Kind:function Name:calc_fat_clusters] map[Kind:function Name:delayed_free] map[Kind:function Name:dir_hash_init] map[Kind:function Name:exit_fat_fs] map[Kind:function Name:fat_add_cluster] map[Kind:function Name:fat_alloc_inode] map[Kind:function Name:fat_attach] map[Kind:function Name:fat_block_truncate_page] map[Kind:function Name:fat_bpb_is_zero] map[Kind:function Name:fat_build_inode] map[Kind:function Name:fat_calc_dir_size] map[Kind:function Name:fat_destroy_inodecache] map[Kind:function Name:fat_detach] map[Kind:function Name:fat_direct_IO] map[Kind:function Name:fat_evict_inode] map[Kind:function Name:fat_fill_inode] map[Kind:function Name:fat_fill_super] map[Kind:function Name:fat_flush_inodes] map[Kind:function Name:fat_free_eofblocks] map[Kind:function Name:fat_free_fc] map[Kind:function Name:fat_free_inode] map[Kind:function Name:fat_get_block] map[Kind:function Name:fat_get_block_bmap] map[Kind:function Name:fat_hash] map[Kind:function Name:fat_hash_init] map[Kind:function Name:fat_iget] map[Kind:function Name:fat_init_fs_context] map[Kind:function Name:fat_init_inodecache] map[Kind:function Name:fat_lock_build_inode] map[Kind:function Name:fat_parse_param] map[Kind:function Name:fat_put_super] map[Kind:function Name:fat_read_bpb] map[Kind:function Name:fat_read_folio] map[Kind:function Name:fat_read_root] map[Kind:function Name:fat_read_static_bpb] map[Kind:function Name:fat_readahead] map[Kind:function Name:fat_reconfigure] map[Kind:function Name:fat_reset_iocharset] map[Kind:function Name:fat_set_state] map[Kind:function Name:fat_show_options] map[Kind:function Name:fat_statfs] map[Kind:function Name:fat_sync_inode] map[Kind:function Name:fat_unlock_build_inode] map[Kind:function Name:fat_validate_dir] map[Kind:function Name:fat_write_begin] map[Kind:function Name:fat_write_end] map[Kind:function Name:fat_write_failed] map[Kind:function Name:fat_write_inode] map[Kind:function Name:fat_writepages] map[Kind:function Name:init_fat_fs] map[Kind:function Name:init_once] map[Kind:function Name:is_exec] map[Kind:function Name:writeback_inode] map[Kind:struct Name:fat_bios_param_block] map[Kind:struct Name:fat_floppy_defaults] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_attach_895] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_build_inode_898] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_detach_896] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_fill_super_906] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_flush_inodes_907] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_free_fc_909] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_init_fs_context_908] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_param_spec_901] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_parse_param_902] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_reconfigure_899] map[Kind:global_variable Name:__UNIQUE_ID_addressable_fat_sync_inode_900] map[Kind:global_variable Name:__UNIQUE_ID_addressable_init_fat_fs_911] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_912] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_913] map[Kind:global_variable Name:__UNIQUE_ID_modinfo_914] map[Kind:global_variable Name:__exitcall_exit_fat_fs] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_attach] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_build_inode] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_detach] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_fill_super] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_flush_inodes] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_free_fc] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_init_fs_context] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_param_spec] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_parse_param] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_reconfigure] map[Kind:global_variable Name:__gendwarfksyms_ptr_fat_sync_inode] map[Kind:global_variable Name:fat_aops] map[Kind:global_variable Name:fat_default_codepage] map[Kind:global_variable Name:fat_default_iocharset] map[Kind:global_variable Name:fat_param_check] map[Kind:global_variable Name:fat_param_conv] map[Kind:global_variable Name:fat_param_errors] map[Kind:global_variable Name:fat_param_nfs] map[Kind:global_variable Name:fat_param_shortname] map[Kind:global_variable Name:fat_param_spec] map[Kind:global_variable Name:fat_param_tz] map[Kind:global_variable Name:fat_sops] map[Kind:global_variable Name:floppy_defaults] map[Kind:global_variable Name:msdos_param_spec] map[Kind:global_variable Name:vfat_param_spec]]]
|
| 19/2 |
2026/02/24 21:29 |
llm |
expert |
0m
Model:
Tokens:
input: 27049
output: 42
thoughts: 1014
Thoughts: **Analyzing the FAT Filesystem and Loop Driver Interaction**
Okay, so I'm thinking through this issue with the FAT filesystem and the loop driver. It looks like FAT doesn't utilize `lock_buffer`, relying instead on its own internal locking mechanisms (like `sbi->inode_hash_lock`). This means that modifications to buffers aren't synchronized with writeback at the buffer level. The loop driver, which essentially just consumes the block device, is potentially exposed to seeing these intermediate states during reads.
My concern initially was whether this poses a problem for the loop driver. If the underlying block device's page cache is getting updated while the loop driver is reading from it, the driver could end up with inconsistent data. This can happen specifically during the `memcpy` operations.
Now, `copy_folio_from_iter_atomic` is involved, reading directly from the iterator, which points to the block device's page. Any page modification during this copy makes it a non-atomic operation, introducing the potential for partial updates. But I'm asking myself, is this inherently harmful?
In most cases, the kernel treats this as "unstable" writeback. And if it's metadata, it would be more concerning. But, I'm reminding myself that the buffer will simply be marked dirty again, leading to a new writeback. The inconsistent data in the backing file should be temporary, lasting only until the next writeback completes.
I'm considering that if the loop device were used for something demanding strict consistency, like another filesystem on top of it, this could be a bigger problem. But here, the loop device *is* the block device for the FAT filesystem. FAT is writing to its own block device, and the loop driver is simply the implementation of that block device.
If FAT doesn't have a problem with temporary inconsistencies in the backing file, then it seems fine. And since FAT doesn't lock the buffer, it seems it doesn't care.
I'm revisiting `__fat_write_inode`. This updates those smaller fields like `raw_entry->size`, `raw_entry->attr`, and `raw_entry->time`. If the loop driver reads these during the update, it could catch a mixed state, say, the new `size` with the old `time`. But again, it will eventually see everything up-to-date.
So, am I at any risk of a crash or memory corruption? No, this is just a `memcpy`. A `memcpy` from a page that is being modified is memory-safe (it won't crash), but may return inconsistent data. KCSAN flags it as a data race. Many such races are considered "benign" if they don't cause real bugs. In this case, it appears to be a known property of how some filesystems interact with the block layer.
Now, I'm asking myself if there is a real reason why this *must* be synchronized. If the loop driver was writing to a real disk via DMA, the DMA might also see inconsistent data. Most hardware handles this fine (it just gets whatever is in memory at the time). The loop driver is doing the same with `memcpy`.
Ah, but there's a known issue with "stable writes". Some block devices (like those with checksums) require that a page remains constant during writeback. If a block device requires this, the block layer should prevent page modifications. This is usually done with `wait_on_page_writeback` in the filesystem's `page_mkwrite` or during buffer dirtying. But FAT doesn't appear to be doing this for its metadata buffers.
Let's check the loop device's stance on stable writes. The loop device itself doesn't have this requirement, but its backing file might. If the backing file is on a filesystem that demands stable writes, then the loop driver should likely respect that. But here, the backing file is shmem, which doesn't require stable writes.
In this scenario, Task 2196 is writing *to* shmem. Specifically, `shmem_file_write_iter` is calling `copy_folio_from_iter_atomic`. The copy is *from* the loop device's page *to* the shmem page, and the loop device's page is being modified by `__fat_write_inode`.
If this were a true bug, it would appear with any block device, not just loop. Any block device writeback could race with a metadata update if the filesystem doesn't lock the buffer. And as we've seen, FAT doesn't lock the buffer.
Now, does FAT *need* to lock the buffer? Let's check `fs/fat/fatent.c` and see how it handles FAT table updates to confirm my initial observation.
|
| 20/2 |
2026/02/24 21:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/fatent.c IncludeLines:true Name:fat_ent_write]
Results: map[SourceCode: 410: int fat_ent_write(struct inode *inode, struct fat_entry *fatent,
411: int new, int wait)
412: {
413: struct super_block *sb = inode->i_sb;
414: const struct fatent_operations *ops = MSDOS_SB(sb)->fatent_ops;
415: int err;
416:
417: ops->ent_put(fatent, new);
418: if (wait) {
419: err = fat_sync_bhs(fatent->bhs, fatent->nr_bhs);
420: if (err)
421: return err;
422: }
423: return fat_mirror_bhs(sb, fatent->bhs, fatent->nr_bhs);
424: }
SourceFile:fs/fat/fatent.c]
|
| 21/2 |
2026/02/24 21:29 |
llm |
expert |
0m
Model:
Tokens:
input: 29399
output: 44
thoughts: 39
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience:
**Considering the `ent_put` Operation for FAT32**
Alright, so we're working with an `ent_put` operation, and the context clearly points to FAT32. I need to make sure we're using the correct implementation for this filesystem. The most logical candidate, based on the filesystem context, would be `fat32_ent_put`. I should go ahead and confirm that assumption and check the definition, to ensure it handles the operation as expected.
|
| 22/2 |
2026/02/24 21:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/fatent.c IncludeLines:true Name:fat32_ent_put]
Results: map[SourceCode: 187: static void fat32_ent_put(struct fat_entry *fatent, int new)
188: {
189: WARN_ON(new & 0xf0000000);
190: new |= le32_to_cpu(*fatent->u.ent32_p) & ~0x0fffffff;
191: *fatent->u.ent32_p = cpu_to_le32(new);
192: mark_buffer_dirty_inode(fatent->bhs[0], fatent->fat_inode);
193: }
SourceFile:fs/fat/fatent.c]
|
| 23/2 |
2026/02/24 21:29 |
llm |
expert |
0m
Model:
Tokens:
input: 29796
output: 39
thoughts: 1764
Thoughts: **Analyzing a Potential Data Race in FAT Filesystem Metadata Updates**
Okay, so I'm digging into this KCSAN report about a possible data race within the FAT filesystem code, specifically related to how it updates directory entries. It seems like the core issue revolves around the lack of buffer locking during metadata modification, which is a known characteristic of FAT. It appears FAT relies on internal locks and serialized operations to maintain consistency, but doesn't worry about intermediate states during writeback.
The race specifically focuses on updating the `raw_entry->size` field, which indicates file size. I initially thought the data race was benign because an atomic 4-byte write on x86 should be safe. I figured that even if the `memcpy` operation in the loop driver had a torn read, the filesystem would eventually converge because the data would be marked dirty and re-written. This is a common and usually acceptable strategy within the kernel, where eventual consistency is preferred over high overhead locking.
However, a closer look suggests a real problem can arise. The loop driver, using `copy_folio_from_iter_atomic`, may read the directory entry while it is being updated. This could lead to a corrupt directory entry. I had to consider several scenarios. First, if the loop device uses shared memory, the corruption is temporary since it is volatile. However, if the loop device points to a persistent file, a crash before a writeback can lead to a corrupted FAT filesystem on that backing file, which is a significant problem. Though, given the nature of FAT, which is not known for its crash resilience, this data race may add a very small window to potential crashes. The absence of journaling is already a huge window for corruption.
This leads me to the critical point: the `__fat_write_inode` function, which is ultimately responsible for these updates. I observed that `fat_sync_inode` calls `__fat_write_inode` and then calls `sync_dirty_buffer(bh)` which should handle writeback. The critical code writes to `raw_entry->size` before the call to `sync_dirty_buffer` where the buffer is locked. My analysis determined that the modification of the directory entry *precedes* the buffer locking during the writeback. This means if the loop driver is already performing an IO on the same buffer, a race exists: `raw_entry->size` could be changed while Task 2196 (the loop driver) is reading the data. A crash here, could lead to data corruption in the shmem or persistent file, because the loop driver may be processing the request already via `copy_folio_from_iter_atomic`.
If FAT was designed for "stable" metadata, locking would be essential to guarantee data integrity during these updates. This lack of locking suggests that FAT operates on a different consistency model. I'm now inclined to investigate similar KCSAN reports and the `fat_free` function within `fs/fat/file.c` to see if this pattern is consistent across other FAT operations. It seems the code intentionally omits the lock.
|
| 24/2 |
2026/02/24 21:29 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/file.c IncludeLines:true Name:fat_free]
Results: map[SourceCode: 309: /* Free all clusters after the skip'th cluster. */
310: static int fat_free(struct inode *inode, int skip)
311: {
312: struct super_block *sb = inode->i_sb;
313: int err, wait, free_start, i_start, i_logstart;
314:
315: if (MSDOS_I(inode)->i_start == 0)
316: return 0;
317:
318: fat_cache_inval_inode(inode);
319:
320: wait = IS_DIRSYNC(inode);
321: i_start = free_start = MSDOS_I(inode)->i_start;
322: i_logstart = MSDOS_I(inode)->i_logstart;
323:
324: /* First, we write the new file size. */
325: if (!skip) {
326: MSDOS_I(inode)->i_start = 0;
327: MSDOS_I(inode)->i_logstart = 0;
328: }
329: MSDOS_I(inode)->i_attrs |= ATTR_ARCH;
330: fat_truncate_time(inode, NULL, S_CTIME|S_MTIME);
331: if (wait) {
332: err = fat_sync_inode(inode);
333: if (err) {
334: MSDOS_I(inode)->i_start = i_start;
335: MSDOS_I(inode)->i_logstart = i_logstart;
336: return err;
337: }
338: } else
339: mark_inode_dirty(inode);
340:
341: /* Write a new EOF, and get the remaining cluster chain for freeing. */
342: if (skip) {
343: struct fat_entry fatent;
344: int ret, fclus, dclus;
345:
346: ret = fat_get_cluster(inode, skip - 1, &fclus, &dclus);
347: if (ret < 0)
348: return ret;
349: else if (ret == FAT_ENT_EOF)
350: return 0;
351:
352: fatent_init(&fatent);
353: ret = fat_ent_read(inode, &fatent, dclus);
354: if (ret == FAT_ENT_EOF) {
355: fatent_brelse(&fatent);
356: return 0;
357: } else if (ret == FAT_ENT_FREE) {
358: fat_fs_error(sb,
359: "%s: invalid cluster chain (i_pos %lld)",
360: __func__, MSDOS_I(inode)->i_pos);
361: ret = -EIO;
362: } else if (ret > 0) {
363: err = fat_ent_write(inode, &fatent, FAT_ENT_EOF, wait);
364: if (err)
365: ret = err;
366: }
367: fatent_brelse(&fatent);
368: if (ret < 0)
369: return ret;
370:
371: free_start = ret;
372: }
373: inode->i_blocks = skip << (MSDOS_SB(sb)->cluster_bits - 9);
374:
375: /* Freeing the remained cluster chain */
376: return fat_free_clusters(inode, free_start);
377: }
SourceFile:fs/fat/file.c]
|
| 25/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 33349
output: 27
thoughts: 752
Thoughts: **Analyzing a Potential Race Condition in the FAT Filesystem**
Okay, so I'm digging into this `fat_free` function and specifically the metadata synchronization logic. My initial thought is that if `wait` is set to true, it calls `fat_sync_inode`, which means we're dealing with `DIRSYNC` and wanting to ensure the metadata is actually on disk. But here's the kicker: even when `DIRSYNC` is active, the code in `__fat_write_inode` doesn't seem to hold a lock while it modifies the buffer. It updates the buffer, *then* calls `sync_dirty_buffer`.
Now, if that buffer was *already* dirty and undergoing writeback, `sync_dirty_buffer` will wait for that existing I/O to complete before starting a new one. The problem is, that *current* I/O could have already read and partially written the buffer to disk *before* my changes are reflected! Effectively, the first I/O writes "garbage" data. The `sync_dirty_buffer` call then initiates a new I/O to correct the data, and so we have the wrong data being written before the correct data. If we crash in between these writes, we're left with garbage data on disk.
So is this a bug? It's not immediately obvious. The user expects their metadata to be on disk after the `fat_free` call returns with `DIRSYNC` set, and it *will* be. But the intermediate state of possibly writing garbage is… suboptimal, shall we say.
But is it actually harmful, in the KCSAN sense? The typical KCSAN-defined harms involve memory corruption, crashes, or compiler-introduced logic errors due to races. A simple assignment like `raw_entry->size = cpu_to_le32(inode->i_size)` is unlikely to be messed with by the compiler. The race is between two threads: one modifying the buffer and the disk's loop driver that is doing the reading.
Now, if the loop driver were a real disk, we'd see the same thing. DMA might be in progress while memory changes, meaning the disk gets whatever it gets at that moment. Many filesystems will have this "problem," which is what I've encountered looking this up. The general consensus is that this is usually okay for most filesystems because they'll just re-dirty the buffer and it will eventually be written correctly.
But wait. There's a specific case where this becomes problematic: block devices requiring "stable writes." These are devices that perform checksumming, such as RAID devices. They calculate the checksum *before* the write and then write the data. If the data changes *after* the checksum but *before* the write, the checksum on disk will be wrong. When the block is read back, the checksum will fail, and we have considered the block corrupt.
Does the loop device have this requirement? No. Does `shmem`? No. So, in this specific configuration, it's likely harmless. But in general, on a block device requiring stable writes, this *is* a potential problem for FAT. The kernel, sensibly, has the `BDI_CAP_STABLE_WRITES` flag to indicate devices with this requirement. If that flag is set, the filesystem should wait for writeback before making modifications. FAT doesn't seem to check for this capability. I'd better check and see if FAT handles stable writes anywhere else. I'll search for `wait_on_page_writeback` in `fs/fat/`.
|
| 26/2 |
2026/02/24 21:30 |
tool |
grepper |
0m
Error:
Args: map[Expression:wait_on_page_writeback.*fs/fat/]
Results:
|
| 27/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 34905
output: 41
thoughts: 19
Thoughts: Okay, here's my interpretation of that thought process, assuming I'm an expert in this field, and speaking from the first-person perspective:
**Initial Assessment and Deep Dive**
Hmm, that's not quite right. Wait a second, hold on, I need to check something... let me immediately jump into the `fat_write_begin` function. I have a feeling the issue likely lies within that crucial section of the code. That's the first place I'd look in this situation.
|
| 28/2 |
2026/02/24 21:30 |
tool |
codesearch-definition-source |
0m
Args: map[ContextFile:fs/fat/inode.c IncludeLines:true Name:fat_write_begin]
Results: map[SourceCode: 223: static int fat_write_begin(const struct kiocb *iocb,
224: struct address_space *mapping,
225: loff_t pos, unsigned len,
226: struct folio **foliop, void **fsdata)
227: {
228: int err;
229:
230: err = cont_write_begin(iocb, mapping, pos, len,
231: foliop, fsdata, fat_get_block,
232: &MSDOS_I(mapping->host)->mmu_private);
233: if (err < 0)
234: fat_write_failed(mapping, pos + len);
235: return err;
236: }
SourceFile:fs/fat/inode.c]
|
| 29/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 35318
output: 43
thoughts: 697
Thoughts: **Benign FAT Metadata Race Condition: A Detailed Examination**
Okay, here's what I'm thinking about this issue. The function `cont_write_begin` is pretty generic, but we're dealing specifically with metadata buffers here, not the actual file data pages. In FAT, metadata buffers are managed using `sb_bread` and `mark_buffer_dirty`.
Now, if we were aiming for robust, stable writes in FAT, especially on a device that demands it, we'd be missing some essential synchronization primitives. However, FAT's usual home is SD cards and USB sticks, and these devices don't necessarily need the strong write stability that the block layer provides.
Considering the age of FAT, the long history of this implementation, and the nature of the potential "harm" – a temporary inconsistency on disk that's rectified by the next write – I'm leaning towards calling this benign. Plus, this particular "read" appears to come from a loop driver writing to shmem, which is very typical for syzkaller tests, and not necessarily a production environment where metadata consistency is the top priority. And honestly, if metadata consistency *were* critical, you wouldn't typically choose FAT in the first place.
But, let's step back and re-examine the KCSAN report. Is there anything else that could be going on here? We have a 4-byte write clashing with a 1024-byte read. The race is definitely focused on those 4 bytes.
Now, could the compiler be doing something odd, like splitting that 4-byte write into four separate 1-byte writes? On x86, with a 4-byte aligned `__le32`, it's almost guaranteed the compiler will use a single `mov` instruction. Even if it *didn't*, the result remains the same: inconsistent data on disk, which is ultimately corrected.
I have to wonder if the loop driver could crash as well. Let me look at the code: `copy_folio_from_iter_atomic` -> `memcpy_from_iter` -> `iterate_bvec` -> `memcpy`. A `memcpy` from valid memory is safe.
So, I'm confident in calling this benign. But just to be absolutely sure, let me verify something: should `__fat_write_inode` be using `lock_buffer`? Let's compare it to `ext2_write_inode`, another old filesystem:
```c
static int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct buffer_head *bh;
struct ext2_inode *raw_inode;
int err = 0;
raw_inode = ext2_get_inode(inode->i_sb, inode->i_ino, &bh);
if (IS_ERR(raw_inode))
return PTR_ERR(raw_inode);
// ... updates raw_inode ...
mark_buffer_dirty(bh);
if (wbc->sync_mode == WB_SYNC_ALL) {
sync_dirty_buffer(bh);
if (buffer_req(bh) && !buffer_uptodate(bh))
err = -EIO;
}
brelse(bh);
return err;
}
```
Wait, now I have to check `ext2_get_inode`. Does *it* lock the buffer? I'll look into `fs/ext2/inode.c`.
|
| 30/2 |
2026/02/24 21:30 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:fs/ext2/inode.c IncludeLines:true Name:ext2_get_inode]
Results: map[SourceCode: SourceFile:]
|
| 31/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 36867
output: 43
thoughts: 32
Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience:
**Debugging a Possible Naming Discrepancy**
Hmm, a potential misnomer has popped into my head. I'm operating under the assumption that a certain function name is correct, but a nagging feeling is prompting a sanity check. Let's not waste time speculating; I need to verify that my mental model is aligned with the codebase. Specifically, the function I'm concerned about is `ext2_write_inode`. Time to navigate to `fs/ext2/inode.c`. That should clear things up quickly. I'll confirm the function's actual name and its exact purpose to settle this minor point before I continue. Gotta stay precise.
|
| 32/2 |
2026/02/24 21:30 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:fs/ext2/inode.c IncludeLines:true Name:ext2_write_inode]
Results: map[SourceCode: SourceFile:]
|
| 33/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 37120
output: 20
thoughts: 16
Thoughts: Here's my attempt at summarizing the thought process, tailored for an expert audience:
**Tracing Down `ext2_write_inode`**
Okay, first things first, I need to pinpoint the `ext2_write_inode` function. It's fundamental for understanding how the ext2 filesystem persists inode metadata changes. I need to refresh my memory of where this is defined, I'm going to look in the kernel source to make sure I know which one. I am pretty sure its the one in the `fs/ext2/inode.c` file, or perhaps the `fs/ext2/` directory? Let me check to be sure. I'm especially interested in its interaction with the block allocation routines and the journal (if enabled). I'll also check the call graph to see what functions call it, and what it depends on. Knowing the calling context is key. Is it being invoked directly after a `write()` system call, or are there layers of caching and buffering involved? Understanding the locking mechanisms it employs is critical to avoiding deadlocks and data corruption, given how inodes can be accessed concurrently by many processes. I need to consider the implications of the inode modification time, and its interaction with the superblock and journal. I'm going to look at the different code paths within `ext2_write_inode` based on whether the inode is dirty, a new inode, or if it involves extended attributes.
|
| 34/2 |
2026/02/24 21:30 |
tool |
grepper |
0m
Args: map[Expression:ext2_write_inode]
Results: map[Output:fs/ext2/ext2.h=740=extern struct inode *ext2_iget (struct super_block *, unsigned long);
fs/ext2/ext2.h:741:extern int ext2_write_inode (struct inode *, struct writeback_control *);
fs/ext2/ext2.h-742-extern void ext2_evict_inode(struct inode *);
--
fs/ext2/inode.c-42-
fs/ext2/inode.c:43:static int __ext2_write_inode(struct inode *inode, int do_sync);
fs/ext2/inode.c-44-
--
fs/ext2/inode.c=72=void ext2_evict_inode(struct inode * inode)
--
fs/ext2/inode.c-90- mark_inode_dirty(inode);
fs/ext2/inode.c:91: __ext2_write_inode(inode, inode_needs_sync(inode));
fs/ext2/inode.c-92- /* truncate to 0 */
--
fs/ext2/inode.c=1387=struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
--
fs/ext2/inode.c-1511-
fs/ext2/inode.c:1512:static int __ext2_write_inode(struct inode *inode, int do_sync)
fs/ext2/inode.c-1513-{
--
fs/ext2/inode.c-1615-
fs/ext2/inode.c:1616:int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
fs/ext2/inode.c-1617-{
fs/ext2/inode.c:1618: return __ext2_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
fs/ext2/inode.c-1619-}
--
fs/ext2/super.c=366=static const struct super_operations ext2_sops = {
--
fs/ext2/super.c-368- .free_inode = ext2_free_in_core_inode,
fs/ext2/super.c:369: .write_inode = ext2_write_inode,
fs/ext2/super.c-370- .evict_inode = ext2_evict_inode,
]
|
| 35/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 38072
output: 44
thoughts: 16
Thoughts: Okay, here we go, diving into `__ext2_write_inode`.
**My Process: Deconstructing `__ext2_write_inode`**
Alright, time to dissect this function. The name itself gives us the goal: it's about writing an inode in the ext2 filesystem. That tells me this is a pretty fundamental operation, likely called whenever an inode needs to be updated on disk. Thinking about it, this could be due to changes in file metadata (size, permissions, timestamps), or even block assignment changes. I'll need to remember that these writes are critical for filesystem integrity. A bad write, or an interrupted one, could lead to severe data corruption.
I suspect this routine handles the actual physical writing to the disk, so it probably takes the inode structure itself and translates it into the on-disk format, incorporating things like block addressing, the inode number, and of course, those vital metadata fields. It will probably have to deal with things like checksumming or journaling in more modern filesystems. I bet there are checks for valid block ranges, ensuring that the new inode doesn't overwrite anything important, and probably some locking to ensure no other process is touching the inode at the same time.
I wonder what kind of error handling this function will have? Does it simply return an error code, or does it try to signal a more drastic filesystem error, possibly mounting it read-only? I need to look closely at those error paths to understand how resilient the write operation is. I'll also check what other functions are called during the inode write process, to understand the overall architecture. I anticipate there will be calls to lower-level routines that handle the actual disk writes, possibly using a block device interface.
Okay, let's see how well my hypothesis holds up when I look at the source code!
|
| 36/2 |
2026/02/24 21:30 |
tool |
codesearch-definition-source |
0m
Error:
Args: map[ContextFile:fs/ext2/inode.c IncludeLines:true Name:__ext2_write_inode]
Results: map[SourceCode: SourceFile:]
|
| 37/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 38533
output: 23
thoughts: 20
Thoughts: Okay, here's my interpretation of those thoughts, tailored for an expert audience, presented in the first person:
**Ah, Ha! The Grep Strikes Again (Almost)**
Okay, initially I was on the right track, but I missed something crucial in the `grep` output. A minor oversight, really. That first pass, while promising, was pointing me in the wrong direction. I got excited by what I *thought* I saw, but I need to go back and cross-reference my understanding.
I need to confirm the *exact* file I was looking for. Now that I have the correct file in view, let's execute the command again, ensuring it's the target location. This second run will either immediately confirm my hypothesis or provide a clear path forward.
|
| 38/2 |
2026/02/24 21:30 |
tool |
read-file |
0m
Args: map[File:fs/ext2/inode.c]
Results: map[Contents:// SPDX-License-Identifier: GPL-2.0
/*
* linux/fs/ext2/inode.c
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card (card@masi.ibp.fr)
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/fs/minix/inode.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Goal-directed block allocation by Stephen Tweedie
* (sct@dcs.ed.ac.uk), 1993, 1998
* Big-endian to little-endian byte-swapping/bitmaps by
* David S. Miller (davem@caip.rutgers.edu), 1995
* 64-bit file support on 64-bit platforms by Jakub Jelinek
* (jj@sunsite.ms.mff.cuni.cz)
*
* Assorted race fixes, rewrite of ext2_get_block() by Al Viro, 2000
*/
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
#include <linux/dax.h>
#include <linux/blkdev.h>
#include <linux/quotaops.h>
#include <linux/writeback.h>
#include <linux/buffer_head.h>
#include <linux/mpage.h>
#include <linux/fiemap.h>
#include <linux/iomap.h>
#include <linux/namei.h>
#include <linux/uio.h>
#include "ext2.h"
#include "acl.h"
#include "xattr.h"
static int __ext2_write_inode(struct inode *inode, int do_sync);
/*
* Test whether an inode is a fast symlink.
*/
static inline int ext2_inode_is_fast_symlink(struct inode *inode)
{
int ea_blocks = EXT2_I(inode)->i_file_acl ?
(inode->i_sb->s_blocksize >> 9) : 0;
return (S_ISLNK(inode->i_mode) &&
inode->i_blocks - ea_blocks == 0);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset);
void ext2_write_failed(struct address_space *mapping, loff_t to)
{
struct inode *inode = mapping->host;
if (to > inode->i_size) {
truncate_pagecache(inode, inode->i_size);
ext2_truncate_blocks(inode, inode->i_size);
}
}
/*
* Called at the last iput() if i_nlink is zero.
*/
void ext2_evict_inode(struct inode * inode)
{
struct ext2_block_alloc_info *rsv;
int want_delete = 0;
if (!inode->i_nlink && !is_bad_inode(inode)) {
want_delete = 1;
dquot_initialize(inode);
} else {
dquot_drop(inode);
}
truncate_inode_pages_final(&inode->i_data);
if (want_delete) {
sb_start_intwrite(inode->i_sb);
/* set dtime */
EXT2_I(inode)->i_dtime = ktime_get_real_seconds();
mark_inode_dirty(inode);
__ext2_write_inode(inode, inode_needs_sync(inode));
/* truncate to 0 */
inode->i_size = 0;
if (inode->i_blocks)
ext2_truncate_blocks(inode, 0);
ext2_xattr_delete_inode(inode);
}
invalidate_inode_buffers(inode);
clear_inode(inode);
ext2_discard_reservation(inode);
rsv = EXT2_I(inode)->i_block_alloc_info;
EXT2_I(inode)->i_block_alloc_info = NULL;
if (unlikely(rsv))
kfree(rsv);
if (want_delete) {
ext2_free_inode(inode);
sb_end_intwrite(inode->i_sb);
}
}
typedef struct {
__le32 *p;
__le32 key;
struct buffer_head *bh;
} Indirect;
static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
{
p->key = *(p->p = v);
p->bh = bh;
}
static inline int verify_chain(Indirect *from, Indirect *to)
{
while (from <= to && from->key == *from->p)
from++;
return (from > to);
}
/**
* ext2_block_to_path - parse the block number into array of offsets
* @inode: inode in question (we are only interested in its superblock)
* @i_block: block number to be parsed
* @offsets: array to store the offsets in
* @boundary: set this non-zero if the referred-to block is likely to be
* followed (on disk) by an indirect block.
* To store the locations of file's data ext2 uses a data structure common
* for UNIX filesystems - tree of pointers anchored in the inode, with
* data blocks at leaves and indirect blocks in intermediate nodes.
* This function translates the block number into path in that tree -
* return value is the path length and @offsets[n] is the offset of
* pointer to (n+1)th node in the nth one. If @block is out of range
* (negative or too large) warning is printed and zero returned.
*
* Note: function doesn't find node addresses, so no IO is needed. All
* we need to know is the capacity of indirect blocks (taken from the
* inode->i_sb).
*/
/*
* Portability note: the last comparison (check that we fit into triple
* indirect block) is spelled differently, because otherwise on an
* architecture with 32-bit longs and 8Kb pages we might get into trouble
* if our filesystem had 8Kb blocks. We might use long long, but that would
* kill us on x86. Oh, well, at least the sign propagation does not matter -
* i_block would have to be negative in the very beginning, so we would not
* get there at all.
*/
static int ext2_block_to_path(struct inode *inode,
long i_block, int offsets[4], int *boundary)
{
int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
const long direct_blocks = EXT2_NDIR_BLOCKS,
indirect_blocks = ptrs,
double_blocks = (1 << (ptrs_bits * 2));
int n = 0;
int final = 0;
if (i_block < 0) {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block < 0", __func__);
} else if (i_block < direct_blocks) {
offsets[n++] = i_block;
final = direct_blocks;
} else if ( (i_block -= direct_blocks) < indirect_blocks) {
offsets[n++] = EXT2_IND_BLOCK;
offsets[n++] = i_block;
final = ptrs;
} else if ((i_block -= indirect_blocks) < double_blocks) {
offsets[n++] = EXT2_DIND_BLOCK;
offsets[n++] = i_block >> ptrs_bits;
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
offsets[n++] = EXT2_TIND_BLOCK;
offsets[n++] = i_block >> (ptrs_bits * 2);
offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
offsets[n++] = i_block & (ptrs - 1);
final = ptrs;
} else {
ext2_msg(inode->i_sb, KERN_WARNING,
"warning: %s: block is too big", __func__);
}
if (boundary)
*boundary = final - 1 - (i_block & (ptrs - 1));
return n;
}
/**
* ext2_get_branch - read the chain of indirect blocks leading to data
* @inode: inode in question
* @depth: depth of the chain (1 - direct pointer, etc.)
* @offsets: offsets of pointers in inode/indirect blocks
* @chain: place to store the result
* @err: here we store the error value
*
* Function fills the array of triples <key, p, bh> and returns %NULL
* if everything went OK or the pointer to the last filled triple
* (incomplete one) otherwise. Upon the return chain[i].key contains
* the number of (i+1)-th block in the chain (as it is stored in memory,
* i.e. little-endian 32-bit), chain[i].p contains the address of that
* number (it points into struct inode for i==0 and into the bh->b_data
* for i>0) and chain[i].bh points to the buffer_head of i-th indirect
* block for i>0 and NULL for i==0. In other words, it holds the block
* numbers of the chain, addresses they were taken from (and where we can
* verify that chain did not change) and buffer_heads hosting these
* numbers.
*
* Function stops when it stumbles upon zero pointer (absent block)
* (pointer to last triple returned, *@err == 0)
* or when it gets an IO error reading an indirect block
* (ditto, *@err == -EIO)
* or when it notices that chain had been changed while it was reading
* (ditto, *@err == -EAGAIN)
* or when it reads all @depth-1 indirect blocks successfully and finds
* the whole chain, all way to the data (returns %NULL, *err == 0).
*/
static Indirect *ext2_get_branch(struct inode *inode,
int depth,
int *offsets,
Indirect chain[4],
int *err)
{
struct super_block *sb = inode->i_sb;
Indirect *p = chain;
struct buffer_head *bh;
*err = 0;
/* i_data is not going away, no lock needed */
add_chain (chain, NULL, EXT2_I(inode)->i_data + *offsets);
if (!p->key)
goto no_block;
while (--depth) {
bh = sb_bread(sb, le32_to_cpu(p->key));
if (!bh)
goto failure;
read_lock(&EXT2_I(inode)->i_meta_lock);
if (!verify_chain(chain, p))
goto changed;
add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
read_unlock(&EXT2_I(inode)->i_meta_lock);
if (!p->key)
goto no_block;
}
return NULL;
changed:
read_unlock(&EXT2_I(inode)->i_meta_lock);
brelse(bh);
*err = -EAGAIN;
goto no_block;
failure:
*err = -EIO;
no_block:
return p;
}
/**
* ext2_find_near - find a place for allocation with sufficient locality
* @inode: owner
* @ind: descriptor of indirect block.
*
* This function returns the preferred place for block allocation.
* It is used when heuristic for sequential allocation fails.
* Rules are:
* + if there is a block to the left of our position - allocate near it.
* + if pointer will live in indirect block - allocate near that block.
* + if pointer will live in inode - allocate in the same cylinder group.
*
* In the latter case we colour the starting block by the callers PID to
* prevent it from clashing with concurrent allocations for a different inode
* in the same block group. The PID is used here so that functionally related
* files will be close-by on-disk.
*
* Caller must make sure that @ind is valid and will stay that way.
*/
static ext2_fsblk_t ext2_find_near(struct inode *inode, Indirect *ind)
{
struct ext2_inode_info *ei = EXT2_I(inode);
__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
__le32 *p;
ext2_fsblk_t bg_start;
ext2_fsblk_t colour;
/* Try to find previous block */
for (p = ind->p - 1; p >= start; p--)
if (*p)
return le32_to_cpu(*p);
/* No such thing, so let's try location of indirect block */
if (ind->bh)
return ind->bh->b_blocknr;
/*
* It is going to be referred from inode itself? OK, just put it into
* the same cylinder group then.
*/
bg_start = ext2_group_first_block_no(inode->i_sb, ei->i_block_group);
colour = (current->pid % 16) *
(EXT2_BLOCKS_PER_GROUP(inode->i_sb) / 16);
return bg_start + colour;
}
/**
* ext2_find_goal - find a preferred place for allocation.
* @inode: owner
* @block: block we want
* @partial: pointer to the last triple within a chain
*
* Returns preferred place for a block (the goal).
*/
static inline ext2_fsblk_t ext2_find_goal(struct inode *inode, long block,
Indirect *partial)
{
struct ext2_block_alloc_info *block_i;
block_i = EXT2_I(inode)->i_block_alloc_info;
/*
* try the heuristic for sequential allocation,
* failing that at least try to get decent locality.
*/
if (block_i && (block == block_i->last_alloc_logical_block + 1)
&& (block_i->last_alloc_physical_block != 0)) {
return block_i->last_alloc_physical_block + 1;
}
return ext2_find_near(inode, partial);
}
/**
* ext2_blks_to_allocate: Look up the block map and count the number
* of direct blocks need to be allocated for the given branch.
*
* @branch: chain of indirect blocks
* @k: number of blocks need for indirect blocks
* @blks: number of data blocks to be mapped.
* @blocks_to_boundary: the offset in the indirect block
*
* return the number of direct blocks to allocate.
*/
static int
ext2_blks_to_allocate(Indirect * branch, int k, unsigned long blks,
int blocks_to_boundary)
{
unsigned long count = 0;
/*
* Simple case, [t,d]Indirect block(s) has not allocated yet
* then it's clear blocks on that path have not allocated
*/
if (k > 0) {
/* right now don't hanel cross boundary allocation */
if (blks < blocks_to_boundary + 1)
count += blks;
else
count += blocks_to_boundary + 1;
return count;
}
count++;
while (count < blks && count <= blocks_to_boundary
&& le32_to_cpu(*(branch[0].p + count)) == 0) {
count++;
}
return count;
}
/**
* ext2_alloc_blocks: Allocate multiple blocks needed for a branch.
* @inode: Owner.
* @goal: Preferred place for allocation.
* @indirect_blks: The number of blocks needed to allocate for indirect blocks.
* @blks: The number of blocks need to allocate for direct blocks.
* @new_blocks: On return it will store the new block numbers for
* the indirect blocks(if needed) and the first direct block.
* @err: Error pointer.
*
* Return: Number of blocks allocated.
*/
static int ext2_alloc_blocks(struct inode *inode,
ext2_fsblk_t goal, int indirect_blks, int blks,
ext2_fsblk_t new_blocks[4], int *err)
{
int target, i;
unsigned long count = 0;
int index = 0;
ext2_fsblk_t current_block = 0;
int ret = 0;
/*
* Here we try to allocate the requested multiple blocks at once,
* on a best-effort basis.
* To build a branch, we should allocate blocks for
* the indirect blocks(if not allocated yet), and at least
* the first direct block of this branch. That's the
* minimum number of blocks need to allocate(required)
*/
target = blks + indirect_blks;
while (1) {
count = target;
/* allocating blocks for indirect blocks and direct blocks */
current_block = ext2_new_blocks(inode, goal, &count, err, 0);
if (*err)
goto failed_out;
target -= count;
/* allocate blocks for indirect blocks */
while (index < indirect_blks && count) {
new_blocks[index++] = current_block++;
count--;
}
if (count > 0)
break;
}
/* save the new block number for the first direct block */
new_blocks[index] = current_block;
/* total number of blocks allocated for direct blocks */
ret = count;
*err = 0;
return ret;
failed_out:
for (i = 0; i <index; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
if (index)
mark_inode_dirty(inode);
return ret;
}
/**
* ext2_alloc_branch - allocate and set up a chain of blocks.
* @inode: owner
* @indirect_blks: depth of the chain (number of blocks to allocate)
* @blks: number of allocated direct blocks
* @goal: preferred place for allocation
* @offsets: offsets (in the blocks) to store the pointers to next.
* @branch: place to store the chain in.
*
* This function allocates @num blocks, zeroes out all but the last one,
* links them into chain and (if we are synchronous) writes them to disk.
* In other words, it prepares a branch that can be spliced onto the
* inode. It stores the information about that chain in the branch[], in
* the same format as ext2_get_branch() would do. We are calling it after
* we had read the existing part of chain and partial points to the last
* triple of that (one with zero ->key). Upon the exit we have the same
* picture as after the successful ext2_get_block(), except that in one
* place chain is disconnected - *branch->p is still zero (we did not
* set the last link), but branch->key contains the number that should
* be placed into *branch->p to fill that gap.
*
* If allocation fails we free all blocks we've allocated (and forget
* their buffer_heads) and return the error value the from failed
* ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
* as described above and return 0.
*/
static int ext2_alloc_branch(struct inode *inode,
int indirect_blks, int *blks, ext2_fsblk_t goal,
int *offsets, Indirect *branch)
{
int blocksize = inode->i_sb->s_blocksize;
int i, n = 0;
int err = 0;
struct buffer_head *bh;
int num;
ext2_fsblk_t new_blocks[4];
ext2_fsblk_t current_block;
num = ext2_alloc_blocks(inode, goal, indirect_blks,
*blks, new_blocks, &err);
if (err)
return err;
branch[0].key = cpu_to_le32(new_blocks[0]);
/*
* metadata blocks and data blocks are allocated.
*/
for (n = 1; n <= indirect_blks; n++) {
/*
* Get buffer_head for parent block, zero it out
* and set the pointer to new one, then send
* parent to disk.
*/
bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
if (unlikely(!bh)) {
err = -ENOMEM;
goto failed;
}
branch[n].bh = bh;
lock_buffer(bh);
memset(bh->b_data, 0, blocksize);
branch[n].p = (__le32 *) bh->b_data + offsets[n];
branch[n].key = cpu_to_le32(new_blocks[n]);
*branch[n].p = branch[n].key;
if ( n == indirect_blks) {
current_block = new_blocks[n];
/*
* End of chain, update the last new metablock of
* the chain to point to the new allocated
* data blocks numbers
*/
for (i=1; i < num; i++)
*(branch[n].p + i) = cpu_to_le32(++current_block);
}
set_buffer_uptodate(bh);
unlock_buffer(bh);
mark_buffer_dirty_inode(bh, inode);
/* We used to sync bh here if IS_SYNC(inode).
* But we now rely upon generic_write_sync()
* and b_inode_buffers. But not for directories.
*/
if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
sync_dirty_buffer(bh);
}
*blks = num;
return err;
failed:
for (i = 1; i < n; i++)
bforget(branch[i].bh);
for (i = 0; i < indirect_blks; i++)
ext2_free_blocks(inode, new_blocks[i], 1);
ext2_free_blocks(inode, new_blocks[i], num);
return err;
}
/**
* ext2_splice_branch - splice the allocated branch onto inode.
* @inode: owner
* @block: (logical) number of block we are adding
* @where: location of missing link
* @num: number of indirect blocks we are adding
* @blks: number of direct blocks we are adding
*
* This function fills the missing link and does all housekeeping needed in
* inode (->i_blocks, etc.). In case of success we end up with the full
* chain to new block and return 0.
*/
static void ext2_splice_branch(struct inode *inode,
long block, Indirect *where, int num, int blks)
{
int i;
struct ext2_block_alloc_info *block_i;
ext2_fsblk_t current_block;
block_i = EXT2_I(inode)->i_block_alloc_info;
/* XXX LOCKING probably should have i_meta_lock ?*/
/* That's it */
*where->p = where->key;
/*
* Update the host buffer_head or inode to point to more just allocated
* direct blocks blocks
*/
if (num == 0 && blks > 1) {
current_block = le32_to_cpu(where->key) + 1;
for (i = 1; i < blks; i++)
*(where->p + i ) = cpu_to_le32(current_block++);
}
/*
* update the most recently allocated logical & physical block
* in i_block_alloc_info, to assist find the proper goal block for next
* allocation
*/
if (block_i) {
block_i->last_alloc_logical_block = block + blks - 1;
block_i->last_alloc_physical_block =
le32_to_cpu(where[num].key) + blks - 1;
}
/* We are done with atomic stuff, now do the rest of housekeeping */
/* had we spliced it onto indirect block? */
if (where->bh)
mark_buffer_dirty_inode(where->bh, inode);
inode_set_ctime_current(inode);
mark_inode_dirty(inode);
}
/*
* Allocation strategy is simple: if we have to allocate something, we will
* have to go the whole way to leaf. So let's do it before attaching anything
* to tree, set linkage between the newborn blocks, write them if sync is
* required, recheck the path, free and repeat if check fails, otherwise
* set the last missing link (that will protect us from any truncate-generated
* removals - all blocks on the path are immune now) and possibly force the
* write on the parent block.
* That has a nice additional property: no special recovery from the failed
* allocations is needed - we simply release blocks and do not touch anything
* reachable from inode.
*
* `handle' can be NULL if create == 0.
*
* return > 0, # of blocks mapped or allocated.
* return = 0, if plain lookup failed.
* return < 0, error case.
*/
static int ext2_get_blocks(struct inode *inode,
sector_t iblock, unsigned long maxblocks,
u32 *bno, bool *new, bool *boundary,
int create)
{
int err;
int offsets[4];
Indirect chain[4];
Indirect *partial;
ext2_fsblk_t goal;
int indirect_blks;
int blocks_to_boundary = 0;
int depth;
struct ext2_inode_info *ei = EXT2_I(inode);
int count = 0;
ext2_fsblk_t first_block = 0;
BUG_ON(maxblocks == 0);
depth = ext2_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
if (depth == 0)
return -EIO;
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
/* Simplest case - block found, no allocation needed */
if (!partial) {
first_block = le32_to_cpu(chain[depth - 1].key);
count++;
/*map more blocks*/
while (count < maxblocks && count <= blocks_to_boundary) {
ext2_fsblk_t blk;
if (!verify_chain(chain, chain + depth - 1)) {
/*
* Indirect block might be removed by
* truncate while we were reading it.
* Handling of that case: forget what we've
* got now, go to reread.
*/
err = -EAGAIN;
count = 0;
partial = chain + depth - 1;
break;
}
blk = le32_to_cpu(*(chain[depth-1].p + count));
if (blk == first_block + count)
count++;
else
break;
}
if (err != -EAGAIN)
goto got_it;
}
/* Next simple case - plain lookup or failed read of indirect block */
if (!create || err == -EIO)
goto cleanup;
mutex_lock(&ei->truncate_mutex);
/*
* If the indirect block is missing while we are reading
* the chain(ext2_get_branch() returns -EAGAIN err), or
* if the chain has been changed after we grab the semaphore,
* (either because another process truncated this branch, or
* another get_block allocated this branch) re-grab the chain to see if
* the request block has been allocated or not.
*
* Since we already block the truncate/other get_block
* at this point, we will have the current copy of the chain when we
* splice the branch into the tree.
*/
if (err == -EAGAIN || !verify_chain(chain, partial)) {
while (partial > chain) {
brelse(partial->bh);
partial--;
}
partial = ext2_get_branch(inode, depth, offsets, chain, &err);
if (!partial) {
count++;
mutex_unlock(&ei->truncate_mutex);
goto got_it;
}
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
}
/*
* Okay, we need to do block allocation. Lazily initialize the block
* allocation info here if necessary
*/
if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
ext2_init_block_alloc_info(inode);
goal = ext2_find_goal(inode, iblock, partial);
/* the number of blocks need to allocate for [d,t]indirect blocks */
indirect_blks = (chain + depth) - partial - 1;
/*
* Next look up the indirect map to count the total number of
* direct blocks to allocate for this branch.
*/
count = ext2_blks_to_allocate(partial, indirect_blks,
maxblocks, blocks_to_boundary);
/*
* XXX ???? Block out ext2_truncate while we alter the tree
*/
err = ext2_alloc_branch(inode, indirect_blks, &count, goal,
offsets + (partial - chain), partial);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
if (IS_DAX(inode)) {
/*
* We must unmap blocks before zeroing so that writeback cannot
* overwrite zeros with stale data from block device page cache.
*/
clean_bdev_aliases(inode->i_sb->s_bdev,
le32_to_cpu(chain[depth-1].key),
count);
/*
* block must be initialised before we put it in the tree
* so that it's not found by another thread before it's
* initialised
*/
err = sb_issue_zeroout(inode->i_sb,
le32_to_cpu(chain[depth-1].key), count,
GFP_KERNEL);
if (err) {
mutex_unlock(&ei->truncate_mutex);
goto cleanup;
}
}
*new = true;
ext2_splice_branch(inode, iblock, partial, indirect_blks, count);
mutex_unlock(&ei->truncate_mutex);
got_it:
if (count > blocks_to_boundary)
*boundary = true;
err = count;
/* Clean up and exit */
partial = chain + depth - 1; /* the whole chain */
cleanup:
while (partial > chain) {
brelse(partial->bh);
partial--;
}
if (err > 0)
*bno = le32_to_cpu(chain[depth-1].key);
return err;
}
int ext2_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
bool new = false, boundary = false;
u32 bno;
int ret;
ret = ext2_get_blocks(inode, iblock, max_blocks, &bno, &new, &boundary,
create);
if (ret <= 0)
return ret;
map_bh(bh_result, inode->i_sb, bno);
bh_result->b_size = (ret << inode->i_blkbits);
if (new)
set_buffer_new(bh_result);
if (boundary)
set_buffer_boundary(bh_result);
return 0;
}
static int ext2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
unsigned flags, struct iomap *iomap, struct iomap *srcmap)
{
unsigned int blkbits = inode->i_blkbits;
unsigned long first_block = offset >> blkbits;
unsigned long max_blocks = (length + (1 << blkbits) - 1) >> blkbits;
struct ext2_sb_info *sbi = EXT2_SB(inode->i_sb);
bool new = false, boundary = false;
u32 bno;
int ret;
bool create = flags & IOMAP_WRITE;
/*
* For writes that could fill holes inside i_size on a
* DIO_SKIP_HOLES filesystem we forbid block creations: only
* overwrites are permitted.
*/
if ((flags & IOMAP_DIRECT) &&
(first_block << blkbits) < i_size_read(inode))
create = 0;
/*
* Writes that span EOF might trigger an IO size update on completion,
* so consider them to be dirty for the purposes of O_DSYNC even if
* there is no other metadata changes pending or have been made here.
*/
if ((flags & IOMAP_WRITE) && offset + length > i_size_read(inode))
iomap->flags |= IOMAP_F_DIRTY;
ret = ext2_get_blocks(inode, first_block, max_blocks,
&bno, &new, &boundary, create);
if (ret < 0)
return ret;
iomap->flags = 0;
iomap->offset = (u64)first_block << blkbits;
if (flags & IOMAP_DAX)
iomap->dax_dev = sbi->s_daxdev;
else
iomap->bdev = inode->i_sb->s_bdev;
if (ret == 0) {
/*
* Switch to buffered-io for writing to holes in a non-extent
* based filesystem to avoid stale data exposure problem.
*/
if (!create && (flags & IOMAP_WRITE) && (flags & IOMAP_DIRECT))
return -ENOTBLK;
iomap->type = IOMAP_HOLE;
iomap->addr = IOMAP_NULL_ADDR;
iomap->length = 1 << blkbits;
} else {
iomap->type = IOMAP_MAPPED;
iomap->addr = (u64)bno << blkbits;
if (flags & IOMAP_DAX)
iomap->addr += sbi->s_dax_part_off;
iomap->length = (u64)ret << blkbits;
iomap->flags |= IOMAP_F_MERGED;
}
if (new)
iomap->flags |= IOMAP_F_NEW;
return 0;
}
static int
ext2_iomap_end(struct inode *inode, loff_t offset, loff_t length,
ssize_t written, unsigned flags, struct iomap *iomap)
{
/*
* Switch to buffered-io in case of any error.
* Blocks allocated can be used by the buffered-io path.
*/
if ((flags & IOMAP_DIRECT) && (flags & IOMAP_WRITE) && written == 0)
return -ENOTBLK;
if (iomap->type == IOMAP_MAPPED &&
written < length &&
(flags & IOMAP_WRITE))
ext2_write_failed(inode->i_mapping, offset + length);
return 0;
}
const struct iomap_ops ext2_iomap_ops = {
.iomap_begin = ext2_iomap_begin,
.iomap_end = ext2_iomap_end,
};
int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
u64 start, u64 len)
{
int ret;
loff_t i_size;
inode_lock(inode);
i_size = i_size_read(inode);
/*
* iomap_fiemap() returns EINVAL for 0 length. Make sure we don't trim
* length to 0 but still trim the range as much as possible since
* ext2_get_blocks() iterates unmapped space block by block which is
* slow.
*/
if (i_size == 0)
i_size = 1;
len = min_t(u64, len, i_size);
ret = iomap_fiemap(inode, fieinfo, start, len, &ext2_iomap_ops);
inode_unlock(inode);
return ret;
}
static int ext2_read_folio(struct file *file, struct folio *folio)
{
return mpage_read_folio(folio, ext2_get_block);
}
static void ext2_readahead(struct readahead_control *rac)
{
mpage_readahead(rac, ext2_get_block);
}
static int
ext2_write_begin(const struct kiocb *iocb, struct address_space *mapping,
loff_t pos, unsigned len, struct folio **foliop, void **fsdata)
{
int ret;
ret = block_write_begin(mapping, pos, len, foliop, ext2_get_block);
if (ret < 0)
ext2_write_failed(mapping, pos + len);
return ret;
}
static int ext2_write_end(const struct kiocb *iocb,
struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct folio *folio, void *fsdata)
{
int ret;
ret = generic_write_end(iocb, mapping, pos, len, copied, folio, fsdata);
if (ret < len)
ext2_write_failed(mapping, pos + len);
return ret;
}
static sector_t ext2_bmap(struct address_space *mapping, sector_t block)
{
return generic_block_bmap(mapping,block,ext2_get_block);
}
static int
ext2_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
return mpage_writepages(mapping, wbc, ext2_get_block);
}
static int
ext2_dax_writepages(struct address_space *mapping, struct writeback_control *wbc)
{
struct ext2_sb_info *sbi = EXT2_SB(mapping->host->i_sb);
return dax_writeback_mapping_range(mapping, sbi->s_daxdev, wbc);
}
const struct address_space_operations ext2_aops = {
.dirty_folio = block_dirty_folio,
.invalidate_folio = block_invalidate_folio,
.read_folio = ext2_read_folio,
.readahead = ext2_readahead,
.write_begin = ext2_write_begin,
.write_end = ext2_write_end,
.bmap = ext2_bmap,
.writepages = ext2_writepages,
.migrate_folio = buffer_migrate_folio,
.is_partially_uptodate = block_is_partially_uptodate,
.error_remove_folio = generic_error_remove_folio,
};
static const struct address_space_operations ext2_dax_aops = {
.writepages = ext2_dax_writepages,
.dirty_folio = noop_dirty_folio,
};
/*
* Probably it should be a library function... search for first non-zero word
* or memcmp with zero_page, whatever is better for particular architecture.
* Linus?
*/
static inline int all_zeroes(__le32 *p, __le32 *q)
{
while (p < q)
if (*p++)
return 0;
return 1;
}
/**
* ext2_find_shared - find the indirect blocks for partial truncation.
* @inode: inode in question
* @depth: depth of the affected branch
* @offsets: offsets of pointers in that branch (see ext2_block_to_path)
* @chain: place to store the pointers to partial indirect blocks
* @top: place to the (detached) top of branch
*
* This is a helper function used by ext2_truncate().
*
* When we do truncate() we may have to clean the ends of several indirect
* blocks but leave the blocks themselves alive. Block is partially
* truncated if some data below the new i_size is referred from it (and
* it is on the path to the first completely truncated data block, indeed).
* We have to free the top of that path along with everything to the right
* of the path. Since no allocation past the truncation point is possible
* until ext2_truncate() finishes, we may safely do the latter, but top
* of branch may require special attention - pageout below the truncation
* point might try to populate it.
*
* We atomically detach the top of branch from the tree, store the block
* number of its root in *@top, pointers to buffer_heads of partially
* truncated blocks - in @chain[].bh and pointers to their last elements
* that should not be removed - in @chain[].p. Return value is the pointer
* to last filled element of @chain.
*
* The work left to caller to do the actual freeing of subtrees:
* a) free the subtree starting from *@top
* b) free the subtrees whose roots are stored in
* (@chain[i].p+1 .. end of @chain[i].bh->b_data)
* c) free the subtrees growing from the inode past the @chain[0].p
* (no partially truncated stuff there).
*/
static Indirect *ext2_find_shared(struct inode *inode,
int depth,
int offsets[4],
Indirect chain[4],
__le32 *top)
{
Indirect *partial, *p;
int k, err;
*top = 0;
for (k = depth; k > 1 && !offsets[k-1]; k--)
;
partial = ext2_get_branch(inode, k, offsets, chain, &err);
if (!partial)
partial = chain + k-1;
/*
* If the branch acquired continuation since we've looked at it -
* fine, it should all survive and (new) top doesn't belong to us.
*/
write_lock(&EXT2_I(inode)->i_meta_lock);
if (!partial->key && *partial->p) {
write_unlock(&EXT2_I(inode)->i_meta_lock);
goto no_top;
}
for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
;
/*
* OK, we've found the last block that must survive. The rest of our
* branch should be detached before unlocking. However, if that rest
* of branch is all ours and does not grow immediately from the inode
* it's easier to cheat and just decrement partial->p.
*/
if (p == chain + k - 1 && p > chain) {
p->p--;
} else {
*top = *p->p;
*p->p = 0;
}
write_unlock(&EXT2_I(inode)->i_meta_lock);
while(partial > p)
{
brelse(partial->bh);
partial--;
}
no_top:
return partial;
}
/**
* ext2_free_data - free a list of data blocks
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: points immediately past the end of array
*
* We are freeing all blocks referred from that array (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static inline void ext2_free_data(struct inode *inode, __le32 *p, __le32 *q)
{
ext2_fsblk_t block_to_free = 0, count = 0;
ext2_fsblk_t nr;
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (nr) {
*p = 0;
/* accumulate blocks to free if they're contiguous */
if (count == 0)
goto free_this;
else if (block_to_free == nr - count)
count++;
else {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
free_this:
block_to_free = nr;
count = 1;
}
}
}
if (count > 0) {
ext2_free_blocks (inode, block_to_free, count);
mark_inode_dirty(inode);
}
}
/**
* ext2_free_branches - free an array of branches
* @inode: inode we are dealing with
* @p: array of block numbers
* @q: pointer immediately past the end of array
* @depth: depth of the branches to free
*
* We are freeing all blocks referred from these branches (numbers are
* stored as little-endian 32-bit) and updating @inode->i_blocks
* appropriately.
*/
static void ext2_free_branches(struct inode *inode, __le32 *p, __le32 *q, int depth)
{
struct buffer_head * bh;
ext2_fsblk_t nr;
if (depth--) {
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
for ( ; p < q ; p++) {
nr = le32_to_cpu(*p);
if (!nr)
continue;
*p = 0;
bh = sb_bread(inode->i_sb, nr);
/*
* A read failure? Report error and clear slot
* (should be rare).
*/
if (!bh) {
ext2_error(inode->i_sb, "ext2_free_branches",
"Read failure, inode=%ld, block=%ld",
inode->i_ino, nr);
continue;
}
ext2_free_branches(inode,
(__le32*)bh->b_data,
(__le32*)bh->b_data + addr_per_block,
depth);
bforget(bh);
ext2_free_blocks(inode, nr, 1);
mark_inode_dirty(inode);
}
} else
ext2_free_data(inode, p, q);
}
/* mapping->invalidate_lock must be held when calling this function */
static void __ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
__le32 *i_data = EXT2_I(inode)->i_data;
struct ext2_inode_info *ei = EXT2_I(inode);
int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
int offsets[4];
Indirect chain[4];
Indirect *partial;
__le32 nr = 0;
int n;
long iblock;
unsigned blocksize;
blocksize = inode->i_sb->s_blocksize;
iblock = (offset + blocksize-1) >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
#ifdef CONFIG_FS_DAX
WARN_ON(!rwsem_is_locked(&inode->i_mapping->invalidate_lock));
#endif
n = ext2_block_to_path(inode, iblock, offsets, NULL);
if (n == 0)
return;
/*
* From here we block out all ext2_get_block() callers who want to
* modify the block allocation tree.
*/
mutex_lock(&ei->truncate_mutex);
if (n == 1) {
ext2_free_data(inode, i_data+offsets[0],
i_data + EXT2_NDIR_BLOCKS);
goto do_indirects;
}
partial = ext2_find_shared(inode, n, offsets, chain, &nr);
/* Kill the top of shared branch (already detached) */
if (nr) {
if (partial == chain)
mark_inode_dirty(inode);
else
mark_buffer_dirty_inode(partial->bh, inode);
ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
}
/* Clear the ends of indirect blocks on the shared branch */
while (partial > chain) {
ext2_free_branches(inode,
partial->p + 1,
(__le32*)partial->bh->b_data+addr_per_block,
(chain+n-1) - partial);
mark_buffer_dirty_inode(partial->bh, inode);
brelse (partial->bh);
partial--;
}
do_indirects:
/* Kill the remaining (whole) subtrees */
switch (offsets[0]) {
default:
nr = i_data[EXT2_IND_BLOCK];
if (nr) {
i_data[EXT2_IND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 1);
}
fallthrough;
case EXT2_IND_BLOCK:
nr = i_data[EXT2_DIND_BLOCK];
if (nr) {
i_data[EXT2_DIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 2);
}
fallthrough;
case EXT2_DIND_BLOCK:
nr = i_data[EXT2_TIND_BLOCK];
if (nr) {
i_data[EXT2_TIND_BLOCK] = 0;
mark_inode_dirty(inode);
ext2_free_branches(inode, &nr, &nr+1, 3);
}
break;
case EXT2_TIND_BLOCK:
;
}
ext2_discard_reservation(inode);
mutex_unlock(&ei->truncate_mutex);
}
static void ext2_truncate_blocks(struct inode *inode, loff_t offset)
{
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return;
if (ext2_inode_is_fast_symlink(inode))
return;
filemap_invalidate_lock(inode->i_mapping);
__ext2_truncate_blocks(inode, offset);
filemap_invalidate_unlock(inode->i_mapping);
}
static int ext2_setsize(struct inode *inode, loff_t newsize)
{
int error;
if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode)))
return -EINVAL;
if (ext2_inode_is_fast_symlink(inode))
return -EINVAL;
if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
return -EPERM;
inode_dio_wait(inode);
if (IS_DAX(inode))
error = dax_truncate_page(inode, newsize, NULL,
&ext2_iomap_ops);
else
error = block_truncate_page(inode->i_mapping,
newsize, ext2_get_block);
if (error)
return error;
filemap_invalidate_lock(inode->i_mapping);
truncate_setsize(inode, newsize);
__ext2_truncate_blocks(inode, newsize);
filemap_invalidate_unlock(inode->i_mapping);
inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
if (inode_needs_sync(inode)) {
sync_mapping_buffers(inode->i_mapping);
sync_inode_metadata(inode, 1);
} else {
mark_inode_dirty(inode);
}
return 0;
}
static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino,
struct buffer_head **p)
{
struct buffer_head * bh;
unsigned long block_group;
unsigned long block;
unsigned long offset;
struct ext2_group_desc * gdp;
*p = NULL;
if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) ||
ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
goto Einval;
block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
gdp = ext2_get_group_desc(sb, block_group, NULL);
if (!gdp)
goto Egdp;
/*
* Figure out the offset within the block group inode table
*/
offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb);
block = le32_to_cpu(gdp->bg_inode_table) +
(offset >> EXT2_BLOCK_SIZE_BITS(sb));
if (!(bh = sb_bread(sb, block)))
goto Eio;
*p = bh;
offset &= (EXT2_BLOCK_SIZE(sb) - 1);
return (struct ext2_inode *) (bh->b_data + offset);
Einval:
ext2_error(sb, "ext2_get_inode", "bad inode number: %lu",
(unsigned long) ino);
return ERR_PTR(-EINVAL);
Eio:
ext2_error(sb, "ext2_get_inode",
"unable to read inode block - inode=%lu, block=%lu",
(unsigned long) ino, block);
Egdp:
return ERR_PTR(-EIO);
}
void ext2_set_inode_flags(struct inode *inode)
{
unsigned int flags = EXT2_I(inode)->i_flags;
inode->i_flags &= ~(S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME |
S_DIRSYNC | S_DAX);
if (flags & EXT2_SYNC_FL)
inode->i_flags |= S_SYNC;
if (flags & EXT2_APPEND_FL)
inode->i_flags |= S_APPEND;
if (flags & EXT2_IMMUTABLE_FL)
inode->i_flags |= S_IMMUTABLE;
if (flags & EXT2_NOATIME_FL)
inode->i_flags |= S_NOATIME;
if (flags & EXT2_DIRSYNC_FL)
inode->i_flags |= S_DIRSYNC;
if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode))
inode->i_flags |= S_DAX;
}
void ext2_set_file_ops(struct inode *inode)
{
inode->i_op = &ext2_file_inode_operations;
inode->i_fop = &ext2_file_operations;
if (IS_DAX(inode))
inode->i_mapping->a_ops = &ext2_dax_aops;
else
inode->i_mapping->a_ops = &ext2_aops;
}
struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
{
struct ext2_inode_info *ei;
struct buffer_head * bh = NULL;
struct ext2_inode *raw_inode;
struct inode *inode;
long ret = -EIO;
int n;
uid_t i_uid;
gid_t i_gid;
inode = iget_locked(sb, ino);
if (!inode)
return ERR_PTR(-ENOMEM);
if (!(inode_state_read_once(inode) & I_NEW))
return inode;
ei = EXT2_I(inode);
ei->i_block_alloc_info = NULL;
raw_inode = ext2_get_inode(inode->i_sb, ino, &bh);
if (IS_ERR(raw_inode)) {
ret = PTR_ERR(raw_inode);
goto bad_inode;
}
inode->i_mode = le16_to_cpu(raw_inode->i_mode);
i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
if (!(test_opt (inode->i_sb, NO_UID32))) {
i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
}
i_uid_write(inode, i_uid);
i_gid_write(inode, i_gid);
set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
inode->i_size = le32_to_cpu(raw_inode->i_size);
inode_set_atime(inode, (signed)le32_to_cpu(raw_inode->i_atime), 0);
inode_set_ctime(inode, (signed)le32_to_cpu(raw_inode->i_ctime), 0);
inode_set_mtime(inode, (signed)le32_to_cpu(raw_inode->i_mtime), 0);
ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
/* We now have enough fields to check if the inode was active or not.
* This is needed because nfsd might try to access dead inodes
* the test is that same one that e2fsck uses
* NeilBrown 1999oct15
*/
if (inode->i_nlink == 0 && (inode->i_mode == 0 || ei->i_dtime)) {
/* this inode is deleted */
ret = -ESTALE;
goto bad_inode;
}
inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
ei->i_flags = le32_to_cpu(raw_inode->i_flags);
ext2_set_inode_flags(inode);
ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
ei->i_frag_no = raw_inode->i_frag;
ei->i_frag_size = raw_inode->i_fsize;
ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
ei->i_dir_acl = 0;
if (ei->i_file_acl &&
!ext2_data_block_valid(EXT2_SB(sb), ei->i_file_acl, 1)) {
ext2_error(sb, "ext2_iget", "bad extended attribute block %u",
ei->i_file_acl);
ret = -EFSCORRUPTED;
goto bad_inode;
}
if (S_ISREG(inode->i_mode))
inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
else
ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
if (i_size_read(inode) < 0) {
ret = -EFSCORRUPTED;
goto bad_inode;
}
ei->i_dtime = 0;
inode->i_generation = le32_to_cpu(raw_inode->i_generation);
ei->i_state = 0;
ei->i_block_group = (ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
ei->i_dir_start_lookup = 0;
/*
* NOTE! The in-memory inode i_data array is in little-endian order
* even on big-endian machines: we do NOT byteswap the block numbers!
*/
for (n = 0; n < EXT2_N_BLOCKS; n++)
ei->i_data[n] = raw_inode->i_block[n];
if (S_ISREG(inode->i_mode)) {
ext2_set_file_ops(inode);
} else if (S_ISDIR(inode->i_mode)) {
inode->i_op = &ext2_dir_inode_operations;
inode->i_fop = &ext2_dir_operations;
inode->i_mapping->a_ops = &ext2_aops;
} else if (S_ISLNK(inode->i_mode)) {
if (ext2_inode_is_fast_symlink(inode)) {
inode->i_link = (char *)ei->i_data;
inode->i_op = &ext2_fast_symlink_inode_operations;
nd_terminate_link(ei->i_data, inode->i_size,
sizeof(ei->i_data) - 1);
} else {
inode->i_op = &ext2_symlink_inode_operations;
inode_nohighmem(inode);
inode->i_mapping->a_ops = &ext2_aops;
}
} else {
inode->i_op = &ext2_special_inode_operations;
if (raw_inode->i_block[0])
init_special_inode(inode, inode->i_mode,
old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
else
init_special_inode(inode, inode->i_mode,
new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
}
brelse (bh);
unlock_new_inode(inode);
return inode;
bad_inode:
brelse(bh);
iget_failed(inode);
return ERR_PTR(ret);
}
static int __ext2_write_inode(struct inode *inode, int do_sync)
{
struct ext2_inode_info *ei = EXT2_I(inode);
struct super_block *sb = inode->i_sb;
ino_t ino = inode->i_ino;
uid_t uid = i_uid_read(inode);
gid_t gid = i_gid_read(inode);
struct buffer_head * bh;
struct ext2_inode * raw_inode = ext2_get_inode(sb, ino, &bh);
int n;
int err = 0;
if (IS_ERR(raw_inode))
return -EIO;
/* For fields not tracking in the in-memory inode,
* initialise them to zero for new inodes. */
if (ei->i_state & EXT2_STATE_NEW)
memset(raw_inode, 0, EXT2_SB(sb)->s_inode_size);
raw_inode->i_mode = cpu_to_le16(inode->i_mode);
if (!(test_opt(sb, NO_UID32))) {
raw_inode->i_uid_low = cpu_to_le16(low_16_bits(uid));
raw_inode->i_gid_low = cpu_to_le16(low_16_bits(gid));
/*
* Fix up interoperability with old kernels. Otherwise, old inodes get
* re-used with the upper 16 bits of the uid/gid intact
*/
if (!ei->i_dtime) {
raw_inode->i_uid_high = cpu_to_le16(high_16_bits(uid));
raw_inode->i_gid_high = cpu_to_le16(high_16_bits(gid));
} else {
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
} else {
raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(uid));
raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(gid));
raw_inode->i_uid_high = 0;
raw_inode->i_gid_high = 0;
}
raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
raw_inode->i_size = cpu_to_le32(inode->i_size);
raw_inode->i_atime = cpu_to_le32(inode_get_atime_sec(inode));
raw_inode->i_ctime = cpu_to_le32(inode_get_ctime_sec(inode));
raw_inode->i_mtime = cpu_to_le32(inode_get_mtime_sec(inode));
raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
raw_inode->i_flags = cpu_to_le32(ei->i_flags);
raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
raw_inode->i_frag = ei->i_frag_no;
raw_inode->i_fsize = ei->i_frag_size;
raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
if (!S_ISREG(inode->i_mode))
raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
else {
raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
if (inode->i_size > 0x7fffffffULL) {
if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
EXT2_SB(sb)->s_es->s_rev_level ==
cpu_to_le32(EXT2_GOOD_OLD_REV)) {
/* If this is the first large file
* created, add a flag to the superblock.
*/
spin_lock(&EXT2_SB(sb)->s_lock);
ext2_update_dynamic_rev(sb);
EXT2_SET_RO_COMPAT_FEATURE(sb,
EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
spin_unlock(&EXT2_SB(sb)->s_lock);
ext2_sync_super(sb, EXT2_SB(sb)->s_es, 1);
}
}
}
raw_inode->i_generation = cpu_to_le32(inode->i_generation);
if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
if (old_valid_dev(inode->i_rdev)) {
raw_inode->i_block[0] =
cpu_to_le32(old_encode_dev(inode->i_rdev));
raw_inode->i_block[1] = 0;
} else {
raw_inode->i_block[0] = 0;
raw_inode->i_block[1] =
cpu_to_le32(new_encode_dev(inode->i_rdev));
raw_inode->i_block[2] = 0;
}
} else for (n = 0; n < EXT2_N_BLOCKS; n++)
raw_inode->i_block[n] = ei->i_data[n];
mark_buffer_dirty(bh);
if (do_sync) {
sync_dirty_buffer(bh);
if (buffer_req(bh) && !buffer_uptodate(bh)) {
printk ("IO error syncing ext2 inode [%s:%08lx]\n",
sb->s_id, (unsigned long) ino);
err = -EIO;
}
}
ei->i_state &= ~EXT2_STATE_NEW;
brelse (bh);
return err;
}
int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
{
return __ext2_write_inode(inode, wbc->sync_mode == WB_SYNC_ALL);
}
int ext2_getattr(struct mnt_idmap *idmap, const struct path *path,
struct kstat *stat, u32 request_mask, unsigned int query_flags)
{
struct inode *inode = d_inode(path->dentry);
struct ext2_inode_info *ei = EXT2_I(inode);
unsigned int flags;
flags = ei->i_flags & EXT2_FL_USER_VISIBLE;
if (flags & EXT2_APPEND_FL)
stat->attributes |= STATX_ATTR_APPEND;
if (flags & EXT2_COMPR_FL)
stat->attributes |= STATX_ATTR_COMPRESSED;
if (flags & EXT2_IMMUTABLE_FL)
stat->attributes |= STATX_ATTR_IMMUTABLE;
if (flags & EXT2_NODUMP_FL)
stat->attributes |= STATX_ATTR_NODUMP;
stat->attributes_mask |= (STATX_ATTR_APPEND |
STATX_ATTR_COMPRESSED |
STATX_ATTR_ENCRYPTED |
STATX_ATTR_IMMUTABLE |
STATX_ATTR_NODUMP);
generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
return 0;
}
int ext2_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
struct iattr *iattr)
{
struct inode *inode = d_inode(dentry);
int error;
error = setattr_prepare(&nop_mnt_idmap, dentry, iattr);
if (error)
return error;
if (is_quota_modification(&nop_mnt_idmap, inode, iattr)) {
error = dquot_initialize(inode);
if (error)
return error;
}
if (i_uid_needs_update(&nop_mnt_idmap, iattr, inode) ||
i_gid_needs_update(&nop_mnt_idmap, iattr, inode)) {
error = dquot_transfer(&nop_mnt_idmap, inode, iattr);
if (error)
return error;
}
if (iattr->ia_valid & ATTR_SIZE && iattr->ia_size != inode->i_size) {
error = ext2_setsize(inode, iattr->ia_size);
if (error)
return error;
}
setattr_copy(&nop_mnt_idmap, inode, iattr);
if (iattr->ia_valid & ATTR_MODE)
error = posix_acl_chmod(&nop_mnt_idmap, dentry, inode->i_mode);
mark_inode_dirty(inode);
return error;
}
]
|
| 39/2 |
2026/02/24 21:30 |
llm |
expert |
0m
Model:
Tokens:
input: 57060
output: 19
thoughts: 940
Thoughts: **Benign Data Race in Legacy Filesystem Metadata Updates**
Okay, so I've been digging into this KCSAN report and I'm pretty sure I've got a handle on the situation. Looking at `__ext2_write_inode`, it's clear that this old-school filesystem doesn't bother with `lock_buffer` before updating the `raw_inode` fields directly. It calls `ext2_get_inode` which uses `sb_bread`, modifies the data, marks the buffer dirty, and optionally syncs it. This pattern, of course, gives us the race.
This is exactly what I expected from these legacy filesystems. It's the standard way of updating metadata. But is it actually a problem? I'd have to say not. The updates are to small fields, and on most modern architectures, these are going to be atomic writes anyway. If we get a torn read during writeback, the buffer gets re-dirtied and rewritten immediately. These filesystems don't care about the concept of stable writes for metadata, so they're totally fine with it.
It's similar in the loop driver case. It's just a different view on the same writeback process. The loop driver is reading a page to write it to the backing file, but it's guaranteed that the `FAT`/`ext2` will eventually make the update.
I'm confident that this is a benign scenario.
Just to be absolutely sure, I had a quick look to make sure that `raw_entry` isn't going to be NULL. It isn't, `bh->b_data` is valid as long as we have the buffer, which we do, because `sb_bread` gives us a referenced `bh` and `brelse` is called at the end. So the race is purely on the data in the buffer.
Okay, let's run through the "harmful" criteria again: memory corruption? No. Crash? No. Logic error? No, it's eventually consistent. Compiler optimizations causing a problem? No, we're just talking about simple assignments to disk-format structures.
The only "harm" is a temporary inconsistent state on the block device. And, as we've already established, that's just how these filesystems operate.
Oh, and there was one detail about the `__fat_write_inode` function I needed to note. It *does* use `sbi->inode_hash_lock`. This protects against other threads calling `__fat_write_inode` for the *same* filesystem, but it doesn't protect against the block layer reading the buffer. That's fine, it's just expected.
So, I'm marking this as benign. I'm all set.
|
| 40/2 |
2026/02/24 21:31 |
tool |
set-results |
0m
Args: map[Benign:true Confident:true]
Results: map[Benign:true Confident:true]
|
| 41/2 |
2026/02/24 21:31 |
llm |
expert |
0m
Model:
Tokens:
input: 58630
output: 773
thoughts: 107
Thoughts: **Benign Data Race Analysis Complete**
Alright, I've finished digging into this data race, and I've come to the conclusion that it's actually benign. It looks like it's happening between a File Allocation Table (FAT) metadata update and the loop driver's writeback of the very same block. This is classic, really. FAT, and other older filesystems like ext2, were never built to hold the locks on metadata buffers during modification, even when writeback is happening. They're banking on that whole re-dirtying mechanism to keep the data consistent on the drive at the end of the day.
The really good news? I've confirmed that this race isn't leading to any memory corruption, and we're not seeing crashes, which is what I'm looking for. The inconsistent disk state is temporary, and, honestly, expected behavior when dealing with a filesystem like this.
|