]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
losetup: deduplicate find_unused() logic
authorThomas Weißschuh <thomas@t-8ch.de>
Sun, 25 Jun 2023 07:59:05 +0000 (09:59 +0200)
committerKarel Zak <kzak@redhat.com>
Mon, 26 Jun 2023 10:02:15 +0000 (12:02 +0200)
Signed-off-by: Thomas Weißschuh <thomas@t-8ch.de>
sys-utils/losetup.c

index 82ecee75fab544cf29967385365598df514f0a2a..75071360d6e170c935cf5891551d737610088cd1 100644 (file)
@@ -470,6 +470,25 @@ static void warn_size(const char *filename, uint64_t size, uint64_t offset, int
                        filename);
 }
 
+static int find_unused(struct loopdev_cxt *lc)
+{
+       int rc;
+
+       rc = loopcxt_find_unused(lc);
+       if (!rc)
+               return 0;
+
+       if (access(_PATH_DEV_LOOPCTL, F_OK) == 0 &&
+                       access(_PATH_DEV_LOOPCTL, W_OK) != 0)
+               ;
+       else
+               errno = -rc;
+
+       warn(_("cannot find an unused loop device"));
+
+       return rc;
+}
+
 static int create_loop(struct loopdev_cxt *lc,
                       int nooverlap, int lo_flags, int flags,
                       const char *file, uint64_t offset, uint64_t sizelimit,
@@ -551,10 +570,8 @@ static int create_loop(struct loopdev_cxt *lc,
                /* Note that loopcxt_{find_unused,set_device}() resets
                 * loopcxt struct.
                 */
-               if (!hasdev && (rc = loopcxt_find_unused(lc))) {
-                       warnx(_("cannot find an unused loop device"));
+               if (!hasdev && (rc = find_unused(lc)))
                        break;
-               }
                if (flags & LOOPDEV_FL_OFFSET)
                        loopcxt_set_offset(lc, offset);
                if (flags & LOOPDEV_FL_SIZELIMIT)
@@ -868,18 +885,8 @@ int main(int argc, char **argv)
                res = delete_all_loops(&lc);
                break;
        case A_FIND_FREE:
-               res = loopcxt_find_unused(&lc);
-               if (res) {
-                       int errsv = errno;
-
-                       if (access(_PATH_DEV_LOOPCTL, F_OK) == 0 &&
-                           access(_PATH_DEV_LOOPCTL, W_OK) != 0)
-                               ;
-                       else
-                               errno = errsv;
-
-                       warn(_("cannot find an unused loop device"));
-               } else
+               res = find_unused(&lc);
+               if (!res)
                        printf("%s\n", loopcxt_get_device(&lc));
                break;
        case A_SHOW: