Skip to contentSkip to conversation

Block layer patches

GIT PULL Kevin Wolf 2 participants 19 messages Jul 28

Subsystems (2)
lore
Share & tools
lore

Kevin Wolf

author
#0 lore raw

The following changes since commit 299e7557ed15a9a325620698add379a3ce2d1d95:

Merge tag 'for_upstream' of https://git.kernel.org/pub/scm/virt/kvm/mst/qemu into staging (2026-07-27 16:51:28 -0400)

are available in the Git repository at:

https://repo.or.cz/qemu/kevin.git tags/for-upstream

for you to fetch changes up to 2896bf07932af5f114ad9c507cb5a45b2983d446:

iotests: increase timeouts for tests to 5 minutes (2026-07-28 17:55:55 +0200)

----------------------------------------------------------------
Block layer patches

- Fix missing locking in latency histogram setters
- coroutine: fix lost wakeup in qemu_co_sleep_wake()
- floppy: Fix READ/WRITE/FORMAT/READ ID behaviour with missing medium
- qcow2: Fix crash on closing a read-only image with dirty bit set
- cloop: fix integer overflow in total_sectors calculation
- dmg: Fix out of bounds accesses (CVE-2026-65929, CVE-2026-65928)
- FUSE export: fix regression with O_TRUNC when export is not growable
- iotests: Various small fixes

----------------------------------------------------------------
Christian Quante (2):
hw/block/fdc: select the drive named by the READ ID command hw/block/fdc: report a missing address mark on an empty drive

Daniel P. Berrangé (1):
iotests: increase timeouts for tests to 5 minutes

Denis V. Lunev (8):
block/accounting: take stats->lock in latency histogram setters block/qapi: take stats->lock when reading BlockAcctStats for query-blockstats tests/unit: add reproducer for BlockAcctStats histogram locking race
qcow2: do not try to clear the dirty bit on a read-only node
iotests: run the test pool with the 'fork' start method
iotests: skip FUSE tests when FUSE is not usable iotests/migrate-bitmaps-postcopy-test: replace the timing assertion with a content check
coroutine: fix lost wakeup in qemu_co_sleep_wake()

Fiona Ebner (2):
block/export/fuse: fix regression with O_TRUNC when export is not growable
iotests: test O_TRUNC behavior for fuse exports

Stefan Hajnoczi (3):
dmg: fix out-of-bounds load in search_chunk() (CVE-2026-65929)
dmg: refuse to open files with no chunks
dmg: reject inconsistent UDRW chunk sector count and length (CVE-2026-65928)

malike (1):
block/cloop: fix integer overflow in total_sectors calculation

 include/block/accounting.h                         |   1 +
 include/qemu/coroutine.h                           |  17 +-
 block/accounting.c                                 |  11 +-
 block/cloop.c                                      |   3 +-
 block/dmg.c                                        |  36 ++++-
 block/export/fuse.c                                |  12 ++
 block/qapi.c                                       |   3 +
 block/qcow2.c                                      |   6 +-
 hw/block/fdc.c                                     |  55 ++++++-
 tests/qtest/fdc-test.c                             |  70 ++++++++-
 tests/unit/test-block-accounting.c                 | 115 ++++++++++++++
 tests/unit/test-coroutine.c                        |  53 +++++++
 util/qemu-coroutine-sleep.c                        |  53 +++++--
 tests/qemu-iotests/testrunner.py                   |   4 +-
 tests/qemu-iotests/039                             |  11 ++
 tests/qemu-iotests/039.out                         |   3 +
 tests/qemu-iotests/common.rc                       |  14 ++
 tests/qemu-iotests/meson.build                     |  15 +-
 tests/qemu-iotests/tests/file-io-error             |   4 +-
 tests/qemu-iotests/tests/fuse-allow-other          |   2 +
 tests/qemu-iotests/tests/fuse-mmap-shared          |   9 +-
 tests/qemu-iotests/tests/fuse-truncate             | 171 +++++++++++++++++++++
 tests/qemu-iotests/tests/fuse-truncate.out         |   5 +
 .../tests/migrate-bitmaps-postcopy-test            |  15 +-
 tests/unit/meson.build                             |   1 +
 25 files changed, 633 insertions(+), 56 deletions(-)
 create mode 100644 tests/unit/test-block-accounting.c
 create mode 100755 tests/qemu-iotests/tests/fuse-truncate
 create mode 100644 tests/qemu-iotests/tests/fuse-truncate.out
author
#1 lore raw

[PULL 01/17] block/cloop: fix integer overflow in total_sectors calculation

From: malike <[email protected]>

The total_sectors is computed as n_blocks * sectors_per_block where both operands are uint32_t. The multiplication is performed in 32-bit arithmetic and can overflow when the product exceeds UINT32_MAX, producing a value much smaller than the true image size. The result is assigned to int64_t total_sectors but the 32-bit multiplication has already wrapped around, and the zero-extension to 64-bit does not recover the correct value.

This causes the block layer to reject valid I/O requests (DoS) when the reported total_sectors is smaller than the actual image.

Use 64-bit arithmetic by casting one operand to uint64_t so the multiplication is performed in 64-bit precision.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3972

Message-ID: <[email protected]>

---
 block/cloop.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
block/cloop.c +2 -1
index 443af1444e8..a16f08e6ef6 100644
@@ -202,7 +202,8 @@ static int cloop_open(BlockDriverState *bs, QDict *options, int flags,
     s->current_block = s->n_blocks;
 
     s->sectors_per_block = s->block_size/512;
-    bs->total_sectors = s->n_blocks * s->sectors_per_block;
+    /* Cast to uint64_t to prevent uint32_t overflow */
+    bs->total_sectors = (uint64_t)s->n_blocks * s->sectors_per_block;
     qemu_co_mutex_init(&s->lock);
     return 0;
 
Signature · 1 line
2.55.0
author
#2 lore raw

[PULL 02/17] block/accounting: take stats->lock in latency histogram setters

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

block_latency_histogram_set() and block_latency_histograms_clear() replace BlockLatencyHistogram's nbins/boundaries/bins without taking stats->lock, while block_account_one_io() reads those same fields under that lock from whatever iothread completes the I/O. The result is usual use-after-free and qemu crash.

Take stats->lock in both setters, matching the lock already held by the reader.

CC Kevin Wolf <[email protected]>
CC Hanna Reitz <[email protected]>
CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC Andrey Drobyshev <[email protected]>

Message-ID: <[email protected]>

---
 block/accounting.c | 8 ++++++++
 1 file changed, 8 insertions(+)
block/accounting.c +8 -0
index f00fe997403..6e06c7609eb 100644
@@ -194,6 +194,8 @@ int block_latency_histogram_set(BlockAcctStats *stats, enum BlockAcctType type,
         return -EINVAL;
     }
 
+    qemu_mutex_lock(&stats->lock);
+
     hist->nbins = new_nbins;
     g_free(hist->boundaries);
     hist->boundaries = g_new(uint64_t, hist->nbins - 1);
@@ -206,6 +208,8 @@ int block_latency_histogram_set(BlockAcctStats *stats, enum BlockAcctType type,
     g_free(hist->bins);
     hist->bins = g_new0(uint64_t, hist->nbins);
 
+    qemu_mutex_unlock(&stats->lock);
+
     return 0;
 }
 
@@ -213,12 +217,16 @@ void block_latency_histograms_clear(BlockAcctStats *stats)
 {
     int i;
 
+    qemu_mutex_lock(&stats->lock);
+
     for (i = 0; i < BLOCK_MAX_IOTYPE; i++) {
         BlockLatencyHistogram *hist = &stats->latency_histogram[i];
         g_free(hist->bins);
         g_free(hist->boundaries);
         memset(hist, 0, sizeof(*hist));
     }
+
+    qemu_mutex_unlock(&stats->lock);
 }
 
 static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
Signature · 1 line
2.55.0
author
#3 lore raw

[PULL 04/17] tests/unit: add reproducer for BlockAcctStats histogram locking race

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

block_latency_histogram_set() and block_latency_histograms_clear() replace BlockLatencyHistogram's nbins/boundaries/bins without taking stats->lock, while block_account_one_io() reads those same fields under that lock from whatever iothread completes the I/O.

Add a test that races two real threads against block_latency_histogram_set() and block_acct_start()/block_acct_done() on the same BlockAcctStats. Applied here it passes, since the previous two commits already take the lock; reverting them locally reproduces the abort this series fixes, in about a second.

CC Kevin Wolf <[email protected]>
CC Hanna Reitz <[email protected]>
CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC Andrey Drobyshev <[email protected]>

Message-ID: <[email protected]>

---
 tests/unit/test-block-accounting.c | 115 +++++++++++++++++++++++++++++
 tests/unit/meson.build             |   1 +
 2 files changed, 116 insertions(+)
 create mode 100644 tests/unit/test-block-accounting.c
tests/unit/test-block-accounting.c new file +115 -0
new file mode 100644
index 00000000000..7aae491cfc2
@@ -0,0 +1,115 @@
+/*
+ * SPDX-License-Identifier: GPL-2.0-or-later
+ *
+ * BlockAcctStats latency histogram locking regression test
+ *
+ * Copyright (c) 2026 Virtuozzo International GmbH.
+ *
+ * Regression test for missing stats->lock in
+ * block_latency_histogram_set()/block_latency_histograms_clear(),
+ * racing block_account_one_io() reading the same fields from an
+ * iothread. Aborts reliably before the fix, passes after it.
+ */
+
+#include "qemu/osdep.h"
+#include "block/block.h"
+#include "block/accounting.h"
+#include "system/block-backend.h"
+#include "system/block-backend-io.h"
+#include "qapi/error.h"
+#include "qemu/main-loop.h"
+#include "qemu/thread.h"
+
+#define RACE_DURATION_MS 2000
+#define NUM_READER_THREADS 8
+
+static bool stop_workers;
+
+/*
+ * Different bin counts, so the writer's g_free()/g_new() churn can be
+ * caught mid-update. Values are small enough (nanoseconds) that plain
+ * back-to-back start/done calls exercise every bin without sleeping.
+ */
+static uint64List boundaries_a[] = {
+    { .next = &boundaries_a[1], .value = 1000 },
+    { .next = &boundaries_a[2], .value = 5000 },
+    { .next = NULL,             .value = 50000 },
+};
+
+static uint64List boundaries_b[] = {
+    { .next = &boundaries_b[1], .value = 800 },
+    { .next = &boundaries_b[2], .value = 3000 },
+    { .next = &boundaries_b[3], .value = 20000 },
+    { .next = NULL,             .value = 200000 },
+};
+
+static void *writer_thread(void *opaque)
+{
+    BlockAcctStats *stats = opaque;
+
+    while (!qatomic_read(&stop_workers)) {
+        block_latency_histogram_set(stats, BLOCK_ACCT_READ, boundaries_a);
+        block_latency_histogram_set(stats, BLOCK_ACCT_READ, boundaries_b);
+        block_latency_histograms_clear(stats);
+    }
+
+    return NULL;
+}
+
+static void *reader_thread(void *opaque)
+{
+    BlockAcctStats *stats = opaque;
+
+    while (!qatomic_read(&stop_workers)) {
+        BlockAcctCookie cookie;
+
+        block_acct_start(stats, &cookie, 4096, BLOCK_ACCT_READ);
+        block_acct_done(stats, &cookie);
+    }
+
+    return NULL;
+}
+
+static void test_latency_histogram_race(void)
+{
+    BlockBackend *blk = blk_new(qemu_get_aio_context(),
+                                BLK_PERM_ALL, BLK_PERM_ALL);
+    BlockAcctStats *stats = blk_get_stats(blk);
+    QemuThread writer, readers[NUM_READER_THREADS];
+    int i;
+
+    /* Histogram has to be enabled (bins != NULL) before racing it. */
+    g_assert(block_latency_histogram_set(stats, BLOCK_ACCT_READ,
+                                         boundaries_a) == 0);
+
+    stop_workers = false;
+    qemu_thread_create(&writer, "hist-writer", writer_thread, stats,
+                       QEMU_THREAD_JOINABLE);
+    for (i = 0; i < NUM_READER_THREADS; i++) {
+        qemu_thread_create(&readers[i], "hist-reader", reader_thread, stats,
+                           QEMU_THREAD_JOINABLE);
+    }
+
+    g_usleep(RACE_DURATION_MS * 1000);
+    qatomic_set(&stop_workers, true);
+
+    qemu_thread_join(&writer);
+    for (i = 0; i < NUM_READER_THREADS; i++) {
+        qemu_thread_join(&readers[i]);
+    }
+
+    blk_unref(blk);
+}
+
+int main(int argc, char **argv)
+{
+    bdrv_init();
+    qemu_init_main_loop(&error_abort);
+
+    g_test_init(&argc, &argv, NULL);
+
+    g_test_add_func("/block-accounting/latency_histogram_race",
+                    test_latency_histogram_race);
+
+    return g_test_run();
+}
tests/unit/meson.build +1 -0
index 5ba6b1a2304..dc3fb954c03 100644
@@ -75,6 +75,7 @@ if have_block
     'test-blockjob': [testblock],
     'test-blockjob-txn': [testblock],
     'test-block-backend': [testblock],
+    'test-block-accounting': [testblock],
     'test-block-iothread': [testblock],
     'test-write-threshold': [testblock],
     'test-crypto-hash': [crypto],
Signature · 1 line
2.55.0
author
#4 lore raw

[PULL 13/17] block/export/fuse: fix regression with O_TRUNC when export is not growable

In reply to Kevin Wolf

From: Fiona Ebner <[email protected]>

Before commit a94a1d7699 ("fuse: Manually process requests (without libfuse)"), the O_TRUNC flag when open()-ing an export would be ignored. This is because libfuse sets FUSE_CAP_ATOMIC_O_TRUNC, so the kernel lets user space handle the O_TRUNC flag, which is ignored by the fuse code for export. After the commit, FUSE_CAP_ATOMIC_O_TRUNC is not set anymore, so the O_TRUNC flag is handled by the kernel, which executes a truncate.

For blockdev-based exports, this causes a regression, because opening with O_TRUNC would previously work, but results in an ENOTSUP after commit a94a1d7699. For file-based exports, the fact that truncate is executed can be considered an improvement in general. However, in combination with growable=off, this still results in a practical regression in combination with virt-fw-vars, which opens its output file with O_TRUNC and previously worked with a file-based export with growable=off. After commit a94a1d7699, the file is truncated upon open and then cannot grow, meaning virt-fw-vars won't be able to write the output.

To fix these regressions, while keeping the improved behavior for file-based exports with growable=on, set the FUSE_CAP_ATOMIC_O_TRUNC flag again if growable=off.

Fixes a94a1d7699 ("fuse: Manually process requests (without libfuse)")

Message-ID: <[email protected]>

---
 block/export/fuse.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
block/export/fuse.c +12 -0
index c0e8dfb6430..9ae22a2e003 100644
@@ -859,6 +859,18 @@ fuse_co_init(FuseExport *exp, struct fuse_init_out *out,
     uint32_t supported_flags = FUSE_ASYNC_READ | FUSE_ASYNC_DIO;
     uint32_t flags2 = 0;
 
+    if (!exp->growable) {
+        /*
+         * Back when libfuse was used, it would always set this flag and thus
+         * the kernel did not execute a truncate itself and passed along O_TRUNC
+         * to user space. Continue setting the flag for backwards compatibility
+         * when the export is not growable to avoid issues with O_TRUNC, i.e.
+         * blockdev-based exports running into ENOTSUP and file-based exports
+         * with growable=off to be truncated and then stuck with size 0.
+         */
+        supported_flags = FUSE_ATOMIC_O_TRUNC;
+    }
+
     if (in->major != 7) {
         error_report("FUSE major version mismatch: We have 7, but kernel has %"
                      PRIu32, in->major);
Signature · 1 line
2.55.0
author
#5 lore raw

[PULL 12/17] coroutine: fix lost wakeup in qemu_co_sleep_wake()

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

cache_clean_timer_del_and_wait() cancels the cache-cleaner coroutine by setting s->cache_clean_interval = 0 and calling qemu_co_sleep_wake() to cut short its qemu_co_sleep_ns_wakeable(). qemu_co_sleep_wake() is
fire-and-forget: it reads w->to_wake and silently returns when it is NULL. A sleeper that is between two iterations -- has just released s->lock but has not yet set w->to_wake inside qemu_co_sleep() -- loses the wake:

iothread0 timer coroutine main thread (qcow2 close)
------------------------- -------------------------
while-body (holding s->lock):

    read interval = 600
    wait_ns = 600 * NS
    release s->lock
                                      take s->lock
                                      interval = 0
                                      qemu_co_sleep_wake(w):
                                        w->to_wake == NULL -> skip
                                        return
                                      qemu_co_queue_wait(exit, s->lock):
                                        release s->lock
                                        yield
  qemu_co_sleep_ns_wakeable:
    aio_timer_init(+600 s)
    qemu_co_sleep:
      cas scheduled NULL -> "qsns"
      w->to_wake = co
      yield  [sleeps 600 s]

cache_clean_timer_del_and_wait() then blocks on cache_clean_timer_exit until the original 600 s expiry fires, and qcow2_close() holds BQL the whole time so the VM stalls behind it.

block_copy_kick() has the same shape. Fix the primitive once instead of working around it in each caller.

Use a tri-state for QemuCoSleep::to_wake:

  NULL     - idle
  co       - sleeper parked
  PENDING  - wake delivered, no sleeper yet (sticky)

qemu_co_sleep_wake() xchgs PENDING into to_wake: a real sleeper is woken, NULL/PENDING is left untouched so the wake stays sticky. qemu_co_sleep() cmpxchg-publishes itself as the sleeper; if a wake was delivered before it got there or races the publish, the cmpxchg observes PENDING and returns without yielding. On normal resume qemu_co_sleep() clears the PENDING the waker left behind so the next sleep starts clean.

A double-fire (real wake plus timer callback) is harmless: the first xchg returns the coroutine and wakes it; the second returns PENDING and is a no-op. Cancellation latency through qemu_co_sleep_wake() is now bounded by aio_co_wake() rather than by the sleep duration.

Fixes f86dde9a15 ("qcow2: Fix cache_clean_timer")
Cc Hanna Czenczek <[email protected]>
Cc Kevin Wolf <[email protected]>

Message-ID: <[email protected]>

---
 include/qemu/coroutine.h    | 17 +++++++++---
 tests/unit/test-coroutine.c | 53 +++++++++++++++++++++++++++++++++++++
 util/qemu-coroutine-sleep.c | 53 ++++++++++++++++++++++++++-----------
 3 files changed, 104 insertions(+), 19 deletions(-)
include/qemu/coroutine.h +13 -4
index e545bbf620f..1c31de60f94 100644
@@ -260,10 +260,19 @@ int coroutine_fn qemu_co_timeout(CoroutineEntry *entry, void *opaque,
                                  uint64_t timeout_ns, CleanupFunc clean);
 
 /**
- * Wake a coroutine if it is sleeping in qemu_co_sleep_ns. The timer will be
- * deleted. @sleep_state must be the variable whose address was given to
- * qemu_co_sleep_ns() and should be checked to be non-NULL before calling
- * qemu_co_sleep_wake().
+ * Wake a coroutine sleeping in qemu_co_sleep() or qemu_co_sleep_ns_wakeable().
+ * The timer set up by the latter is deleted on wakeup.
+ *
+ * The wake is sticky: if no sleeper is parked on @w at the time of the call,
+ * the wake is recorded on @w and consumed by the next qemu_co_sleep() on the
+ * same @w, which then returns without yielding. This closes the lost-wakeup
+ * window between two sleeps and is the documented behavior callers should
+ * rely on -- e.g. a cancellation signal raised between iterations of a
+ * sleep/work loop will shorten the next sleep instead of being dropped.
+ *
+ * The state persists until consumed: if no further qemu_co_sleep() is ever
+ * called on @w, the pending wake is harmlessly discarded when @w goes away.
+ * Multiple wakes coalesce -- the next sleep consumes at most one.
  */
 void qemu_co_sleep_wake(QemuCoSleep *w);
 
tests/unit/test-coroutine.c +53 -0

65 lines not on this page · raw message

util/qemu-coroutine-sleep.c +38 -15

84 lines not on this page · raw message

Signature · 1 line
2.55.0
author
#6 lore raw

[PULL 09/17] iotests: run the test pool with the 'fork' start method

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

run_tests_pool() shares the runner via the class attribute TestRunner.shared_self, relying on worker processes to inherit it. That only works with the 'fork' start method. Python 3.14 switched the Linux default to 'forkserver', so workers see shared_self as None and parallel runs abort with:

assert runner is not None
AssertionError

Only reproduces with Python 3.14+ and 'check -jN' (N > 1); meson runs one test per process and never calls run_tests_pool(), so CI is unaffected.

Request get_context('fork') explicitly; it is available on all supported Python versions and a no-op before 3.14.

Message-ID: <[email protected]>

---
 tests/qemu-iotests/testrunner.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
tests/qemu-iotests/testrunner.py +2 -2
index dbe2dddc32e..cc36867719d 100644
@@ -26,7 +26,7 @@
 import json
 import shutil
 import sys
-from multiprocessing import Pool
+from multiprocessing import get_context
 from typing import List, Optional, Any, Sequence, Dict
 from testenv import TestEnv
 
@@ -125,7 +125,7 @@ def run_tests_pool(self, tests: List[str],
         assert TestRunner.shared_self is None
         TestRunner.shared_self = self
 
-        with Pool(jobs) as p:
+        with get_context('fork').Pool(jobs) as p:
             results = p.starmap(self.proc_run_test,
                                 zip(tests, [test_field_width] * len(tests)))
 
Signature · 1 line
2.55.0
author
#7 lore raw

[PULL 11/17] iotests/migrate-bitmaps-postcopy-test: replace the timing assertion with a content check

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

downtime * 10 < postcopy_time was an unnormalized wall-clock heuristic (commit e80a4150a5) that fails on fast hosts, where the bitmap payload now transfers in under a second.

Check the actual invariant instead: right after RESUME, bitmap0's content hash on the destination must not yet match the fully migrated value. Throttle max-bandwidth first, since all-zero chunks skip the payload write and would otherwise let a fast host finish the transfer before the check runs.

CC Kevin Wolf <[email protected]>
CC Hanna Reitz <[email protected]>
CC Vladimir Sementsov-Ogievskiy <[email protected]>

Message-ID: <[email protected]>

---
 .../tests/migrate-bitmaps-postcopy-test           | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
tests/qemu-iotests/tests/migrate-bitmaps-postcopy-test +14 -1
index c519e6db8c7..33ff2b861f7 100755
@@ -160,12 +160,26 @@ class TestDirtyBitmapPostcopyMigration(iotests.QMPTestCase):
 
         self.vm_b.cmd('migrate-set-capabilities', capabilities=caps)
 
+        # Throttle so the chunks covering our discards (the only ones
+        # not skipped by the all-zero fast path) can't outrun the check
+        # below.
+        self.vm_a.cmd('migrate-set-parameters', max_bandwidth=16536)
+
         self.vm_a.cmd('migrate', uri='exec:cat>' + fifo)
 
         self.vm_a.cmd('migrate-start-postcopy')
 
         event_resume = self.vm_b.event_wait('RESUME')
         self.vm_b_events.append(event_resume)
+
+        # bitmap0 can't already have its final content: that requires
+        # the bit data to have actually arrived.
+        result = self.vm_b.qmp('x-debug-block-dirty-bitmap-sha256',
+                               node='drive0', name='bitmap0')
+        assert result['return']['sha256'] != all_discards_sha256
+
+        self.vm_a.cmd('migrate-set-parameters', max_bandwidth=0)
+
         return (event_resume, discards1_sha256, all_discards_sha256)
 
     def test_postcopy_success(self):
@@ -186,7 +200,6 @@ class TestDirtyBitmapPostcopyMigration(iotests.QMPTestCase):
         downtime = event_dist(event_stop, event_resume)
         postcopy_time = event_dist(event_resume, event_complete)
 
-        assert downtime * 10 < postcopy_time
         if debug:
             print('downtime:', downtime)
             print('postcopy_time:', postcopy_time)
Signature · 1 line
2.55.0
author
#8 lore raw

[PULL 10/17] iotests: skip FUSE tests when FUSE is not usable

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

file-io-error, fuse-allow-other and fuse-mmap-shared skip only when FUSE is not compiled in. When FUSE is built in but unusable at run time (no /dev/fuse access, fusermount lacking permissions), the export fails to mount with "Failed to mount FUSE session to export" and the tests report a spurious failure instead of skipping, like NBD tests already do for missing NBD support.

Add _notrun_on_fuse_error() to common.rc and use it in the shell tests. fuse-mmap-shared is Python, so it gets an equivalent inline check.

Message-ID: <[email protected]>

---
 tests/qemu-iotests/common.rc              | 14 ++++++++++++++
 tests/qemu-iotests/tests/file-io-error    |  4 +---
 tests/qemu-iotests/tests/fuse-allow-other |  2 ++
 tests/qemu-iotests/tests/fuse-mmap-shared |  9 ++++++---
 4 files changed, 23 insertions(+), 6 deletions(-)
tests/qemu-iotests/common.rc +14 -0
index 298bc483e0c..bcb1ec50a93 100644
@@ -981,6 +981,20 @@ _require_drivers()
     done
 }
 
+# Skip if FUSE is unusable: not compiled in, or the export failed to
+# mount. $1 is the failing 'block-export-add' reply.
+_notrun_on_fuse_error()
+{
+    case "$1" in
+        *"Parameter 'type' does not accept value 'fuse'"*)
+            _notrun "No FUSE support"
+            ;;
+        *"Failed to mount FUSE session"*)
+            _notrun "FUSE not usable in this environment"
+            ;;
+    esac
+}
+
 # Check that we have a file system that allows huge (but very sparse) files
 #
 _require_large_file()
tests/qemu-iotests/tests/file-io-error +1 -3
index fb8db73b31b..0d970c102f6 100755
@@ -89,9 +89,7 @@ output=$(_send_qemu_cmd $QEMU_HANDLE \
     'return' \
     | grep -v 'option allow_other only allowed if')
 
-if echo "$output" | grep -q "Parameter 'type' does not accept value 'fuse'"; then
-    _notrun 'No FUSE support'
-fi
+_notrun_on_fuse_error "$output"
 echo "$output"
 
 echo
tests/qemu-iotests/tests/fuse-allow-other +2 -0
index eaa39f8f236..50a36601d75 100755
@@ -77,6 +77,8 @@ fuse_export_add()
         _notrun "allow_other not supported"
     fi
 
+    _notrun_on_fuse_error "$output"
+
     echo "$output"
 }
 
tests/qemu-iotests/tests/fuse-mmap-shared +6 -3
index 52941a3bb69..b1901058946 100755
@@ -28,9 +28,12 @@ def test_fuse_support(mount_point):
     })
     test_qsd.stop()
     if 'error' in res:
-        assert (res['error']['desc'] ==
-                "Parameter 'type' does not accept value 'fuse'")
-        iotests.notrun('No FUSE support')
+        desc = res['error']['desc']
+        if desc == "Parameter 'type' does not accept value 'fuse'":
+            iotests.notrun('No FUSE support')
+        if 'Failed to mount FUSE session' in desc:
+            iotests.notrun('FUSE not usable in this environment')
+        assert False, desc
 
 # Shared mmap when using direct IO is only supported for Linux kernels >= 6.6
 # with commit e78662e818f94 ("fuse: add a new fuse init flag to relax
Signature · 1 line
2.55.0
author
#9 lore raw

[PULL 03/17] block/qapi: take stats->lock when reading BlockAcctStats for query-blockstats

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

bdrv_query_blk_stats() reads BlockAcctStats's counters, latency histogram, and per-interval TimedAverage stats without stats->lock, while block_account_one_io() updates the same fields under that lock from an iothread. timed_average_min()/max()/avg() make this worse than a stale read: they call check_expirations(), which can reset a window's sum/count/min/max -- a write, not just a read -- so this is a genuine race with a concurrent writer, not merely a slower reader like the scalar counters.

Take stats->lock for the whole call, both to close the race and to make the returned snapshot internally consistent (previously each field could reflect a different instant relative to concurrent updates).

block_acct_queue_depth() used to take the lock itself on every call; since bdrv_query_blk_stats() is its only caller and now already holds the lock, that would self-deadlock. Make it require the caller to hold stats->lock instead (documented and asserted).

CC Kevin Wolf <[email protected]>
CC Hanna Reitz <[email protected]>
CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC Andrey Drobyshev <[email protected]>

Message-ID: <[email protected]>

---
 include/block/accounting.h | 1 +
 block/accounting.c         | 3 +--
 block/qapi.c               | 3 +++
 3 files changed, 5 insertions(+), 2 deletions(-)
include/block/accounting.h +1 -0
index b1cf417b572..12d32460927 100644
@@ -116,6 +116,7 @@ void block_acct_invalid(BlockAcctStats *stats, enum BlockAcctType type);
 void block_acct_merge_done(BlockAcctStats *stats, enum BlockAcctType type,
                            int num_requests);
 int64_t block_acct_idle_time_ns(BlockAcctStats *stats);
+/* Caller must hold stats->stats->lock. */
 double block_acct_queue_depth(BlockAcctTimedStats *stats,
                               enum BlockAcctType type);
 int block_latency_histogram_set(BlockAcctStats *stats, enum BlockAcctType type,
block/accounting.c +1 -2
index 6e06c7609eb..038af370170 100644
@@ -318,10 +318,9 @@ double block_acct_queue_depth(BlockAcctTimedStats *stats,
     uint64_t sum, elapsed;
 
     assert(type < BLOCK_MAX_IOTYPE);
+    assert(qemu_mutex_trylock(&stats->stats->lock) == -EBUSY);
 
-    qemu_mutex_lock(&stats->stats->lock);
     sum = timed_average_sum(&stats->latency[type], &elapsed);
-    qemu_mutex_unlock(&stats->stats->lock);
 
     return (double) sum / elapsed;
 }
block/qapi.c +3 -0
index eabfbfc2585..1dfac510918 100644
@@ -535,6 +535,8 @@ static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
     BlockAcctTimedStats *ts = NULL;
     BlockLatencyHistogram *hgram;
 
+    qemu_mutex_lock(&stats->lock);
+
     ds->rd_bytes = stats->nr_bytes[BLOCK_ACCT_READ];
     ds->wr_bytes = stats->nr_bytes[BLOCK_ACCT_WRITE];
     ds->zone_append_bytes = stats->nr_bytes[BLOCK_ACCT_ZONE_APPEND];
@@ -624,6 +626,7 @@ static void bdrv_query_blk_stats(BlockDeviceStats *ds, BlockBackend *blk)
         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_ZONE_APPEND]);
     ds->flush_latency_histogram
         = bdrv_latency_histogram_stats(&hgram[BLOCK_ACCT_FLUSH]);
+    qemu_mutex_unlock(&stats->lock);
 }
 
 static BlockStats * GRAPH_RDLOCK
Signature · 1 line
2.55.0
author
#10 lore raw

[PULL 14/17] iotests: test O_TRUNC behavior for fuse exports

In reply to Kevin Wolf

From: Fiona Ebner <[email protected]>

The test cases for the blockdev-based export and for the file-based export with growable=on work before commit a94a1d7699 ("fuse: Manually process requests (without libfuse)"), then are broken until commit "block/export/fuse: fix regression with O_TRUNC when export is growable".

The test case for the blockdev-based export requires passwordless sudo for losetup and chmod similar to test 108.

Message-ID: <[email protected]>

---
 tests/qemu-iotests/tests/fuse-truncate     | 171 +++++++++++++++++++++
 tests/qemu-iotests/tests/fuse-truncate.out |   5 +
 2 files changed, 176 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/fuse-truncate
 create mode 100644 tests/qemu-iotests/tests/fuse-truncate.out
tests/qemu-iotests/tests/fuse-truncate new file +171 -0
new file mode 100755
index 00000000000..10bc1175c09
@@ -0,0 +1,171 @@
+#!/usr/bin/env python3
+# group: rw
+#
+# Test how fuse exports behave with regard to O_TRUNC.
+#
+# Copyright (C) 2026 Proxmox Server Solutions GmbH
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+import os
+import subprocess
+from pathlib import Path
+
+import iotests
+from iotests import qemu_img, QemuStorageDaemon
+
+fuse_mount_point = os.path.join(iotests.test_dir, 'export.fuse')
+image_size = 1 * 1024 * 1024
+image = os.path.join(iotests.test_dir, 'image.' + iotests.imgfmt)
+
+def check_fuse_support():
+    Path(fuse_mount_point).touch()
+    test_qsd = QemuStorageDaemon('--blockdev', 'null-co,node-name=node0',
+                                 qmp=True)
+    res = test_qsd.qmp('block-export-add', {
+        'id': 'exp0',
+        'type': 'fuse',
+        'node-name': 'node0',
+        'mountpoint': fuse_mount_point,
+        'allow-other': 'off'
+    })
+    test_qsd.stop()
+    os.remove(fuse_mount_point)
+    if 'error' in res:
+        assert (res['error']['desc'] ==
+                "Parameter 'type' does not accept value 'fuse'")
+        iotests.notrun('No FUSE support')
+
+def check_sudo_support():
+    try:
+        subprocess.run(['sudo', '-n', 'losetup', '--version'],
+                       capture_output=True, check=True)
+    except subprocess.CalledProcessError:
+        return False
+    try:
+        subprocess.run(['sudo', '-n', 'chmod', '--version'],
+                       capture_output=True, check=True)
+    except subprocess.CalledProcessError:
+        return False
+    return True
+
+check_fuse_support()
+
+class TestTruncateBase(iotests.QMPTestCase):
+    growable = False
+    supports_preconditions = True
+
+    def evaluate_preconditions(self):
+        return
+
+    def add_blockdev(self):
+        qemu_img('create', '-f', iotests.imgfmt, image, str(image_size))
+        self.qsd.cmd('blockdev-add', {
+            'node-name': 'node0',
+            'driver': iotests.imgfmt,
+            'file': {
+                'driver': 'file',
+                'filename': image
+            }
+        })
+
+    def cleanup_blockdev(self):
+        os.remove(image)
+
+    def add_export(self):
+        self.qsd.cmd('block-export-add', {
+            'id': 'exp0',
+            'type': 'fuse',
+            'node-name': 'node0',
+            'mountpoint': fuse_mount_point,
+            'growable': self.growable,
+            'writable': True,
+            'allow-other': 'off'
+        })
+
+    def stop_qsd(self):
+        if self.qsd:
+            self.qsd.cmd('block-export-del', {'id': 'exp0'})
+            self.qsd.stop()
+            self.qsd = None
+
+    def setUp(self):
+        self.evaluate_preconditions()
+        if not self.supports_preconditions:
+            return
+        Path(fuse_mount_point).touch()
+        self.qsd = QemuStorageDaemon(qmp=True)
+        self.add_blockdev()
+        self.add_export()
+
+    def tearDown(self):
+        if not self.supports_preconditions:
+            return
+        self.stop_qsd()
+        self.cleanup_blockdev()
+        os.remove(fuse_mount_point)
+
+class TestTruncateFileGrowable(TestTruncateBase):
+    growable = True
+
+    def test_o_trunc(self):
+        with open(fuse_mount_point, 'w+b') as file:
+            file.seek(0, os.SEEK_END)
+            self.assertEqual(file.tell(), 0)
+            file.write(b"test")
+        self.stop_qsd()
+
+class TestTruncateFileNotGrowable(TestTruncateBase):
+    growable = False
+
+    def test_o_trunc(self):
+        with open(fuse_mount_point, 'w+b') as file:
+            file.seek(0, os.SEEK_END)
+            self.assertEqual(file.tell(), image_size)
+            file.seek(0, os.SEEK_SET)
+            file.write(b"test")
+        self.stop_qsd()
+
+class TestTruncateBlockdev(TestTruncateBase):
+    growable = False
+
+    def evaluate_preconditions(self):
+        self.supports_preconditions = check_sudo_support()
+
+    def add_blockdev(self):
+        qemu_img('create', '-f', iotests.imgfmt, image, str(image_size))
+        res = subprocess.run(['sudo', '-n', 'losetup', '--show', '-f', image],
+                             check=True, capture_output=True, text=True)
+        self.loopdev = res.stdout.strip()
+        subprocess.run(['sudo', '-n', 'chmod', 'go+rw', self.loopdev],
+                       check=True, capture_output=True)
+        self.qsd.cmd('blockdev-add', {
+            'node-name': 'node0',
+            'driver': iotests.imgfmt,
+            'file': {
+                'driver': 'host_device',
+                'filename': self.loopdev
+            }
+        })
+
+    def cleanup_blockdev(self):
+        subprocess.run(['sudo', '-n', 'losetup', '--detach', self.loopdev],
+                       check=True, capture_output=True)
+        os.remove(image)
+
+    def test_o_trunc(self):
+        if not self.supports_preconditions:
+            iotests.case_notrun('No passwordless sudo for losetup and chmod')
+            return
+
+        with open(fuse_mount_point, 'w+b') as file:
+            file.seek(0, os.SEEK_END)
+            self.assertEqual(file.tell(), image_size)
+            file.seek(0, os.SEEK_SET)
+            file.write(b"test")
+        self.stop_qsd()
+
+if __name__ == '__main__':
+    iotests.main(supported_fmts=['raw'],
+                 supported_protocols=['file'],
+                 supported_platforms=['linux'])
tests/qemu-iotests/tests/fuse-truncate.out new file +5 -0
new file mode 100644
index 00000000000..8d7e9967009
@@ -0,0 +1,5 @@
+...
+----------------------------------------------------------------------
+Ran 3 tests
+
+OK
Signature · 1 line
2.55.0
#11 lore raw

Re: [PULL 14/17] iotests: test O_TRUNC behavior for fuse exports

Hi Kevin and Fiona,
Please take a look at the following CI failure and send a new pull request:

https://gitlab.com/qemu-project/qemu/-/jobs/15583116603#L174

88/104 block-raw-optional+block-slow - qemu:io-raw-fuse-truncate ERROR 0.24s exit status 1

Quoted 1 line
Quoted 1 line
Quoted 1 line

MESON_TEST_ITERATION=1 MSAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1 RUST_BACKTRACE=1 ASAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_summary=1 MALLOC_PERTURB_=106 UBSAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1 LD_LIBRARY_PATH=/builds/qemu-project/qemu/build/subprojects/libvfio-user/lib PYTHON=/builds/qemu-project/qemu/build/pyvenv/bin/python3 /builds/qemu-project/qemu/build/pyvenv/bin/python3 /builds/qemu-project/qemu/build/../tests/qemu-iotests/check -tap -raw fuse-truncate --source-dir /builds/qemu-project/qemu/tests/qemu-iotests --build-dir /builds/qemu-project/qemu/build/tests/qemu-iotests

――――――――――――――――――――――――――――――――――――― ✀ ――――――――――――――――――――――――――――――――――――― stderr:

builds/qemu-project/qemu/build/scratch/raw-file-fuse-truncate/fuse-truncate.out.bad renamed from builds/qemu-project/qemu/tests/qemu-iotests/tests/fuse-truncate.out +6 -1
@@ -1,5 +1,23 @@
-...
+E..
+======================================================================
+ERROR: test_o_trunc (__main__.TestTruncateBlockdev)
+----------------------------------------------------------------------
+Traceback (most recent call last):
+ File "/builds/qemu-project/qemu/tests/qemu-iotests/tests/fuse-truncate",

line 93, in setUp
+ self.evaluate_preconditions()
+ File "/builds/qemu-project/qemu/tests/qemu-iotests/tests/fuse-truncate", line 133, in evaluate_preconditions
+ self.supports_preconditions = check_sudo_support()
+ File "/builds/qemu-project/qemu/tests/qemu-iotests/tests/fuse-truncate", line 41, in check_sudo_support
+ subprocess.run(['sudo', '-n', 'losetup', '--version'],
+ File "/usr/lib64/python3.9/subprocess.py", line 505, in run
+ with Popen(*popenargs, **kwargs) as process:
+ File "/usr/lib64/python3.9/subprocess.py", line 951, in __init__
+ self._execute_child(args, executable, preexec_fn, close_fds,
+ File "/usr/lib64/python3.9/subprocess.py", line 1837, in _execute_child
+ raise child_exception_type(errno_num, err_msg, err_filename) +FileNotFoundError: [Errno 2] No such file or directory: 'sudo'

author
#12 lore raw

[PULL 17/17] iotests: increase timeouts for tests to 5 minutes

In reply to Kevin Wolf

From: Daniel P. Berrangé <[email protected]>

Currently we have tests timeout set to 3 minutes, on the basis that they're generally done in less than a minute. I've hit a couple of random failures suggesting that's not sufficiently pessimistic. Increase the timeout to 5 minutes to have a greater safety net in high load scenarios.

Message-ID: <[email protected]>

---
 tests/qemu-iotests/meson.build | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
tests/qemu-iotests/meson.build +7 -8
index bc6132a0f7f..8857f25f291 100644
@@ -52,16 +52,17 @@ foreach driver, speed: qemu_iotests_drivers
               '-tap', '-' + driver, item,
               '--source-dir', meson.current_source_dir(),
               '--build-dir', meson.current_build_dir()]
-      # Some individual tests take as long as 45 seconds
-      # Bump the timeout to 3 minutes for some headroom
-      # on slow machines to minimize spurious failures
+      # Some individual tests take as long as 3 minutes
+      # in high load scenarios. Bump the timeout to 5
+      # minutes for some headroom on slow / loaded
+      # machines to minimize spurious failures
       test('io-' + driver + '-' + item,
            python,
            args: args,
            depends: qemu_iotests_binaries,
            env: qemu_iotests_env,
            protocol: 'tap',
-           timeout: 180,
+           timeout: 300,
            suite: suites)
     endforeach
   endif
@@ -94,16 +95,14 @@ foreach driver, speed: qemu_iotests_drivers
               '-tap', '-' + driver, item,
               '--source-dir', meson.current_source_dir(),
               '--build-dir', meson.current_build_dir()]
-      # Some individual tests take as long as 45 seconds
-      # Bump the timeout to 3 minutes for some headroom
-      # on slow machines to minimize spurious failures
+      # See earlier note about timeouts
       test('io-' + driver + '-' + item,
            python,
            args: args,
            depends: qemu_iotests_binaries,
            env: qemu_iotests_env,
            protocol: 'tap',
-           timeout: 180,
+           timeout: 300,
            suite: suites)
   endforeach
 endforeach
Signature · 1 line
2.55.0
author
#13 lore raw

[PULL 16/17] hw/block/fdc: report a missing address mark on an empty drive

In reply to Kevin Wolf

From: Christian Quante <[email protected]>

READ ID on a drive with no medium terminates normally and returns the made-up sector ID left over from the "Pretend we are spinning" emulation. The only error path is a data rate mismatch, and media_rate is assigned solely by pick_geometry(); it is never reset when the medium is removed. A guest that has just ejected a diskette is therefore told that one is still present.

READ, WRITE and FORMAT have a related problem: fd_seek() answers 2 both for "track/head out of range" and for "no medium", so the callers report ST0 = ABNTERM with ST1 = 0x00 either way. Without ST1.MA the guest cannot tell an absent diskette from a transient error. Give fd_seek() a return code of its own for an absent medium, and let both switch statements report the missing address mark for it.

The comments on the two switches were swapped: fd_seek() answers 2 for a bad track or head and 3 for a sector past last_sect, but case 2 read "sect too big" and case 3 "track too big". Both now say what they mean.

This is a behaviour change for FORMAT TRACK on an empty drive as well, which now answers ST1.MA rather than ST1 = 0x00. None of the guests tested reaches that path -- DOS gives up during media sensing and never issues the command -- but it seemed wrong to leave fdctrl_format_sector() falling through to "default" for a case fd_seek() now reports explicitly.

Failing READ ID does not make guests detect the removal: real hardware never completes the command on an empty drive, because there are no index pulses, and OS/2 for one relies on that timeout. It does stop the controller from claiming a diskette that is not there.

tests/qtest/fdc-test.c starts QEMU with "-device floppy,id=floppy0" and no medium, and test_read_id asserts a normal termination with a made-up cylinder 8 / head 1. That contradicts its neighbours test_no_media_on_start and test_media_change, which state that DSKCHG signals an absent medium. Insert a medium before READ ID and eject it afterwards -- the rewritten test passes before and after this change -- and add test_read_id_no_media for the empty drive.

Guests checked, reading and writing, with and without a medium: Linux 2.0.34 and 7.0, PC-DOS 7, IBM DOS 5.02, Windows for Workgroups 3.11 and OS/2 2.11. None changes behaviour. No version of the Linux floppy driver from 1.2.13 to master issues READ ID at all -- FD_READID is defined in the uapi header for FDRAWCMD users and the driver never sends it -- so Linux detects an empty drive by stepping the head and reading DSKCHG instead.

Message-ID: <[email protected]>

[kwolf: Added fd_seek() comment for new return value 5]
---
 hw/block/fdc.c         | 50 +++++++++++++++++++++++++-----
 tests/qtest/fdc-test.c | 70 +++++++++++++++++++++++++++++++++++++-----
 2 files changed, 106 insertions(+), 14 deletions(-)
hw/block/fdc.c +43 -7
index 9b2409cfa4c..1178b959a64 100644
@@ -196,6 +196,12 @@ static void fd_init(FDrive *drv)
 
 #define NUM_SIDES(drv) ((drv)->flags & FDISK_DBL_SIDES ? 2 : 1)
 
+/* Is a diskette present in the drive? */
+static bool fd_media_present(FDrive *drv)
+{
+    return drv->blk != NULL && blk_is_inserted(drv->blk);
+}
+
 static int fd_sector_calc(uint8_t head, uint8_t track, uint8_t sect,
                           uint8_t last_sect, uint8_t num_sides)
 {
@@ -222,6 +228,7 @@ static int fd_offset(FDrive *drv)
  * returns 2 if track is invalid
  * returns 3 if sector is invalid
  * returns 4 if seek is disabled
+ * returns 5 if no floppy is inserted
  */
 static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
                    int enable_seek)
@@ -258,7 +265,7 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
 #endif
         drv->head = head;
         if (drv->track != track) {
-            if (drv->blk != NULL && blk_is_inserted(drv->blk)) {
+            if (fd_media_present(drv)) {
                 drv->media_changed = 0;
             }
             ret = 1;
@@ -267,8 +274,8 @@ static int fd_seek(FDrive *drv, uint8_t head, uint8_t track, uint8_t sect,
         drv->sect = sect;
     }
 
-    if (drv->blk == NULL || !blk_is_inserted(drv->blk)) {
-        ret = 2;
+    if (!fd_media_present(drv)) {
+        ret = 5;
     }
 
     return ret;
@@ -1476,14 +1483,24 @@ static void fdctrl_start_transfer(FDCtrl *fdctrl, int direction)
                                   NUM_SIDES(cur_drv)));
     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
     case 2:
-        /* sect too big */
+        /* track/head out of range */
         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
         fdctrl->fifo[3] = kt;
         fdctrl->fifo[4] = kh;
         fdctrl->fifo[5] = ks;
         return;
+    case 5:
+        /*
+         * No medium: there is no address mark to be found.  Guests that tell
+         * an absent diskette from an unreadable one rely on ST1.MA.
+         */
+        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
+        fdctrl->fifo[3] = kt;
+        fdctrl->fifo[4] = kh;
+        fdctrl->fifo[5] = ks;
+        return;
     case 3:
-        /* track too big */
+        /* sector too big */
         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
         fdctrl->fifo[3] = kt;
         fdctrl->fifo[4] = kh;
@@ -1791,14 +1808,21 @@ static void fdctrl_format_sector(FDCtrl *fdctrl)
                                   NUM_SIDES(cur_drv)));
     switch (fd_seek(cur_drv, kh, kt, ks, fdctrl->config & FD_CONFIG_EIS)) {
     case 2:
-        /* sect too big */
+        /* track/head out of range */
         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, 0x00, 0x00);
         fdctrl->fifo[3] = kt;
         fdctrl->fifo[4] = kh;
         fdctrl->fifo[5] = ks;
         return;
+    case 5:
+        /* no medium */
+        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
+        fdctrl->fifo[3] = kt;
+        fdctrl->fifo[4] = kh;
+        fdctrl->fifo[5] = ks;
+        return;
     case 3:
-        /* track too big */
+        /* sector too big */
         fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_EC, 0x00);
         fdctrl->fifo[3] = kt;
         fdctrl->fifo[4] = kh;
@@ -2306,6 +2330,18 @@ static void fdctrl_result_timer(void *opaque)
     FDCtrl *fdctrl = opaque;
     FDrive *cur_drv = get_cur_drv(fdctrl);
 
+    /*
+     * An empty drive has no address marks to read.  Completing READ ID
+     * successfully, with the made-up sector ID left over from the "spinning"
+     * emulation below, tells the guest that a diskette is still present after
+     * it has been ejected.  The only error path left was a data rate mismatch,
+     * and media_rate is never reset when the medium is removed.
+     */
+    if (!fd_media_present(cur_drv)) {
+        FLOPPY_DPRINTF("read id on empty drive\n");
+        fdctrl_stop_transfer(fdctrl, FD_SR0_ABNTERM, FD_SR1_MA, 0x00);
+        return;
+    }
     /* Pretend we are spinning.
      * This is needed for Coherent, which uses READ ID to check for
      * sector interleaving.
tests/qtest/fdc-test.c +63 -7

112 lines not on this page · raw message

Signature · 1 line
2.55.0
author
#14 lore raw

[PULL 07/17] dmg: reject inconsistent UDRW chunk sector count and length (CVE-2026-65928)

In reply to Kevin Wolf

From: Stefan Hajnoczi <[email protected]>

The chunk metadata contains both:
- Sector count: number of 512-byte sectors in the virtual disk
- Length: number of bytes in the image file

The UDRW chunk type indicates uncompressed data that can be accessed directly. The code is missing input validation to verify that sector count is consistent with length.

If sector count is larger than length, then read requests can access beyond the end of the s->uncompressed_chunk buffer. This is an out-of-bounds heap access that could lead to a crash or an information leak.

While we're at it, also zero the end of the last sector when length is unaligned. This prevents information leaks from the s->uncompressed_chunk buffer.

Fixes: CVE-2026-65928
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3846

Message-ID: <[email protected]>

---
 block/dmg.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
block/dmg.c +25 -0
index 6f8120e0338..5d7d3b8901f 100644
@@ -312,6 +312,21 @@ static int dmg_read_mish_block(BDRVDMGState *s, DmgHeaderState *ds,
             goto fail;
         }
 
+        /*
+         * Uncompressed chunk length must match sector count. Compressed chunks
+         * are validated during dmg_read_chunk() since the uncompressed size is
+         * not known ahead of time.
+         */
+        if (s->types[i] == UDRW) {
+            if (s->sectorcounts[i] != DIV_ROUND_UP(s->lengths[i], 512)) {
+                error_report("length %" PRIu64 " for chunk %" PRIu32
+                             " is inconsistent with sector count %" PRIu64,
+                             s->lengths[i], i, s->sectorcounts[i]);
+                ret = -EINVAL;
+                goto fail;
+            }
+        }
+
         update_max_chunk_size(s, i, &ds->max_compressed_size,
                               &ds->max_sectors_per_chunk);
         offset += 40;
@@ -722,6 +737,16 @@ dmg_read_chunk(BlockDriverState *bs, uint64_t sector_num)
             if (ret < 0) {
                 return -1;
             }
+
+            /*
+             * Zero the unread part of the last sector when chunk length is
+             * unaligned to avoid exposing uninitialized memory. Valid image
+             * files may never hit this case, but cover it to be safe.
+             */
+            if (s->lengths[chunk] & 511) {
+                size_t trailing_bytes = 512 - (s->lengths[chunk] & 511);
+                memset(s->uncompressed_chunk + s->lengths[chunk], 0, trailing_bytes);
+            }
             break;
         case UDZE: /* zeros */
         case UDIG: /* ignore */
Signature · 1 line
2.55.0
author
#15 lore raw

[PULL 05/17] dmg: fix out-of-bounds load in search_chunk() (CVE-2026-65929)

In reply to Kevin Wolf

From: Stefan Hajnoczi <[email protected]>

The binary search in search_chunk() uses s->n_chunks as the (inclusive) upper bound. Chunk indices are in the right-open interval [0, s->n_chunks) so it is wrong to search all the way up to s->n_chunks rather than s->n_chunks - 1.

The worst case security scenario I can see is convincing a victim to hotplug a malicious DMG file to a running guest, potentially causing QEMU to crash when loading from memory beyond the end of s->sectors[] or s->sectorscounts[]. This could be a denial of service.

Fixes: CVE-2026-65929
Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/3844

Message-ID: <[email protected]>

---
 block/dmg.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
block/dmg.c +4 -1
index 33dcb3a3498..e325127d144 100644
@@ -609,7 +609,10 @@ static inline int is_sector_in_chunk(BDRVDMGState *s,
 static inline uint32_t search_chunk(BDRVDMGState *s, uint64_t sector_num)
 {
     /* binary search */
-    uint32_t chunk1 = 0, chunk2 = s->n_chunks, chunk3;
+    uint32_t chunk1 = 0, chunk2 = s->n_chunks - 1, chunk3;
+    if (s->n_chunks == 0) {
+        goto err; /* should never happen */
+    }
     while (chunk1 <= chunk2) {
         chunk3 = (chunk1 + chunk2) / 2;
         if (s->sectors[chunk3] > sector_num) {
Signature · 1 line
2.55.0
author
#16 lore raw

[PULL 06/17] dmg: refuse to open files with no chunks

In reply to Kevin Wolf

From: Stefan Hajnoczi <[email protected]>

The dmg block driver expects the disk image file to contain at least one chunk. Refuse to open such files. This ensures that dmg block driver state always has non-NULL s->sectors[] and related fields.

Note that the previous commit fixed the only known way to trigger a crash. This patch is just for defense - let's avoid opening the file and having NULL pointers in dmg block driver state.

Resolves: https://gitlab.com/qemu-project/qemu/-/work_items/4021

Message-ID: <[email protected]>

---
 block/dmg.c | 6 ++++++
 1 file changed, 6 insertions(+)
block/dmg.c +6 -0
index e325127d144..6f8120e0338 100644
@@ -559,6 +559,12 @@ static int dmg_open(BlockDriverState *bs, QDict *options, int flags,
         goto fail;
     }
 
+    /* There must be at least one chunk */
+    if (s->n_chunks == 0) {
+        ret = -EINVAL;
+        goto fail;
+    }
+
     /* initialize zlib engine */
     s->compressed_chunk = qemu_try_blockalign(bs->file->bs,
                                               ds.max_compressed_size + 1);
Signature · 1 line
2.55.0
author
#17 lore raw

[PULL 15/17] hw/block/fdc: select the drive named by the READ ID command

In reply to Kevin Wolf

From: Christian Quante <[email protected]>

Every other command handler begins by latching the drive from the command byte:

    SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);

fdctrl_handle_readid() does not, so it works on whichever drive happened to be selected last. A guest that issues READ ID for a drive other than the one currently selected gets an answer about the wrong one.

It has gone unnoticed because a driver normally writes the DOR to spin up the motor first, and that write selects the drive as a side effect. The controller does not require it, though, and the command carries the drive number for a reason.

Message-ID: <[email protected]>

---
 hw/block/fdc.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
hw/block/fdc.c +4 -1
index 2c1681b7d0a..9b2409cfa4c 100644
@@ -1936,7 +1936,10 @@ static void fdctrl_handle_save(FDCtrl *fdctrl, int direction)
 
 static void fdctrl_handle_readid(FDCtrl *fdctrl, int direction)
 {
-    FDrive *cur_drv = get_cur_drv(fdctrl);
+    FDrive *cur_drv;
+
+    SET_CUR_DRV(fdctrl, fdctrl->fifo[1] & FD_DOR_SELMASK);
+    cur_drv = get_cur_drv(fdctrl);
 
     cur_drv->head = (fdctrl->fifo[1] >> 2) & 1;
     timer_mod(fdctrl->result_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
Signature · 1 line
2.55.0
author
#18 lore raw

[PULL 08/17] qcow2: do not try to clear the dirty bit on a read-only node

In reply to Kevin Wolf

From: "Denis V. Lunev" <[email protected]>

qcow2_do_close() -> qcow2_inactivate() clears the dirty bit with a plain write to bs->file, unconditionally. A read-only node can still be dirty, inherited from an earlier writable session, and that write then hits a missing BLK_PERM_WRITE and asserts in bdrv_co_write_req_prepare() (block/io.c) on an entirely ordinary close -- closing is expected, the dirty bit on a read-only node is not.

Skip the clear for read-only nodes, same as read access already does. Any other still-dirty node keeps the unguarded write: it is expected to hold write permission, and a missing one there is a bug worth seeing.

Message-ID: <[email protected]>

---
 block/qcow2.c              |  6 +++++-
 tests/qemu-iotests/039     | 11 +++++++++++
 tests/qemu-iotests/039.out |  3 +++
 3 files changed, 19 insertions(+), 1 deletion(-)
block/qcow2.c +5 -1
index 19271b10a49..7292dd036c9 100644
@@ -2870,7 +2870,11 @@ static int GRAPH_RDLOCK qcow2_inactivate(BlockDriverState *bs)
                      strerror(-ret));
     }
 
-    if (result == 0) {
+    /*
+     * A read-only node cannot resolve an inherited dirty bit here;
+     * leave it dirty, same as plain read access already does.
+     */
+    if (result == 0 && !bdrv_is_read_only(bs)) {
         qcow2_mark_clean(bs);
     }
 
tests/qemu-iotests/039 +11 -0
index e43e7026ce3..94a8bfe754e 100755
@@ -84,6 +84,17 @@ $QEMU_IO -r -c "read -P 0x5a 0 512" "$TEST_IMG" | _filter_qemu_io
 # The dirty bit must be set
 _qcow2_dump_header | grep incompatible_features
 
+echo
+echo "== Read-only open must not crash on close =="
+
+# We must not try to write the QCOW2 header to a read-only image.
+$QEMU_IMG info --image-opts \
+    "driver=$IMGFMT,read-only=on,file.driver=file,file.filename=$TEST_IMG,file.read-only=off" \
+    > /dev/null
+
+# The dirty bit must still be set: this open never wrote any guest data
+_qcow2_dump_header | grep incompatible_features
+
 echo
 echo "== Repairing the image file must succeed =="
 
tests/qemu-iotests/039.out +3 -0
index 8fdbcc528aa..c66361128f6 100644
@@ -24,6 +24,9 @@ read 512/512 bytes at offset 0
 512 bytes, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 incompatible_features     [0]
 
+== Read-only open must not crash on close ==
+incompatible_features     [0]
+
 == Repairing the image file must succeed ==
 ERROR cluster 5 refcount=0 reference=1
 Rebuilding refcount structure
Signature · 1 line
2.55.0