Blob Blame History Raw
From 51cc3a6620a6ca934d468bda345678768493f5d8 Mon Sep 17 00:00:00 2001
From: Hugh Dickins <hughd@google.com>
Date: Thu, 2 Sep 2021 14:53:57 -0700
Subject: [PATCH] fs, mm: fix race in unlinking swapfile
Git-commit: 51cc3a6620a6ca934d468bda345678768493f5d8
Patch-mainline: v5.15-rc1
References: bsc#1191455

We had a recurring situation in which admin procedures setting up
swapfiles would race with test preparation clearing away swapfiles; and
just occasionally that got stuck on a swapfile "(deleted)" which could
never be swapped off.  That is not supposed to be possible.

2.6.28 commit f9454548e17c ("don't unlink an active swapfile") admitted
that it was leaving a race window open: now close it.

may_delete() makes the IS_SWAPFILE check (amongst many others) before
inode_lock has been taken on target: now repeat just that simple check in
vfs_unlink() and vfs_rename(), after taking inode_lock.

Which goes most of the way to fixing the race, but swapon() must also
check after it acquires inode_lock, that the file just opened has not
already been unlinked.

Link: https://lkml.kernel.org/r/e17b91ad-a578-9a15-5e3-4989e0f999b5@google.com
Fixes: f9454548e17c ("don't unlink an active swapfile")
Signed-off-by: Hugh Dickins <hughd@google.com>
Reviewed-by: Jan Kara <jack@suse.cz>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>
Acked-by: Jan Kara <jack@suse.cz>

---
 fs/namei.c    |    8 +++++++-
 mm/swapfile.c |    3 +++
 2 files changed, 10 insertions(+), 1 deletion(-)

--- a/fs/namei.c
+++ b/fs/namei.c
@@ -4026,7 +4026,9 @@ int vfs_unlink(struct inode *dir, struct
 		return -EPERM;
 
 	inode_lock(target);
-	if (is_local_mountpoint(dentry))
+	if (IS_SWAPFILE(target))
+		error = -EPERM;
+	else if (is_local_mountpoint(dentry))
 		error = -EBUSY;
 	else {
 		error = security_inode_unlink(dir, dentry);
@@ -4478,6 +4480,10 @@ int vfs_rename(struct inode *old_dir, st
 	else if (target)
 		inode_lock(target);
 
+	error = -EPERM;
+	if (IS_SWAPFILE(source) || (target && IS_SWAPFILE(target)))
+		goto out;
+
 	error = -EBUSY;
 	if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry))
 		goto out;
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2498,6 +2498,7 @@ static struct swap_info_struct *alloc_sw
 static int claim_swapfile(struct swap_info_struct *p, struct inode *inode)
 {
 	int error;
+	struct dentry *dentry = p->swap_file->f_path.dentry;
 
 	if (S_ISBLK(inode->i_mode)) {
 		p->bdev = bdgrab(I_BDEV(inode));
@@ -2515,6 +2516,8 @@ static int claim_swapfile(struct swap_in
 	} else if (S_ISREG(inode->i_mode)) {
 		p->bdev = inode->i_sb->s_bdev;
 		inode_lock(inode);
+		if (d_unlinked(dentry) || cant_mount(dentry))
+			return -ENOENT;
 		if (IS_SWAPFILE(inode))
 			return -EBUSY;
 	} else