From acd229fc2afe0c402cca3b21e0490be71dec2725 Mon Sep 17 00:00:00 2001
From: Karel Zak <kzak@redhat.com>
Date: Tue, 3 Mar 2020 10:55:28 +0100
Subject: [PATCH] libmount: move "already mounted" code to separate function

Signed-off-by: Karel Zak <kzak@redhat.com>
---
 libmount/src/context_mount.c | 54 +++++++++++++++++++++++++++++---------------
 1 file changed, 36 insertions(+), 18 deletions(-)

diff --git a/libmount/src/context_mount.c b/libmount/src/context_mount.c
index 088d132..0c4b765 100644
--- a/libmount/src/context_mount.c
+++ b/libmount/src/context_mount.c
@@ -1119,6 +1119,36 @@ int mnt_context_do_mount(struct libmnt_context *cxt)
 	return res;
 }
 
+/*
+ * Returns mountinfo FS entry of context source patch if the source is already
+ * mounted. This function is used for "already mounted" message or to get FS of
+ * re-used loop device.
+ */
+static struct libmnt_fs *get_already_mounted_source(struct libmnt_context *cxt)
+{
+	const char *src;
+	struct libmnt_table *tb;
+
+	assert(cxt);
+
+	src = mnt_fs_get_srcpath(cxt->fs);
+
+	if (src && mnt_context_get_mtab(cxt, &tb) == 0) {
+		struct libmnt_iter itr;
+		struct libmnt_fs *fs;
+
+		mnt_reset_iter(&itr, MNT_ITER_FORWARD);
+		while (mnt_table_next_fs(tb, &itr, &fs) == 0) {
+			const char *s = mnt_fs_get_srcpath(fs),
+				   *t = mnt_fs_get_target(fs);
+
+			if (t && s && mnt_fs_streq_srcpath(fs, src))
+				return fs;
+		}
+	}
+	return NULL;
+}
+
 /**
  * mnt_context_finalize_mount:
  * @cxt: context
@@ -1721,34 +1751,22 @@ int mnt_context_get_mount_excode(
 		break;
 
 	case EBUSY:
-	{
-		struct libmnt_table *tb;
-
 		if (!buf)
 			break;
 		if (mflags & MS_REMOUNT) {
 			snprintf(buf, bufsz, _("mount point is busy"));
 			break;
 		}
-		if (src && mnt_context_get_mtab(cxt, &tb) == 0) {
-			struct libmnt_iter itr;
-			struct libmnt_fs *fs;
-
-			mnt_reset_iter(&itr, MNT_ITER_FORWARD);
-			while (mnt_table_next_fs(tb, &itr, &fs) == 0) {
-				const char *s = mnt_fs_get_srcpath(fs),
-					   *t = mnt_fs_get_target(fs);
-
-				if (t && s && mnt_fs_streq_srcpath(fs, src)) {
-					snprintf(buf, bufsz, _("%s already mounted on %s"), s, t);
-					break;
-				}
-			}
+		if (src) {
+			struct libmnt_fs *fs = get_already_mounted_source(cxt);
+
+			if (fs && mnt_fs_get_target(fs))
+				snprintf(buf, bufsz, _("%s already mounted on %s"),
+						src, mnt_fs_get_target(fs));
 		}
 		if (!*buf)
 			snprintf(buf, bufsz, _("%s already mounted or mount point busy"), src);
 		break;
-	}
 	case ENOENT:
 		if (tgt && lstat(tgt, &st)) {
 			if (buf)
-- 
1.8.3.1

