]> 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)
committerThomas Weißschuh <thomas@t-8ch.de>
Sun, 25 Jun 2023 08:06:21 +0000 (10:06 +0200)
Signed-off-by: Thomas Weißschuh <thomas@t-8ch.de>
sys-utils/losetup.c

index 7b19436b487bed6e0db5defa483b49edc9c614c4..9e8bd509ac5c190fd00c75564da1df59ec3c1d87 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: