From af9fc22d03bde1a223c4a5e469c5c33c15837e67 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Thomas=20Wei=C3=9Fschuh?= Date: Sun, 25 Jun 2023 09:59:05 +0200 Subject: [PATCH] losetup: deduplicate find_unused() logic MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Thomas Weißschuh --- sys-utils/losetup.c | 37 ++++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/sys-utils/losetup.c b/sys-utils/losetup.c index 7b19436b48..9e8bd509ac 100644 --- a/sys-utils/losetup.c +++ b/sys-utils/losetup.c @@ -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: -- 2.47.2