[PATCH 02/10] libext2fs: fix checking for valid fds in mmp.c

Darrick J. Wong
2026-04-22T23:24:04Z

File descriptors are non-negative numbers, which means that 0 is a valid
fd. Fix the code to be consistent with Unix behaviors.

Cc: <linux-ext4@vger.kernel.org> # v1.42
Fixes: 0f5eba7501f467 ("ext2fs: add multi-mount protection (INCOMPAT_MMP)")
Fixes: 76a6c8788c79e4 ("mmp: do not use O_DIRECT when working with regular file")
Signed-off-by: "Darrick J. Wong" <djwong@kernel.org>
---
lib/ext2fs/mmp.c | 6 +++---
lib/ext2fs/openfs.c | 1 +
2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/lib/ext2fs/mmp.c b/lib/ext2fs/mmp.c
index e2823732e2b6a2..cb15a18fce5547 100644
--- a/lib/ext2fs/mmp.c
+++ b/lib/ext2fs/mmp.c
@@ -59,11 +59,11 @@ errcode_t ext2fs_mmp_read(ext2_filsys fs, blk64_t mmp_blk, void *buf)
return EXT2_ET_MMP_BAD_BLOCK;

/* ext2fs_open() reserves fd0,1,2 to avoid stdio collision, so checking
- * mmp_fd <= 0 is OK to validate that the fd is valid. This opens its
+ * mmp_fd < 0 is OK to validate that the fd is valid. This opens its
* own fd to read the MMP block to ensure that it is using O_DIRECT,
* regardless of how the io_manager is doing reads, to avoid caching of
* the MMP block by the io_manager or the VM. It needs to be fresh. */
- if (fs->mmp_fd <= 0) {
+ if (fs->mmp_fd < 0) {
struct stat st;
int flags = O_RDONLY | O_DIRECT;

@@ -427,7 +427,7 @@ errcode_t ext2fs_mmp_stop(ext2_filsys fs)
retval = ext2fs_mmp_write(fs, fs->super->s_mmp_block, fs->mmp_cmp);

mmp_error:
- if (fs->mmp_fd > 0) {
+ if (fs->mmp_fd >= 0) {
close(fs->mmp_fd);
fs->mmp_fd = -1;
}
diff --git a/lib/ext2fs/openfs.c b/lib/ext2fs/openfs.c
index 2b8e0e753c46e8..41359d15740881 100644
--- a/lib/ext2fs/openfs.c
+++ b/lib/ext2fs/openfs.c
@@ -148,6 +148,7 @@ errcode_t ext2fs_open2(const char *name, const char *io_options,
/* don't overwrite sb backups unless flag is explicitly cleared */
fs->flags |= EXT2_FLAG_MASTER_SB_ONLY;
fs->umask = 022;
+ fs->mmp_fd = -1;

time_env = ext2fs_safe_getenv("SOURCE_DATE_EPOCH");
if (time_env) {