From 302002e211eeafed6befcc8cb9020bfbd2858571 Mon Sep 17 00:00:00 2001 From: Vojtech Trefny Date: Tue, 24 Feb 2026 12:59:12 +0100 Subject: [PATCH] loop: Remove the loop device when setting sector size fails Fixes: #1170 --- src/plugins/loop.c | 6 ++++++ tests/loop_test.py | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/src/plugins/loop.c b/src/plugins/loop.c index cef228ab8..037dde841 100644 --- a/src/plugins/loop.c +++ b/src/plugins/loop.c @@ -372,6 +372,9 @@ gboolean bd_loop_setup_from_fd (gint fd, guint64 offset, guint64 size, gboolean if (status != 0) { g_set_error (&l_error, BD_LOOP_ERROR, BD_LOOP_ERROR_FAIL, "Failed to set status for the %s device: %m", loop_device); + if (ioctl (loop_fd, LOOP_CLR_FD) < 0) + bd_utils_log_format (BD_UTILS_LOG_WARNING, + "Failed to clear the %s device: %m", loop_device); g_free (loop_device); close (loop_fd); bd_utils_report_finished (progress_id, l_error->message); @@ -391,6 +394,9 @@ gboolean bd_loop_setup_from_fd (gint fd, guint64 offset, guint64 size, gboolean if (status != 0) { g_set_error (&l_error, BD_LOOP_ERROR, BD_LOOP_ERROR_FAIL, "Failed to set sector size for the %s device: %m", loop_device); + if (ioctl (loop_fd, LOOP_CLR_FD) < 0) + bd_utils_log_format (BD_UTILS_LOG_WARNING, + "Failed to clear the %s device: %m", loop_device); g_free (loop_device); close (loop_fd); bd_utils_report_finished (progress_id, l_error->message); diff --git a/tests/loop_test.py b/tests/loop_test.py index e59dba076..cb7df269d 100644 --- a/tests/loop_test.py +++ b/tests/loop_test.py @@ -1,4 +1,5 @@ import os +import time import unittest import overrides_hack @@ -142,6 +143,17 @@ def test_loop_setup_sector_size(self): with open("/sys/block/%s/queue/logical_block_size" % self.loop, "r") as f: self.assertEqual(f.read().strip(), "4096") + succ = BlockDev.loop_teardown(self.loop) + self.assertTrue(succ) + + # invalid sector size -- setup should fail, make sure we also removed the loop device after + with self.assertRaisesRegex(GLib.GError, "Failed to set sector size"): + BlockDev.loop_setup(self.dev_file, sector_size=7) + + time.sleep(2) + loop_name = BlockDev.loop_get_loop_name(self.dev_file) + self.assertIsNone(loop_name) + class LoopTestSetupPartprobe(LoopTestCase): def test_loop_setup_partprobe(self):