diff --git a/fs/kernfs/dir.c b/fs/kernfs/dir.c
index a387534c9577855b6ea6d8e2868e4f85c52551b4..1e98efc2bf6d83946b934e2e1b6021c9f09c4fc1 100644
--- a/fs/kernfs/dir.c
+++ b/fs/kernfs/dir.c
@@ -1684,11 +1684,14 @@ static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx)
 		kernfs_get(pos);
 
 		mutex_unlock(&kernfs_mutex);
-		if (!dir_emit(ctx, name, len, ino, type))
-			return 0;
+		if (unlikely(!dir_emit(ctx, name, len, ino, type))) {
+			kernfs_put(pos);
+			goto out;
+		}
 		mutex_lock(&kernfs_mutex);
 	}
 	mutex_unlock(&kernfs_mutex);
+out:
 	file->private_data = NULL;
 	ctx->pos = INT_MAX;
 	return 0;