[PATCH] sys_swapon: fix inode locking

From: Cesar Eduardo Barros
Date: Tue Mar 22 2011 - 22:03:34 EST

A conflict between 52c50567d8ab0a0a87f12cceaa4194967854f0bd (mm: swap:
unlock swapfile inode mutex before closing file on bad swapfiles) and
83ef99befc324803a54cf2a5fab5a322df3a99d6 (sys_swapon: remove did_down
variable) caused a double unlock of the inode mutex (once in bad_swap:
before the filp_close, once at the end just before returning).

The patch which added the extra unlock cleared did_down to avoid
unlocking twice, but the other patch removed the did_down variable.

To fix, set inode to NULL after the first unlock, since it will be used
after that point only for the final unlock.

While checking this patch, I found a path which could unlock without
locking, in case the same inode was added as a swapfile twice. To fix,
move the setting of the inode variable further down, to just before
claim_swapfile, which will lock the inode before doing anything else.

Cc: Mel Gorman <mgorman@xxxxxxx>
Cc: Hugh Dickins <hughd@xxxxxxxxxx>
Cc: Eric B Munson <emunson@xxxxxxxxx>
Cc: KAMEZAWA Hiroyuki <kamezawa.hiroyu@xxxxxxxxxxxxxx>
Cc: Andrew Morton <akpm@xxxxxxxxxxxxxxxxxxxx>
Cc: Linus Torvalds <torvalds@xxxxxxxxxxxxxxxxxxxx>
Signed-off-by: Cesar Eduardo Barros <cesarb@xxxxxxxxxx>
mm/swapfile.c | 7 +++++--
1 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/mm/swapfile.c b/mm/swapfile.c
index aafcf36..71b42ec 100644
--- a/mm/swapfile.c
+++ b/mm/swapfile.c
@@ -2088,7 +2088,6 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)

p->swap_file = swap_file;
mapping = swap_file->f_mapping;
- inode = mapping->host;

for (i = 0; i < nr_swapfiles; i++) {
struct swap_info_struct *q = swap_info[i];
@@ -2101,6 +2100,8 @@ SYSCALL_DEFINE2(swapon, const char __user *, specialfile, int, swap_flags)

+ inode = mapping->host;
+ /* If S_ISREG(inode->i_mode) will do mutex_lock(&inode->i_mutex); */
error = claim_swapfile(p, inode);
if (unlikely(error))
goto bad_swap;
@@ -2187,8 +2188,10 @@ bad_swap:
if (swap_file) {
- if (inode && S_ISREG(inode->i_mode))
+ if (inode && S_ISREG(inode->i_mode)) {
+ inode = NULL;
+ }
filp_close(swap_file, NULL);

To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/