public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
* [PATCH qemu] fix windows retrim on scsi-hd: emulate GET LBA STATUS
@ 2026-11-24 17:29 Dirk Nehring
  0 siblings, 0 replies; only message in thread
From: Dirk Nehring @ 2026-11-24 17:29 UTC (permalink / raw)
  To: dnehring, pve-devel

scsi-hd reports thin provisioning when discard is enabled but rejects
GET LBA STATUS, which Windows sends before it retrims a thin-provisioned
volume ("Optimize Drives", defrag /L). Current Windows Server 2022 then
skips the retrim with "Incorrect function. (0x80070001)", so space freed
in the guest is not given back to the storage. This affects every
Windows guest with a virtio-scsi disk and discard=on, as vioscsi passes
the command through to QEMU.

Add a patch emulating the command, reporting every LBA as "mapped or
unknown". Tested with Windows Server 2022 build 20348.5622 on a default
VM config (virtio-scsi-single, discard=on, LVM-thin): the retrim now
completes and the freed space is returned.

Signed-off-by: Dirk Nehring <dnehring@marcant.net>
---

Notes:

The same change against plain QEMU 11.1.3, with the full rationale in
its commit message, is the patch this adds as extra/0008. It is not on
qemu-devel yet. If you prefer it to go upstream first, please say so;
we can send it there, or you can forward it with this thread as
reference.

Background: since a 2026 Windows update, "Optimize Drives" fails on
every Windows guest with a virtio-scsi disk and discard=on with event
264 "Incorrect function. (0x80070001)" (see virtio-win issue #1574).
Delete-time TRIM still works, but a retrim, e.g. after deleting with
delete notifications off or after a migration, frees nothing on thin
storage. We hit it on NetApp FAS LUNs and reproduced it on LVM-thin.
The driver fix discussed there (virtio-win PR #1653) changes viostor
(virtio-blk) only; vioscsi passes the CDB through, so QEMU has to
answer it.

A QEMU trace shows the command Windows sends:
  9e 12 00 00 00 00 00 00 08 00 00 1f ff f8 00 00
i.e. GET LBA STATUS from LBA 2048 with an ALLOCATION LENGTH of
0x1ffff8. scsi-disk rejects it with INVALID FIELD IN CDB, first
because the service action is not implemented, and second because
scsi_disk_emulate_command() refuses any emulated command asking for
more than 64 KiB. The patch handles both: every LBA is reported as
"mapped or unknown" (without querying the block layer, so RBD and
other network storage cannot block), and GET LBA STATUS gets a 64 KiB
buffer with the rest returned as residual.

No compat property is needed: only a command that used to fail is
added, so it also helps VMs pinned to an older machine version.

Tested on Proxmox VE 9.2.32 with Windows Server 2022 build 20348.5622
and virtio-win 0.1.302, q35 (pc-q35-11.1), virtio-scsi-single, a
16 GiB data disk on LVM-thin with discard=on, NTFS with 4 KiB
clusters. 4 GiB written and deleted with delete notifications off,
then "defrag T: /L":

                       pve-qemu-kvm 11.1.3-4    with this patch
  result               event 264, retrim        event 258, retrim
                       aborted                  completed
  thin LV usage        4140 MiB                 46 MiB

The 2022 release build 20348.587 tolerates the failed command, which
is why older guests were not affected.

The new qtest (virtio-scsi-test: get-lba-status, including the exact
CDB Windows sends) and the existing virtio-scsi qtests pass;
checkpatch.pl is clean. We keep the test VM around and are happy to
run further tests or traces.

 ...008-scsi-disk-emulate-GET-LBA-STATUS.patch | 329 ++++++++++++++++++
 debian/patches/series                         |   1 +
 2 files changed, 330 insertions(+)
 create mode 100644 debian/patches/extra/0008-scsi-disk-emulate-GET-LBA-STATUS.patch

diff --git a/debian/patches/extra/0008-scsi-disk-emulate-GET-LBA-STATUS.patch b/debian/patches/extra/0008-scsi-disk-emulate-GET-LBA-STATUS.patch
new file mode 100644
index 0000000..0bb12f4
--- /dev/null
+++ b/debian/patches/extra/0008-scsi-disk-emulate-GET-LBA-STATUS.patch
@@ -0,0 +1,329 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dirk Nehring <dnehring@marcant.net>
+Date: Sun, 22 Nov 2026 19:46:50 +0100
+Subject: [PATCH] scsi-disk: emulate GET LBA STATUS
+
+scsi-hd reports thin provisioning in VPD page 0xb2 whenever
+discard_granularity is set, which it is by default (4 KiB), but it
+rejects GET LBA STATUS with INVALID FIELD IN CDB.
+
+Windows sends GET LBA STATUS before it retrims a thin-provisioned
+volume ("Optimize Drives", defrag /L), at least with 4 KiB NTFS clusters
+and the default 4 KiB unmap granularity. Current Windows Server 2022
+(build 20348.5622) then skips the retrim with "Incorrect function.
+(0x80070001)" (event 264 of the storage optimizer), so the space freed
+in the guest is not given back to the storage; the 2022 release build
+(20348.587) still went ahead. The vioscsi driver of virtio-win 0.1.302
+passes the CDB to QEMU as is.
+
+Emulate the command and report every LBA as "mapped or unknown"
+(provisioning status 0), as SBC permits. QEMU does not know the
+provisioning state of every backend, and asking the block layer from
+here could block on network storage. The guest then unmaps all the
+space it considers free, which is what a retrim is for.
+
+Windows asks with an ALLOCATION LENGTH of 0x1ffff8, above the 64 KiB
+that scsi_disk_emulate_command() accepts. Let GET LBA STATUS through
+with a 64 KiB buffer and leave the rest as residual; one descriptor
+covers 2^32 - 1 blocks, so a few hundred descriptors fit in any case.
+
+Tested with Windows Server 2022 build 20348.5622 and a 16 GiB scsi-hd
+(virtio-scsi-pci, discard=unmap) on an LVM-thin volume: after deleting
+4 GiB with delete notifications disabled, "defrag T: /L" failed with
+event 264 before and completed with event 258 after this change, and
+the thin volume went from 4140 MiB back to 46 MiB.
+
+Only a command that used to fail is added. Nothing else the guest
+sees changes, so older machine types need no compat property.
+
+Link: https://github.com/virtio-win/kvm-guest-drivers-windows/issues/1574
+Signed-off-by: Dirk Nehring <dnehring@marcant.net>
+---
+ hw/scsi/scsi-disk.c            | 100 ++++++++++++++++++++++++++++++++-
+ hw/scsi/trace-events           |   1 +
+ include/scsi/constants.h       |   1 +
+ tests/qtest/virtio-scsi-test.c |  91 +++++++++++++++++++++++++++++-
+ 4 files changed, 190 insertions(+), 3 deletions(-)
+
+diff --git a/hw/scsi/scsi-disk.c b/hw/scsi/scsi-disk.c
+index a42f7d8..605c8b4 100644
+--- a/hw/scsi/scsi-disk.c
++++ b/hw/scsi/scsi-disk.c
+@@ -1728,6 +1728,85 @@ invalid_field:
+     scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));
+ }
+ 
++/*
++ * GET LBA STATUS (SBC-4 5.6).  A guest that is told the device is thin
++ * provisioned (see VPD page 0xb2) may ask which LBAs are mapped before it
++ * reclaims space.  Windows does so for retrim ("Optimize Drives"), at least
++ * with the default discard_granularity of 4 KiB and 4 KiB NTFS clusters,
++ * and skips the retrim with "Incorrect function" if the command fails.
++ *
++ * QEMU does not know the provisioning state of every backend, and asking
++ * the block layer here could block on network storage, so every LBA is
++ * reported as "mapped or unknown", which SBC permits.  The guest then
++ * unmaps everything it considers free, as it would on any other disk.
++ *
++ * Returns the length of the parameter data, or -1 after a CHECK CONDITION
++ * has been set or when the CDB has an invalid field.
++ */
++static int scsi_disk_emulate_get_lba_status(SCSIDiskReq *r, uint8_t *outbuf)
++{
++    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);
++    uint64_t lba = r->req.cmd.lba;
++    uint32_t alloc_len = r->req.cmd.xfer;
++    uint8_t report_type = r->req.cmd.buf[14];
++    uint64_t nb_sectors;
++    uint32_t len, max_desc;
++    bool all_match;
++    uint32_t n = 0;
++
++    trace_scsi_disk_emulate_command_GET_LBA_STATUS(lba, alloc_len,
++                                                   report_type);
++
++    switch (report_type) {
++    case 0x00: /* all LBAs */
++    case 0x02: /* mapped LBAs */
++        all_match = true;
++        break;
++    case 0x01: /* LBAs with a non-zero provisioning status */
++    case 0x03: /* deallocated LBAs */
++    case 0x04: /* anchored LBAs */
++    case 0x10: /* LBAs that may return an unrecovered error */
++        all_match = false;
++        break;
++    default:
++        return -1;
++    }
++
++    blk_get_geometry(s->qdev.conf.blk, &nb_sectors);
++    nb_sectors /= s->qdev.blocksize / BDRV_SECTOR_SIZE;
++    if (!nb_sectors) {
++        scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));
++        return -1;
++    }
++    if (lba >= nb_sectors) {
++        scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));
++        return -1;
++    }
++
++    /*
++     * One descriptor covers at most 2^32 - 1 blocks.  Return as many as
++     * the allocation length and the buffer have room for, and at least one
++     * so that the PARAMETER DATA LENGTH tells a short buffer what it is
++     * missing.  r->buflen is at least 4096.
++     */
++    len = MIN(alloc_len, r->buflen);
++    max_desc = len >= 24 ? (len - 8) / 16 : 1;
++    while (all_match && lba < nb_sectors && n < max_desc) {
++        uint8_t *desc = &outbuf[8 + 16 * n];
++        uint64_t count = MIN(nb_sectors - lba, UINT32_MAX);
++
++        stq_be_p(&desc[0], lba);
++        stl_be_p(&desc[8], count);
++        desc[12] = 0; /* PROVISIONING STATUS: mapped or unknown */
++        lba += count;
++        n++;
++    }
++
++    /* PARAMETER DATA LENGTH: the bytes that follow this field */
++    stl_be_p(&outbuf[0], 4 + 16 * n);
++    return 8 + 16 * n;
++}
++
+ /* sector_num and nb_sectors expected to be in qdev blocksize */
+ static inline bool check_lba_range(SCSIDiskState *s,
+                                    uint64_t sector_num, uint32_t nb_sectors)
+@@ -2060,9 +2139,19 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
+      * as all zeros.
+      */
+     if (req->cmd.xfer > 65536) {
+-        goto illegal_request;
++        /*
++         * GET LBA STATUS returns a few descriptors at most, but Windows
++         * asks with an ALLOCATION LENGTH of almost 2 MiB.  Return the
++         * first 64 KiB, the rest is left as residual.
++         */
++        if (req->cmd.buf[0] != SERVICE_ACTION_IN_16 ||
++            (req->cmd.buf[1] & 31) != SAI_GET_LBA_STATUS) {
++            goto illegal_request;
++        }
++        r->buflen = 65536;
++    } else {
++        r->buflen = MAX(4096, req->cmd.xfer);
+     }
+-    r->buflen = MAX(4096, req->cmd.xfer);
+ 
+     if (!r->iov.iov_base) {
+         r->iov.iov_base = blk_blockalign(s->qdev.conf.blk, r->buflen);
+@@ -2230,6 +2319,13 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
+             /* Protection, exponent and lowest lba field left blank. */
+             break;
+         }
++        if ((req->cmd.buf[1] & 31) == SAI_GET_LBA_STATUS) {
++            buflen = scsi_disk_emulate_get_lba_status(r, outbuf);
++            if (buflen < 0) {
++                goto illegal_request;
++            }
++            break;
++        }
+         trace_scsi_disk_emulate_command_SAI_unsupported();
+         goto illegal_request;
+     case SYNCHRONIZE_CACHE:
+diff --git a/hw/scsi/trace-events b/hw/scsi/trace-events
+index a8ac1e7..62a606d 100644
+--- a/hw/scsi/trace-events
++++ b/hw/scsi/trace-events
+@@ -362,6 +362,7 @@ scsi_disk_emulate_read_data(int buflen) "Read buf_len=%d"
+ scsi_disk_emulate_write_data(int buflen) "Write buf_len=%d"
+ scsi_disk_emulate_command_SAI_16(void) "SAI READ CAPACITY(16)"
+ scsi_disk_emulate_command_SAI_unsupported(void) "Unsupported Service Action In"
++scsi_disk_emulate_command_GET_LBA_STATUS(uint64_t lba, uint32_t alloc_len, int report_type) "SAI GET LBA STATUS lba %" PRIu64 " alloc_len %u report_type %d"
+ scsi_disk_emulate_command_SEEK_10(uint64_t lba) "Seek(10) (sector %" PRId64 ")"
+ scsi_disk_emulate_command_MODE_SELECT(size_t xfer) "Mode Select(6) (len %zd)"
+ scsi_disk_emulate_command_MODE_SELECT_10(size_t xfer) "Mode Select(10) (len %zd)"
+diff --git a/include/scsi/constants.h b/include/scsi/constants.h
+index 717e470..3de213f 100644
+--- a/include/scsi/constants.h
++++ b/include/scsi/constants.h
+@@ -154,6 +154,7 @@
+  * SERVICE ACTION IN subcodes
+  */
+ #define SAI_READ_CAPACITY_16  0x10
++#define SAI_GET_LBA_STATUS    0x12
+ 
+ /*
+  * READ POSITION service action codes
+diff --git a/tests/qtest/virtio-scsi-test.c b/tests/qtest/virtio-scsi-test.c
+index e2350c5..14ce1b0 100644
+--- a/tests/qtest/virtio-scsi-test.c
++++ b/tests/qtest/virtio-scsi-test.c
+@@ -11,6 +11,7 @@
+ #include "qemu/osdep.h"
+ #include "libqtest-single.h"
+ #include "qemu/module.h"
++#include "qemu/bswap.h"
+ #include "scsi/constants.h"
+ #include "libqos/libqos-pc.h"
+ #include "libqos/libqos-spapr.h"
+@@ -59,9 +60,13 @@ static uint64_t qvirtio_scsi_alloc(QVirtioSCSIQueues *vs, size_t alloc_size,
+     return addr;
+ }
+ 
++/*
++ * data_in receives what the device returns (it must hold data_in_len
++ * bytes), data_out is what the driver sends.
++ */
+ static uint8_t virtio_scsi_do_command(QVirtioSCSIQueues *vs,
+                                       const uint8_t *cdb,
+-                                      const uint8_t *data_in,
++                                      uint8_t *data_in,
+                                       size_t data_in_len,
+                                       uint8_t *data_out, size_t data_out_len,
+                                       struct virtio_scsi_cmd_resp *resp_out)
+@@ -110,6 +115,9 @@ static uint8_t virtio_scsi_do_command(QVirtioSCSIQueues *vs,
+     if (resp_out) {
+         memread(resp_addr, resp_out, sizeof(*resp_out));
+     }
++    if (data_in_len) {
++        memread(data_in_addr, data_in, data_in_len);
++    }
+ 
+     guest_free(alloc, req_addr);
+     guest_free(alloc, resp_addr);
+@@ -236,6 +244,83 @@ static void test_unmap_large_lba(void *obj, void *data,
+     qvirtio_scsi_pci_free(vs);
+ }
+ 
++/*
++ * GET LBA STATUS reports every LBA as mapped or unknown.  Windows asks for
++ * it before a retrim of a thin-provisioned disk and gives up when the
++ * command is rejected.
++ */
++static void test_get_lba_status(void *obj, void *data,
++                                QGuestAllocator *t_alloc)
++{
++    QVirtioSCSI *scsi = obj;
++    QVirtioSCSIQueues *vs;
++    /* SERVICE ACTION IN(16), GET LBA STATUS, alloc length 32 */
++    uint8_t cdb[VIRTIO_SCSI_CDB_SIZE] = {
++        0x9e, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
++        0x00, 0x00, 0x00, 0x20, 0x00, 0x00
++    };
++    struct virtio_scsi_cmd_resp resp;
++    uint8_t buf[32];
++    const uint32_t big_len = 0x1ffff8;
++    g_autofree uint8_t *big = g_malloc(big_len);
++    /* null-co is 1 GiB, in 512-byte blocks */
++    const uint32_t nb_blocks = 0x200000;
++
++    alloc = t_alloc;
++    vs = qvirtio_scsi_init(scsi->vdev);
++
++    /* From LBA 0: one descriptor up to the end of the device */
++    memset(buf, 0xff, sizeof(buf));
++    virtio_scsi_do_command(vs, cdb, buf, sizeof(buf), NULL, 0, &resp);
++    g_assert_cmphex(resp.response, ==, 0);
++    g_assert_cmphex(resp.status, ==, GOOD);
++    g_assert_cmpuint(ldl_be_p(&buf[0]), ==, 4 + 16); /* parameter data len */
++    g_assert_cmpuint(ldq_be_p(&buf[8]), ==, 0);       /* LBA */
++    g_assert_cmpuint(ldl_be_p(&buf[16]), ==, nb_blocks);
++    g_assert_cmphex(buf[20] & 0xf, ==, 0);            /* mapped or unknown */
++
++    /* From a later LBA: the descriptor starts there */
++    stq_be_p(&cdb[2], 0x1000);
++    virtio_scsi_do_command(vs, cdb, buf, sizeof(buf), NULL, 0, &resp);
++    g_assert_cmphex(resp.status, ==, GOOD);
++    g_assert_cmpuint(ldq_be_p(&buf[8]), ==, 0x1000);
++    g_assert_cmpuint(ldl_be_p(&buf[16]), ==, nb_blocks - 0x1000);
++
++    /* REPORT TYPE deallocated: nothing matches */
++    cdb[14] = 0x03;
++    virtio_scsi_do_command(vs, cdb, buf, sizeof(buf), NULL, 0, &resp);
++    g_assert_cmphex(resp.status, ==, GOOD);
++    g_assert_cmpuint(ldl_be_p(&buf[0]), ==, 4);
++    cdb[14] = 0x00;
++
++    /* Past the end: LBA OUT OF RANGE */
++    stq_be_p(&cdb[2], nb_blocks);
++    virtio_scsi_do_command(vs, cdb, buf, sizeof(buf), NULL, 0, &resp);
++    g_assert_cmphex(resp.status, ==, CHECK_CONDITION);
++    g_assert_cmphex(resp.sense[2], ==, ILLEGAL_REQUEST);
++    g_assert_cmphex(resp.sense[12], ==, 0x21); /* LBA OUT OF RANGE */
++
++    /*
++     * The command Windows sends before a retrim: LBA 2048, ALLOCATION
++     * LENGTH 0x1ffff8.  Allowed although it is above the 64 KiB that
++     * other emulated commands may ask for; what is not transferred is
++     * returned as residual.
++     */
++    stq_be_p(&cdb[2], 2048);
++    stl_be_p(&cdb[10], big_len);
++    memset(big, 0xff, big_len);
++    virtio_scsi_do_command(vs, cdb, big, big_len, NULL, 0, &resp);
++    g_assert_cmphex(resp.response, ==, 0);
++    g_assert_cmphex(resp.status, ==, GOOD);
++    g_assert_cmpuint(le32_to_cpu(resp.resid), ==, big_len - 65536);
++    g_assert_cmpuint(ldl_be_p(&big[0]), ==, 4 + 16);
++    g_assert_cmpuint(ldq_be_p(&big[8]), ==, 2048);
++    g_assert_cmpuint(ldl_be_p(&big[16]), ==, nb_blocks - 2048);
++    g_assert_cmphex(big[20] & 0xf, ==, 0);
++
++    qvirtio_scsi_pci_free(vs);
++}
++
+ static void test_write_to_cdrom(void *obj, void *data,
+                                 QGuestAllocator *t_alloc)
+ {
+@@ -399,6 +484,10 @@ static void register_virtio_scsi_test(void)
+     qos_add_test("large-lba-unmap", "virtio-scsi",
+                  test_unmap_large_lba, &opts);
+ 
++    opts.before = virtio_scsi_setup;
++    qos_add_test("get-lba-status", "virtio-scsi",
++                 test_get_lba_status, &opts);
++
+     opts.before = virtio_scsi_setup_cd;
+     qos_add_test("write-to-cdrom", "virtio-scsi", test_write_to_cdrom, &opts);
+ 
diff --git a/debian/patches/series b/debian/patches/series
index bc240a0..bb2f171 100644
--- a/debian/patches/series
+++ b/debian/patches/series
@@ -5,6 +5,7 @@ extra/0004-hw-scsi-lsi53c895a-gracefully-handle-re-entrant-DMA.patch
 extra/0005-qapi-virtio-Restore-backend-features-in-x-query-virt.patch
 extra/0006-qapi-monitor-Handle-missing-vhost-user-protocol-feat.patch
 extra/0007-block-rbd-query-block-status-in-a-worker-thread.patch
+extra/0008-scsi-disk-emulate-GET-LBA-STATUS.patch
 bitmap-mirror/0001-drive-mirror-add-support-for-sync-bitmap-mode-never.patch
 bitmap-mirror/0002-drive-mirror-add-support-for-conditional-and-always-.patch
 bitmap-mirror/0003-mirror-add-check-for-bitmap-mode-without-bitmap.patch



^ permalink raw reply related	[flat|nested] only message in thread

only message in thread, other threads:[~2026-11-24 17:33 UTC | newest]

Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-24 17:29 [PATCH qemu] fix windows retrim on scsi-hd: emulate GET LBA STATUS Dirk Nehring

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal