Skip to contentSkip to conversation

block: BLOCK_IO_DELAY event

PATCH Superseded Hanna Czenczek 6 participants 47 messages Aug 31 – Sep 24 Block layer

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover block: BLOCK_IO_DELAY event

Based-on: <[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this (which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

(PS: The nice thing about throwing an alert while the request is still going on would be that it could allow us to also stop the VM in case of excessive latency, before the request completes, so the guest would be shielded from such excessive latency. This might be useful for Windows guests that just have a maximum request lantency before throwing a BSOD.)

Hanna Czenczek (9):
block/accounting: Add offset to BlockAcctCookie qapi/block: Add IoAccountingOperation enum qapi/block: Add BLOCK_IO_DELAY event
block-backend: Public blk_get_attached_dev_path() block/accounting: Add BB field to latency checker block/accounting: Emit BLOCK_IO_DELAY event
block: Add delay-alert-ms property block/accounting: Move latency_ns override down
iotests: Add delay-alert test

 qapi/block.json                          |  52 +++++++++
 include/block/accounting.h               |  20 +++-
 include/hw/block/block.h                 |   5 +-
 include/system/block-backend-io.h        |   9 ++
 include/system/dma.h                     |   2 +-
 block/accounting.c                       |  60 ++++++++--
 block/block-backend.c                    |   8 +-
 blockdev.c                               |  16 ++-
 hw/block/block.c                         |   4 +-
 hw/block/dataplane/xen-block.c           |   4 +-
 hw/block/virtio-blk.c                    |  15 +--
 hw/ide/ahci.c                            |   6 +-
 hw/ide/atapi.c                           |   9 +-
 hw/ide/core.c                            |   9 +-
 hw/ide/macio.c                           |  15 ++-
 hw/nvme/ctrl.c                           |  43 ++++---
 hw/nvme/dif.c                            |   8 +-
 hw/scsi/scsi-disk.c                      |  28 +++--
 qemu-io-cmds.c                           |  14 +--
 system/dma-helpers.c                     |   4 +-
 tests/unit/test-block-accounting.c       |   2 +-
 tests/qemu-iotests/172.out               |  38 +++++++
 tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
 tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
 24 files changed, 472 insertions(+), 81 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/delay-alert
 create mode 100644 tests/qemu-iotests/tests/delay-alert.out
Signature · 1 line
2.55.0
#1 lore raw

PATCH 1/9 block/accounting: Add offset to BlockAcctCookie

For latency alerts, we will want to generate QMP events from block accounting cookies. These should contain some minimal information about the offending request, i.e., start offset, size, and type. The latter two are already part of the cookie, the former is not. Add it.

---
 include/block/accounting.h         |  7 ++++-
 include/system/dma.h               |  2 +-
 block/accounting.c                 |  3 ++-
 hw/block/dataplane/xen-block.c     |  4 +--
 hw/block/virtio-blk.c              | 15 ++++++-----
 hw/ide/ahci.c                      |  6 +++--
 hw/ide/atapi.c                     |  9 ++++---
 hw/ide/core.c                      |  9 +++++--
 hw/ide/macio.c                     | 15 ++++++++---
 hw/nvme/ctrl.c                     | 43 +++++++++++++++++-------------
 hw/nvme/dif.c                      |  8 +++---
 hw/scsi/scsi-disk.c                | 28 ++++++++++++-------
 qemu-io-cmds.c                     | 14 +++++-----
 system/dma-helpers.c               |  4 +--
 tests/unit/test-block-accounting.c |  2 +-
 15 files changed, 105 insertions(+), 64 deletions(-)
include/block/accounting.h +6 -1
index 12d32460927..9386440ec89 100644
@@ -95,6 +95,7 @@ struct BlockAcctStats {
 };
 
 typedef struct BlockAcctCookie {
+    int64_t offset;
     int64_t bytes;
     int64_t start_time_ns;
     enum BlockAcctType type;
@@ -108,8 +109,12 @@ void block_acct_cleanup(BlockAcctStats *stats);
 void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
 BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
                                               BlockAcctTimedStats *s);
+/**
+ * Begin an I/O operation.
+ * @offset == -1 indicates an unknown offset (e.g. for meta operations).
+ */
 void block_acct_start(BlockAcctStats *stats, BlockAcctCookie *cookie,
-                      int64_t bytes, enum BlockAcctType type);
+                      int64_t offset, int64_t bytes, enum BlockAcctType type);
 void block_acct_done(BlockAcctStats *stats, BlockAcctCookie *cookie);
 void block_acct_failed(BlockAcctStats *stats, BlockAcctCookie *cookie);
 void block_acct_invalid(BlockAcctStats *stats, enum BlockAcctType type);
include/system/dma.h +1 -1
index 82e7ad54374..1291697642e 100644
@@ -305,7 +305,7 @@ MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
                           QEMUSGList *sg, MemTxAttrs attrs);
 
 void dma_acct_start(BlockBackend *blk, BlockAcctCookie *cookie,
-                    QEMUSGList *sg, enum BlockAcctType type);
+                    QEMUSGList *sg, int64_t offset, enum BlockAcctType type);
 
 /**
  * dma_aligned_pow2_mask: Return the address bit mask of the largest
block/accounting.c +2 -1
index 038af370170..66e5001403f 100644
@@ -115,10 +115,11 @@ BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
 }
 
 void block_acct_start(BlockAcctStats *stats, BlockAcctCookie *cookie,
-                      int64_t bytes, enum BlockAcctType type)
+                      int64_t offset, int64_t bytes, enum BlockAcctType type)
 {
     assert(type < BLOCK_MAX_IOTYPE);
 
+    cookie->offset = offset;
     cookie->bytes = bytes;
     cookie->start_time_ns = qemu_clock_get_ns(clock_type);
     cookie->type = type;
hw/block/dataplane/xen-block.c +2 -2
index 48c2e315f31..f4dab9b2510 100644
@@ -373,7 +373,7 @@ static int xen_block_do_aio(XenBlockRequest *request)
     case BLKIF_OP_READ:
         qemu_iovec_add(&request->v, request->buf, request->size);
         block_acct_start(blk_get_stats(dataplane->blk), &request->acct,
-                         request->v.size, BLOCK_ACCT_READ);
+                         request->start, request->v.size, BLOCK_ACCT_READ);
         request->aio_inflight++;
         blk_aio_preadv(dataplane->blk, request->start, &request->v, 0,
                        xen_block_complete_aio, request);
@@ -386,7 +386,7 @@ static int xen_block_do_aio(XenBlockRequest *request)
 
         qemu_iovec_add(&request->v, request->buf, request->size);
         block_acct_start(blk_get_stats(dataplane->blk), &request->acct,
-                         request->v.size,
+                         request->start, request->v.size,
                          request->req.operation == BLKIF_OP_WRITE ?
                          BLOCK_ACCT_WRITE : BLOCK_ACCT_FLUSH);
         request->aio_inflight++;
hw/block/virtio-blk.c +8 -7
index 384a5ee3f1c..d2605814795 100644
@@ -338,7 +338,7 @@ static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
 {
     VirtIOBlock *s = req->dev;
 
-    block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
+    block_acct_start(blk_get_stats(s->blk), &req->acct, -1, 0,
                      BLOCK_ACCT_FLUSH);
 
     /*
@@ -421,8 +421,8 @@ static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
             blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
-                         BLOCK_ACCT_WRITE);
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         sector << BDRV_SECTOR_BITS, bytes, BLOCK_ACCT_WRITE);
 
         blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
                               bytes, blk_aio_flags,
@@ -437,8 +437,8 @@ static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
             goto err;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
-                         BLOCK_ACCT_UNMAP);
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         sector << BDRV_SECTOR_BITS, bytes, BLOCK_ACCT_UNMAP);
 
         blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
                          virtio_blk_discard_write_zeroes_complete, req);
@@ -813,7 +813,7 @@ static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
     data->zone_append_data.offset = offset;
     qemu_iovec_init_external(&req->qiov, out_iov, out_num);
 
-    block_acct_start(blk_get_stats(s->blk), &req->acct, len,
+    block_acct_start(blk_get_stats(s->blk), &req->acct, offset, len,
                      BLOCK_ACCT_ZONE_APPEND);
 
     blk_aio_zone_append(s->blk, &data->zone_append_data.offset, &req->qiov, 0,
@@ -893,7 +893,8 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
             return 0;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         req->sector_num * BDRV_SECTOR_SIZE, req->qiov.size,
                          is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
 
         /* merge would exceed maximum number of requests or IO direction
hw/ide/ahci.c +4 -2
index 6b04762c4ad..cf63c87a013 100644
@@ -1092,7 +1092,8 @@ static void execute_ncq_command(NCQTransferState *ncq_tfs)
         trace_execute_ncq_command_read(ad->hba, port, ncq_tfs->tag,
                                        ncq_tfs->sector_count, ncq_tfs->lba);
         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
-                       &ncq_tfs->sglist, BLOCK_ACCT_READ);
+                       &ncq_tfs->sglist, ncq_tfs->lba << BDRV_SECTOR_BITS,
+                       BLOCK_ACCT_READ);
         ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
                                       ncq_tfs->lba << BDRV_SECTOR_BITS,
                                       BDRV_SECTOR_SIZE,
@@ -1102,7 +1103,8 @@ static void execute_ncq_command(NCQTransferState *ncq_tfs)
         trace_execute_ncq_command_write(ad->hba, port, ncq_tfs->tag,
                                         ncq_tfs->sector_count, ncq_tfs->lba);
         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
-                       &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
+                       &ncq_tfs->sglist, ncq_tfs->lba << BDRV_SECTOR_BITS,
+                       BLOCK_ACCT_WRITE);
         ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
                                        ncq_tfs->lba << BDRV_SECTOR_BITS,
                                        BDRV_SECTOR_SIZE,
hw/ide/atapi.c +6 -3
index 0ea149ad8c6..6f1187bce12 100644
@@ -163,6 +163,7 @@ static int cd_read_sector(IDEState *s)
     trace_cd_read_sector(s->lba);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     (int64_t)s->lba << ATAPI_SECTOR_BITS,
                      nsec * ATAPI_SECTOR_SIZE, BLOCK_ACCT_READ);
 
     ide_buffered_readv(s, (int64_t)s->lba << 2, &s->qiov, nsec * 4,
@@ -297,7 +298,8 @@ static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
     s->elementary_transfer_size = 0;
 
     if (s->atapi_dma) {
-        block_acct_start(blk_get_stats(s->blk), &s->acct, size,
+        /* No offset available for these commands */
+        block_acct_start(blk_get_stats(s->blk), &s->acct, -1, size,
                          BLOCK_ACCT_READ);
         s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
         ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
@@ -419,8 +421,9 @@ static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
     s->io_buffer_size = 0;
     s->cd_sector_size = sector_size;
 
-    block_acct_start(blk_get_stats(s->blk), &s->acct, s->packet_transfer_size,
-                     BLOCK_ACCT_READ);
+    block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     (int64_t)lba << ATAPI_SECTOR_BITS,
+                     s->packet_transfer_size, BLOCK_ACCT_READ);
 
     /* XXX: check if BUSY_STAT should be set */
     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
hw/ide/core.c +7 -2
index 06e6bb6067d..4b559cf68d0 100644
@@ -491,6 +491,7 @@ static void coroutine_fn ide_trim_co_entry(void *opaque)
             }
 
             block_acct_start(blk_get_stats(s->blk), &s->acct,
+                             sector << BDRV_SECTOR_BITS,
                              count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
 
             /* Got an entry! Submit and exit.  */
@@ -833,6 +834,7 @@ static void ide_sector_read(IDEState *s)
     qemu_iovec_init_buf(&s->qiov, s->io_buffer, n * BDRV_SECTOR_SIZE);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     sector_num << BDRV_SECTOR_BITS,
                      n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
     s->pio_aiocb = ide_buffered_readv(s, sector_num, &s->qiov, n,
                                       ide_sector_read_cb, s);
@@ -1009,10 +1011,12 @@ static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd)
     switch (dma_cmd) {
     case IDE_DMA_READ:
         block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS,
                          s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
         break;
     case IDE_DMA_WRITE:
         block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS,
                          s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
         break;
     default:
@@ -1112,7 +1116,8 @@ static void ide_sector_write(IDEState *s)
     qemu_iovec_init_buf(&s->qiov, s->io_buffer, n * BDRV_SECTOR_SIZE);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
-                     n * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
+                     sector_num << BDRV_SECTOR_BITS, n * BDRV_SECTOR_SIZE,
+                     BLOCK_ACCT_WRITE);
     s->pio_aiocb = blk_aio_pwritev(s->blk, sector_num << BDRV_SECTOR_BITS,
                                    &s->qiov, 0, ide_sector_write_cb, s);
 }
@@ -1147,7 +1152,7 @@ static void ide_flush_cache(IDEState *s)
 
     s->status |= BUSY_STAT;
     ide_set_retry(s);
-    block_acct_start(blk_get_stats(s->blk), &s->acct, 0, BLOCK_ACCT_FLUSH);
+    block_acct_start(blk_get_stats(s->blk), &s->acct, -1, 0, BLOCK_ACCT_FLUSH);
     s->pio_aiocb = blk_aio_flush(s->blk, ide_flush_cb, s);
 }
 
hw/ide/macio.c +12 -3
index 40fb4f3b4f3..99d079be916 100644
@@ -218,7 +218,14 @@ static void pmac_ide_transfer(DBDMA_io *io)
     MACIO_DPRINTF("\n");
 
     if (s->drive_kind == IDE_CD) {
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        int64_t offset = -1;
+
+        if (s->lba >= 0) {
+            /* Same hardcoded 11 as in pmac_ide_atapi_transfer_cb() */
+            offset = ((int64_t)s->lba << 11) + s->io_buffer_index;
+        }
+
+        block_acct_start(blk_get_stats(s->blk), &s->acct, offset, io->len,
                          BLOCK_ACCT_READ);
 
         pmac_ide_atapi_transfer_cb(io, 0);
@@ -227,11 +234,13 @@ static void pmac_ide_transfer(DBDMA_io *io)
 
     switch (s->dma_cmd) {
     case IDE_DMA_READ:
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS, io->len,
                          BLOCK_ACCT_READ);
         break;
     case IDE_DMA_WRITE:
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS, io->len,
                          BLOCK_ACCT_WRITE);
         break;
     default:
hw/nvme/ctrl.c +25 -18

117 lines not on this page · raw message

hw/nvme/dif.c +4 -4
index 4e7874f3223..fbd4d8eb816 100644
@@ -644,8 +644,8 @@ uint16_t nvme_dif_rw(NvmeCtrl *n, NvmeRequest *req)
     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
 
     if (req->cmd.opcode == NVME_CMD_READ) {
-        block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
-                         BLOCK_ACCT_READ);
+        block_acct_start(blk_get_stats(blk), &req->acct, offset,
+                         ctx->data.iov.size, BLOCK_ACCT_READ);
 
         req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
                                     nvme_dif_rw_mdata_in_cb, ctx);
@@ -690,8 +690,8 @@ uint16_t nvme_dif_rw(NvmeCtrl *n, NvmeRequest *req)
         }
     }
 
-    block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
-                     BLOCK_ACCT_WRITE);
+    block_acct_start(blk_get_stats(blk), &req->acct, offset,
+                     ctx->data.iov.size, BLOCK_ACCT_WRITE);
 
     req->aiocb = blk_aio_pwritev(ns->blkconf.blk, offset, &ctx->data.iov, 0,
                                  nvme_dif_rw_mdata_out_cb, ctx);
hw/scsi/scsi-disk.c +18 -10
index 24bd1a78b6e..5b40e404e13 100644
@@ -484,7 +484,8 @@ static void scsi_do_read(SCSIDiskReq *r, int ret)
     scsi_req_ref(&r->req);
 
     if (r->req.sg) {
-        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_READ);
+        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg,
+                       r->sector << BDRV_SECTOR_BITS, BLOCK_ACCT_READ);
         r->req.residual -= r->req.sg->size;
         r->req.aiocb = dma_blk_io(r->req.sg, r->sector << BDRV_SECTOR_BITS,
                                   BDRV_SECTOR_SIZE,
@@ -493,7 +494,8 @@ static void scsi_do_read(SCSIDiskReq *r, int ret)
     } else {
         scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         r->qiov.size, BLOCK_ACCT_READ);
+                         r->sector << BDRV_SECTOR_BITS, r->qiov.size,
+                         BLOCK_ACCT_READ);
         r->req.aiocb = sdc->dma_readv(r->sector << BDRV_SECTOR_BITS, &r->qiov,
                                       scsi_read_complete, r, r);
     }
@@ -551,7 +553,7 @@ static void scsi_read_data(SCSIRequest *req)
     first = !r->started;
     r->started = true;
     if (first && r->need_fua) {
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_do_read_cb, r);
     } else {
@@ -634,7 +636,7 @@ static void scsi_write_data(SCSIRequest *req)
 
     if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
         r->req.cmd.buf[0] == VERIFY_16) {
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         cb = r->req.sg ? scsi_dma_complete : scsi_write_complete;
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, cb, r);
@@ -642,7 +644,8 @@ static void scsi_write_data(SCSIRequest *req)
     }
 
     if (r->req.sg) {
-        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_WRITE);
+        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg,
+                       r->sector << BDRV_SECTOR_BITS, BLOCK_ACCT_WRITE);
         r->req.residual -= r->req.sg->size;
         r->req.aiocb = dma_blk_io(r->req.sg, r->sector << BDRV_SECTOR_BITS,
                                   BDRV_SECTOR_SIZE,
@@ -650,7 +653,8 @@ static void scsi_write_data(SCSIRequest *req)
                                   DMA_DIRECTION_TO_DEVICE);
     } else {
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         r->qiov.size, BLOCK_ACCT_WRITE);
+                         r->sector << BDRV_SECTOR_BITS, r->qiov.size,
+                         BLOCK_ACCT_WRITE);
         r->req.aiocb = sdc->dma_writev(r->sector << BDRV_SECTOR_BITS, &r->qiov,
                                        scsi_write_complete, r, r);
     }
@@ -1710,7 +1714,7 @@ static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
     if (!blk_enable_write_cache(s->qdev.conf.blk)) {
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r);
         return;
@@ -1777,6 +1781,7 @@ static void scsi_unmap_complete_noio(UnmapCBData *data, int ret)
         }
 
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
+                         r->sector * BDRV_SECTOR_SIZE,
                          r->sector_count * BDRV_SECTOR_SIZE,
                          BLOCK_ACCT_UNMAP);
 
@@ -1894,7 +1899,8 @@ static void scsi_write_same_complete(void *opaque, int ret)
                             data->iov.iov_len);
     if (data->iov.iov_len) {
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         data->iov.iov_len, BLOCK_ACCT_WRITE);
+                         data->sector << BDRV_SECTOR_BITS, data->iov.iov_len,
+                         BLOCK_ACCT_WRITE);
         /* Reinitialize qiov, to handle unaligned WRITE SAME request
          * where final qiov may need smaller size */
         qemu_iovec_init_external(&data->qiov, &data->iov, 1);
@@ -1943,6 +1949,7 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf)
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
+                         r->req.cmd.lba * s->qdev.blocksize,
                          nb_sectors * s->qdev.blocksize,
                         BLOCK_ACCT_WRITE);
         r->req.aiocb = blk_aio_pwrite_zeroes(s->qdev.conf.blk,
@@ -1969,7 +1976,8 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf)
 
     scsi_req_ref(&r->req);
     block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                     data->iov.iov_len, BLOCK_ACCT_WRITE);
+                     data->sector << BDRV_SECTOR_BITS, data->iov.iov_len,
+                     BLOCK_ACCT_WRITE);
     r->req.aiocb = blk_aio_pwritev(s->qdev.conf.blk,
                                    data->sector << BDRV_SECTOR_BITS,
                                    &data->qiov, 0,
@@ -2237,7 +2245,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     case SYNCHRONIZE_CACHE:
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r);
         return 0;
qemu-io-cmds.c +7 -7
index de4c1966fea..655dfae9057 100644
@@ -1538,8 +1538,8 @@ static int aio_read_f(BlockBackend *blk, int argc, char **argv)
     }
 
     clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
-    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                     BLOCK_ACCT_READ);
+    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                     ctx->qiov.size, BLOCK_ACCT_READ);
     blk_aio_preadv(blk, ctx->offset, &ctx->qiov, ctx->flags, aio_read_done,
                    ctx);
     return 0;
@@ -1693,8 +1693,8 @@ static int aio_write_f(BlockBackend *blk, int argc, char **argv)
         }
 
         clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
-        block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                         BLOCK_ACCT_WRITE);
+        block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                         ctx->qiov.size, BLOCK_ACCT_WRITE);
 
         blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, ctx->flags,
                         aio_write_done, ctx);
@@ -1706,7 +1706,7 @@ static int aio_write_f(BlockBackend *blk, int argc, char **argv)
 static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
 {
     BlockAcctCookie cookie;
-    block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
+    block_acct_start(blk_get_stats(blk), &cookie, -1, 0, BLOCK_ACCT_FLUSH);
     blk_drain_all();
     block_acct_done(blk_get_stats(blk), &cookie);
     return 0;
@@ -2325,8 +2325,8 @@ static int aio_discard_f(BlockBackend *blk, int argc, char **argv)
 
     clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
     ctx->qiov.size = count;
-    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                     BLOCK_ACCT_UNMAP);
+    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                     ctx->qiov.size, BLOCK_ACCT_UNMAP);
     blk_aio_pdiscard(blk, ctx->offset, count, aio_discard_done, ctx);
 
     return 0;
system/dma-helpers.c +2 -2
index 0d592f64680..7bf41119ebc 100644
@@ -315,9 +315,9 @@ MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
 }
 
 void dma_acct_start(BlockBackend *blk, BlockAcctCookie *cookie,
-                    QEMUSGList *sg, enum BlockAcctType type)
+                    QEMUSGList *sg, int64_t offset, enum BlockAcctType type)
 {
-    block_acct_start(blk_get_stats(blk), cookie, sg->size, type);
+    block_acct_start(blk_get_stats(blk), cookie, offset, sg->size, type);
 }
 
 uint64_t dma_aligned_pow2_mask(uint64_t start, uint64_t end, int max_addr_bits)
tests/unit/test-block-accounting.c +1 -1
index 7aae491cfc2..0081502891c 100644
@@ -63,7 +63,7 @@ static void *reader_thread(void *opaque)
     while (!qatomic_read(&stop_workers)) {
         BlockAcctCookie cookie;
 
-        block_acct_start(stats, &cookie, 4096, BLOCK_ACCT_READ);
+        block_acct_start(stats, &cookie, -1, 4096, BLOCK_ACCT_READ);
         block_acct_done(stats, &cookie);
     }
 
Signature · 1 line
2.55.0
Acked-by on v1 1/9
#2 lore raw

Re: [PATCH 1/9] block/accounting: Add offset to BlockAcctCookie

Quoted 657 lines · Hanna Czenczek

For latency alerts, we will want to generate QMP events from block accounting cookies. These should contain some minimal information about the offending request, i.e., start offset, size, and type. The latter two are already part of the cookie, the former is not. Add it.

---
 include/block/accounting.h         |  7 ++++-
 include/system/dma.h               |  2 +-
 block/accounting.c                 |  3 ++-
 hw/block/dataplane/xen-block.c     |  4 +--
 hw/block/virtio-blk.c              | 15 ++++++-----
 hw/ide/ahci.c                      |  6 +++--
 hw/ide/atapi.c                     |  9 ++++---
 hw/ide/core.c                      |  9 +++++--
 hw/ide/macio.c                     | 15 ++++++++---
 hw/nvme/ctrl.c                     | 43 +++++++++++++++++-------------
 hw/nvme/dif.c                      |  8 +++---
 hw/scsi/scsi-disk.c                | 28 ++++++++++++-------
 qemu-io-cmds.c                     | 14 +++++-----
 system/dma-helpers.c               |  4 +--
 tests/unit/test-block-accounting.c |  2 +-
 15 files changed, 105 insertions(+), 64 deletions(-)
include/block/accounting.h +6 -1
index 12d32460927..9386440ec89 100644
@@ -95,6 +95,7 @@ struct BlockAcctStats {
 };
 
 typedef struct BlockAcctCookie {
+    int64_t offset;
     int64_t bytes;
     int64_t start_time_ns;
     enum BlockAcctType type;
@@ -108,8 +109,12 @@ void block_acct_cleanup(BlockAcctStats *stats);
 void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
 BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
                                               BlockAcctTimedStats *s);
+/**
+ * Begin an I/O operation.
+ * @offset == -1 indicates an unknown offset (e.g. for meta operations).
+ */
 void block_acct_start(BlockAcctStats *stats, BlockAcctCookie *cookie,
-                      int64_t bytes, enum BlockAcctType type);
+                      int64_t offset, int64_t bytes, enum BlockAcctType type);
 void block_acct_done(BlockAcctStats *stats, BlockAcctCookie *cookie);
 void block_acct_failed(BlockAcctStats *stats, BlockAcctCookie *cookie);
 void block_acct_invalid(BlockAcctStats *stats, enum BlockAcctType type);
include/system/dma.h +1 -1
index 82e7ad54374..1291697642e 100644
@@ -305,7 +305,7 @@ MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
                           QEMUSGList *sg, MemTxAttrs attrs);
 
 void dma_acct_start(BlockBackend *blk, BlockAcctCookie *cookie,
-                    QEMUSGList *sg, enum BlockAcctType type);
+                    QEMUSGList *sg, int64_t offset, enum BlockAcctType type);
 
 /**
  * dma_aligned_pow2_mask: Return the address bit mask of the largest
block/accounting.c +2 -1
index 038af370170..66e5001403f 100644
@@ -115,10 +115,11 @@ BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
 }
 
 void block_acct_start(BlockAcctStats *stats, BlockAcctCookie *cookie,
-                      int64_t bytes, enum BlockAcctType type)
+                      int64_t offset, int64_t bytes, enum BlockAcctType type)
 {
     assert(type < BLOCK_MAX_IOTYPE);
 
+    cookie->offset = offset;
     cookie->bytes = bytes;
     cookie->start_time_ns = qemu_clock_get_ns(clock_type);
     cookie->type = type;
hw/block/dataplane/xen-block.c +2 -2
index 48c2e315f31..f4dab9b2510 100644
@@ -373,7 +373,7 @@ static int xen_block_do_aio(XenBlockRequest *request)
     case BLKIF_OP_READ:
         qemu_iovec_add(&request->v, request->buf, request->size);
         block_acct_start(blk_get_stats(dataplane->blk), &request->acct,
-                         request->v.size, BLOCK_ACCT_READ);
+                         request->start, request->v.size, BLOCK_ACCT_READ);
         request->aio_inflight++;
         blk_aio_preadv(dataplane->blk, request->start, &request->v, 0,
                        xen_block_complete_aio, request);
@@ -386,7 +386,7 @@ static int xen_block_do_aio(XenBlockRequest *request)
 
         qemu_iovec_add(&request->v, request->buf, request->size);
         block_acct_start(blk_get_stats(dataplane->blk), &request->acct,
-                         request->v.size,
+                         request->start, request->v.size,
                          request->req.operation == BLKIF_OP_WRITE ?
                          BLOCK_ACCT_WRITE : BLOCK_ACCT_FLUSH);
         request->aio_inflight++;
hw/block/virtio-blk.c +8 -7
index 384a5ee3f1c..d2605814795 100644
@@ -338,7 +338,7 @@ static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
 {
     VirtIOBlock *s = req->dev;
 
-    block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
+    block_acct_start(blk_get_stats(s->blk), &req->acct, -1, 0,
                      BLOCK_ACCT_FLUSH);
 
     /*
@@ -421,8 +421,8 @@ static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
             blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
-                         BLOCK_ACCT_WRITE);
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         sector << BDRV_SECTOR_BITS, bytes, BLOCK_ACCT_WRITE);
 
         blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
                               bytes, blk_aio_flags,
@@ -437,8 +437,8 @@ static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
             goto err;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
-                         BLOCK_ACCT_UNMAP);
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         sector << BDRV_SECTOR_BITS, bytes, BLOCK_ACCT_UNMAP);
 
         blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
                          virtio_blk_discard_write_zeroes_complete, req);
@@ -813,7 +813,7 @@ static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
     data->zone_append_data.offset = offset;
     qemu_iovec_init_external(&req->qiov, out_iov, out_num);
 
-    block_acct_start(blk_get_stats(s->blk), &req->acct, len,
+    block_acct_start(blk_get_stats(s->blk), &req->acct, offset, len,
                      BLOCK_ACCT_ZONE_APPEND);
 
     blk_aio_zone_append(s->blk, &data->zone_append_data.offset, &req->qiov, 0,
@@ -893,7 +893,8 @@ static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
             return 0;
         }
 
-        block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
+        block_acct_start(blk_get_stats(s->blk), &req->acct,
+                         req->sector_num * BDRV_SECTOR_SIZE, req->qiov.size,
                          is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
 
         /* merge would exceed maximum number of requests or IO direction
hw/ide/ahci.c +4 -2
index 6b04762c4ad..cf63c87a013 100644
@@ -1092,7 +1092,8 @@ static void execute_ncq_command(NCQTransferState *ncq_tfs)
         trace_execute_ncq_command_read(ad->hba, port, ncq_tfs->tag,
                                        ncq_tfs->sector_count, ncq_tfs->lba);
         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
-                       &ncq_tfs->sglist, BLOCK_ACCT_READ);
+                       &ncq_tfs->sglist, ncq_tfs->lba << BDRV_SECTOR_BITS,
+                       BLOCK_ACCT_READ);
         ncq_tfs->aiocb = dma_blk_read(ide_state->blk, &ncq_tfs->sglist,
                                       ncq_tfs->lba << BDRV_SECTOR_BITS,
                                       BDRV_SECTOR_SIZE,
@@ -1102,7 +1103,8 @@ static void execute_ncq_command(NCQTransferState *ncq_tfs)
         trace_execute_ncq_command_write(ad->hba, port, ncq_tfs->tag,
                                         ncq_tfs->sector_count, ncq_tfs->lba);
         dma_acct_start(ide_state->blk, &ncq_tfs->acct,
-                       &ncq_tfs->sglist, BLOCK_ACCT_WRITE);
+                       &ncq_tfs->sglist, ncq_tfs->lba << BDRV_SECTOR_BITS,
+                       BLOCK_ACCT_WRITE);
         ncq_tfs->aiocb = dma_blk_write(ide_state->blk, &ncq_tfs->sglist,
                                        ncq_tfs->lba << BDRV_SECTOR_BITS,
                                        BDRV_SECTOR_SIZE,
hw/ide/atapi.c +6 -3
index 0ea149ad8c6..6f1187bce12 100644
@@ -163,6 +163,7 @@ static int cd_read_sector(IDEState *s)
     trace_cd_read_sector(s->lba);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     (int64_t)s->lba << ATAPI_SECTOR_BITS,
                      nsec * ATAPI_SECTOR_SIZE, BLOCK_ACCT_READ);
 
     ide_buffered_readv(s, (int64_t)s->lba << 2, &s->qiov, nsec * 4,
@@ -297,7 +298,8 @@ static void ide_atapi_cmd_reply(IDEState *s, int size, int max_size)
     s->elementary_transfer_size = 0;
 
     if (s->atapi_dma) {
-        block_acct_start(blk_get_stats(s->blk), &s->acct, size,
+        /* No offset available for these commands */
+        block_acct_start(blk_get_stats(s->blk), &s->acct, -1, size,
                          BLOCK_ACCT_READ);
         s->status = READY_STAT | SEEK_STAT | DRQ_STAT;
         ide_start_dma(s, ide_atapi_cmd_read_dma_cb);
@@ -419,8 +421,9 @@ static void ide_atapi_cmd_read_dma(IDEState *s, int lba, int nb_sectors,
     s->io_buffer_size = 0;
     s->cd_sector_size = sector_size;
 
-    block_acct_start(blk_get_stats(s->blk), &s->acct, s->packet_transfer_size,
-                     BLOCK_ACCT_READ);
+    block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     (int64_t)lba << ATAPI_SECTOR_BITS,
+                     s->packet_transfer_size, BLOCK_ACCT_READ);
 
     /* XXX: check if BUSY_STAT should be set */
     s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;
hw/ide/core.c +7 -2
index 06e6bb6067d..4b559cf68d0 100644
@@ -491,6 +491,7 @@ static void coroutine_fn ide_trim_co_entry(void *opaque)
             }
 
             block_acct_start(blk_get_stats(s->blk), &s->acct,
+                             sector << BDRV_SECTOR_BITS,
                              count << BDRV_SECTOR_BITS, BLOCK_ACCT_UNMAP);
 
             /* Got an entry! Submit and exit.  */
@@ -833,6 +834,7 @@ static void ide_sector_read(IDEState *s)
     qemu_iovec_init_buf(&s->qiov, s->io_buffer, n * BDRV_SECTOR_SIZE);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
+                     sector_num << BDRV_SECTOR_BITS,
                      n * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
     s->pio_aiocb = ide_buffered_readv(s, sector_num, &s->qiov, n,
                                       ide_sector_read_cb, s);
@@ -1009,10 +1011,12 @@ static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd)
     switch (dma_cmd) {
     case IDE_DMA_READ:
         block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS,
                          s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);
         break;
     case IDE_DMA_WRITE:
         block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS,
                          s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
         break;
     default:
@@ -1112,7 +1116,8 @@ static void ide_sector_write(IDEState *s)
     qemu_iovec_init_buf(&s->qiov, s->io_buffer, n * BDRV_SECTOR_SIZE);
 
     block_acct_start(blk_get_stats(s->blk), &s->acct,
-                     n * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);
+                     sector_num << BDRV_SECTOR_BITS, n * BDRV_SECTOR_SIZE,
+                     BLOCK_ACCT_WRITE);
     s->pio_aiocb = blk_aio_pwritev(s->blk, sector_num << BDRV_SECTOR_BITS,
                                    &s->qiov, 0, ide_sector_write_cb, s);
 }
@@ -1147,7 +1152,7 @@ static void ide_flush_cache(IDEState *s)
 
     s->status |= BUSY_STAT;
     ide_set_retry(s);
-    block_acct_start(blk_get_stats(s->blk), &s->acct, 0, BLOCK_ACCT_FLUSH);
+    block_acct_start(blk_get_stats(s->blk), &s->acct, -1, 0, BLOCK_ACCT_FLUSH);
     s->pio_aiocb = blk_aio_flush(s->blk, ide_flush_cb, s);
 }
 
hw/ide/macio.c +12 -3
index 40fb4f3b4f3..99d079be916 100644
@@ -218,7 +218,14 @@ static void pmac_ide_transfer(DBDMA_io *io)
     MACIO_DPRINTF("\n");
 
     if (s->drive_kind == IDE_CD) {
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        int64_t offset = -1;
+
+        if (s->lba >= 0) {
+            /* Same hardcoded 11 as in pmac_ide_atapi_transfer_cb() */
+            offset = ((int64_t)s->lba << 11) + s->io_buffer_index;
+        }
+
+        block_acct_start(blk_get_stats(s->blk), &s->acct, offset, io->len,
                          BLOCK_ACCT_READ);
 
         pmac_ide_atapi_transfer_cb(io, 0);
@@ -227,11 +234,13 @@ static void pmac_ide_transfer(DBDMA_io *io)
 
     switch (s->dma_cmd) {
     case IDE_DMA_READ:
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS, io->len,
                          BLOCK_ACCT_READ);
         break;
     case IDE_DMA_WRITE:
-        block_acct_start(blk_get_stats(s->blk), &s->acct, io->len,
+        block_acct_start(blk_get_stats(s->blk), &s->acct,
+                         ide_get_sector(s) << BDRV_SECTOR_BITS, io->len,
                          BLOCK_ACCT_WRITE);
         break;
     default:
hw/nvme/ctrl.c +25 -18
index 5168551e115..980816a2145 100644
@@ -2754,7 +2754,7 @@ static uint16_t nvme_verify(NvmeCtrl *n, NvmeRequest *req)
     qemu_iovec_init(&ctx->data.iov, 1);
     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
 
-    block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
+    block_acct_start(blk_get_stats(blk), &req->acct, offset, ctx->data.iov.size,
                      BLOCK_ACCT_READ);
 
     req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
@@ -2983,6 +2983,7 @@ static void nvme_copy_out_cb(void *opaque, int ret)
     uint32_t nlb;
     size_t mlen;
     uint8_t *mbounce;
+    int64_t offset;
 
     if (ret < 0 || iocb->ret < 0) {
         block_acct_failed(stats, &iocb->acct.write);
@@ -3003,10 +3004,10 @@ static void nvme_copy_out_cb(void *opaque, int ret)
     qemu_iovec_reset(&iocb->iov);
     qemu_iovec_add(&iocb->iov, mbounce, mlen);
 
-    block_acct_start(stats, &iocb->acct.write, mlen, BLOCK_ACCT_WRITE);
-    iocb->aiocb = blk_aio_pwritev(dns->blkconf.blk, nvme_moff(dns, iocb->slba),
-                                  &iocb->iov, 0, nvme_copy_out_completed_cb,
-                                  iocb);
+    offset = nvme_moff(dns, iocb->slba);
+    block_acct_start(stats, &iocb->acct.write, offset, mlen, BLOCK_ACCT_WRITE);
+    iocb->aiocb = blk_aio_pwritev(dns->blkconf.blk, offset, &iocb->iov, 0,
+                                  nvme_copy_out_completed_cb, iocb);
 
     return;
 
@@ -3029,6 +3030,7 @@ static void nvme_copy_in_completed_cb(void *opaque, int ret)
     uint64_t reftag;
     size_t len, mlen;
     uint16_t status;
+    int64_t offset;
 
     if (ret < 0) {
         iocb->ret = ret;
@@ -3113,10 +3115,11 @@ static void nvme_copy_in_completed_cb(void *opaque, int ret)
     qemu_iovec_reset(&iocb->iov);
     qemu_iovec_add(&iocb->iov, iocb->bounce, len);
 
-    block_acct_start(blk_get_stats(dns->blkconf.blk), &iocb->acct.write, len,
-                     BLOCK_ACCT_WRITE);
+    offset = nvme_l2b(dns, iocb->slba);
+    block_acct_start(blk_get_stats(dns->blkconf.blk), &iocb->acct.write,
+                     offset, len, BLOCK_ACCT_WRITE);
 
-    iocb->aiocb = blk_aio_pwritev(dns->blkconf.blk, nvme_l2b(dns, iocb->slba),
+    iocb->aiocb = blk_aio_pwritev(dns->blkconf.blk, offset,
                                   &iocb->iov, 0, nvme_copy_out_cb, iocb);
 
     return;
@@ -3136,6 +3139,7 @@ static void nvme_copy_in_cb(void *opaque, int ret)
     uint64_t slba;
     uint32_t nlb;
     size_t mlen;
+    int64_t offset;
 
     if (ret < 0 || iocb->ret < 0) {
         block_acct_failed(stats, &iocb->acct.read);
@@ -3154,10 +3158,11 @@ static void nvme_copy_in_cb(void *opaque, int ret)
     qemu_iovec_reset(&iocb->iov);
     qemu_iovec_add(&iocb->iov, iocb->bounce + nvme_l2b(sns, nlb), mlen);
 
-    block_acct_start(stats, &iocb->acct.read, mlen, BLOCK_ACCT_READ);
-    iocb->aiocb = blk_aio_preadv(sns->blkconf.blk, nvme_moff(sns, slba),
-                                 &iocb->iov, 0, nvme_copy_in_completed_cb,
-                                 iocb);
+    offset = nvme_moff(sns, slba);
+    block_acct_start(stats, &iocb->acct.read, offset, mlen,
+                     BLOCK_ACCT_READ);
+    iocb->aiocb = blk_aio_preadv(sns->blkconf.blk, offset, &iocb->iov, 0,
+                                 nvme_copy_in_completed_cb, iocb);
     return;
 
 out:
@@ -3236,6 +3241,7 @@ static void nvme_do_copy(NvmeCopyAIOCB *iocb)
     uint16_t status;
     uint32_t dnsid = le32_to_cpu(req->cmd.nsid);
     uint32_t snsid = dnsid;
+    int64_t offset;
 
     if (iocb->ret < 0) {
         goto done;
@@ -3362,10 +3368,11 @@ static void nvme_do_copy(NvmeCopyAIOCB *iocb)
     assert(len <= blen);
     qemu_iovec_add(&iocb->iov, iocb->bounce, len);
 
-    block_acct_start(blk_get_stats(sns->blkconf.blk), &iocb->acct.read, len,
-                     BLOCK_ACCT_READ);
+    offset = nvme_l2b(sns, slba);
+    block_acct_start(blk_get_stats(sns->blkconf.blk), &iocb->acct.read,
+                     offset, len, BLOCK_ACCT_READ);
 
-    iocb->aiocb = blk_aio_preadv(sns->blkconf.blk, nvme_l2b(sns, slba),
+    iocb->aiocb = blk_aio_preadv(sns->blkconf.blk, offset,
                                  &iocb->iov, 0, nvme_copy_in_cb, iocb);
     return;
 
@@ -3524,7 +3531,7 @@ static uint16_t nvme_compare(NvmeCtrl *n, NvmeRequest *req)
     qemu_iovec_init(&ctx->data.iov, 1);
     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, data_len);
 
-    block_acct_start(blk_get_stats(blk), &req->acct, data_len,
+    block_acct_start(blk_get_stats(blk), &req->acct, offset, data_len,
                      BLOCK_ACCT_READ);
     req->aiocb = blk_aio_preadv(blk, offset, &ctx->data.iov, 0,
                                 nvme_compare_data_cb, req);
@@ -3722,7 +3729,7 @@ static uint16_t nvme_read(NvmeCtrl *n, NvmeRequest *req)
 
     data_offset = nvme_l2b(ns, slba);
 
-    block_acct_start(blk_get_stats(blk), &req->acct, data_size,
+    block_acct_start(blk_get_stats(blk), &req->acct, data_offset, data_size,
                      BLOCK_ACCT_READ);
     nvme_blk_read(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
     return NVME_NO_COMPLETE;
@@ -3892,7 +3899,7 @@ static uint16_t nvme_do_write(NvmeCtrl *n, NvmeRequest *req, bool append,
             goto invalid;
         }
 
-        block_acct_start(blk_get_stats(blk), &req->acct, data_size,
+        block_acct_start(blk_get_stats(blk), &req->acct, data_offset, data_size,
                          BLOCK_ACCT_WRITE);
         nvme_blk_write(blk, data_offset, BDRV_SECTOR_SIZE, nvme_rw_cb, req);
     } else {
hw/nvme/dif.c +4 -4
index 4e7874f3223..fbd4d8eb816 100644
@@ -644,8 +644,8 @@ uint16_t nvme_dif_rw(NvmeCtrl *n, NvmeRequest *req)
     qemu_iovec_add(&ctx->data.iov, ctx->data.bounce, len);
 
     if (req->cmd.opcode == NVME_CMD_READ) {
-        block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
-                         BLOCK_ACCT_READ);
+        block_acct_start(blk_get_stats(blk), &req->acct, offset,
+                         ctx->data.iov.size, BLOCK_ACCT_READ);
 
         req->aiocb = blk_aio_preadv(ns->blkconf.blk, offset, &ctx->data.iov, 0,
                                     nvme_dif_rw_mdata_in_cb, ctx);
@@ -690,8 +690,8 @@ uint16_t nvme_dif_rw(NvmeCtrl *n, NvmeRequest *req)
         }
     }
 
-    block_acct_start(blk_get_stats(blk), &req->acct, ctx->data.iov.size,
-                     BLOCK_ACCT_WRITE);
+    block_acct_start(blk_get_stats(blk), &req->acct, offset,
+                     ctx->data.iov.size, BLOCK_ACCT_WRITE);
 
     req->aiocb = blk_aio_pwritev(ns->blkconf.blk, offset, &ctx->data.iov, 0,
                                  nvme_dif_rw_mdata_out_cb, ctx);
hw/scsi/scsi-disk.c +18 -10
index 24bd1a78b6e..5b40e404e13 100644
@@ -484,7 +484,8 @@ static void scsi_do_read(SCSIDiskReq *r, int ret)
     scsi_req_ref(&r->req);
 
     if (r->req.sg) {
-        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_READ);
+        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg,
+                       r->sector << BDRV_SECTOR_BITS, BLOCK_ACCT_READ);
         r->req.residual -= r->req.sg->size;
         r->req.aiocb = dma_blk_io(r->req.sg, r->sector << BDRV_SECTOR_BITS,
                                   BDRV_SECTOR_SIZE,
@@ -493,7 +494,8 @@ static void scsi_do_read(SCSIDiskReq *r, int ret)
     } else {
         scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         r->qiov.size, BLOCK_ACCT_READ);
+                         r->sector << BDRV_SECTOR_BITS, r->qiov.size,
+                         BLOCK_ACCT_READ);
         r->req.aiocb = sdc->dma_readv(r->sector << BDRV_SECTOR_BITS, &r->qiov,
                                       scsi_read_complete, r, r);
     }
@@ -551,7 +553,7 @@ static void scsi_read_data(SCSIRequest *req)
     first = !r->started;
     r->started = true;
     if (first && r->need_fua) {
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_do_read_cb, r);
     } else {
@@ -634,7 +636,7 @@ static void scsi_write_data(SCSIRequest *req)
 
     if (r->req.cmd.buf[0] == VERIFY_10 || r->req.cmd.buf[0] == VERIFY_12 ||
         r->req.cmd.buf[0] == VERIFY_16) {
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         cb = r->req.sg ? scsi_dma_complete : scsi_write_complete;
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, cb, r);
@@ -642,7 +644,8 @@ static void scsi_write_data(SCSIRequest *req)
     }
 
     if (r->req.sg) {
-        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_WRITE);
+        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg,
+                       r->sector << BDRV_SECTOR_BITS, BLOCK_ACCT_WRITE);
         r->req.residual -= r->req.sg->size;
         r->req.aiocb = dma_blk_io(r->req.sg, r->sector << BDRV_SECTOR_BITS,
                                   BDRV_SECTOR_SIZE,
@@ -650,7 +653,8 @@ static void scsi_write_data(SCSIRequest *req)
                                   DMA_DIRECTION_TO_DEVICE);
     } else {
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         r->qiov.size, BLOCK_ACCT_WRITE);
+                         r->sector << BDRV_SECTOR_BITS, r->qiov.size,
+                         BLOCK_ACCT_WRITE);
         r->req.aiocb = sdc->dma_writev(r->sector << BDRV_SECTOR_BITS, &r->qiov,
                                        scsi_write_complete, r, r);
     }
@@ -1710,7 +1714,7 @@ static void scsi_disk_emulate_mode_select(SCSIDiskReq *r, uint8_t *inbuf)
     if (!blk_enable_write_cache(s->qdev.conf.blk)) {
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r);
         return;
@@ -1777,6 +1781,7 @@ static void scsi_unmap_complete_noio(UnmapCBData *data, int ret)
         }
 
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
+                         r->sector * BDRV_SECTOR_SIZE,
                          r->sector_count * BDRV_SECTOR_SIZE,
                          BLOCK_ACCT_UNMAP);
 
@@ -1894,7 +1899,8 @@ static void scsi_write_same_complete(void *opaque, int ret)
                             data->iov.iov_len);
     if (data->iov.iov_len) {
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                         data->iov.iov_len, BLOCK_ACCT_WRITE);
+                         data->sector << BDRV_SECTOR_BITS, data->iov.iov_len,
+                         BLOCK_ACCT_WRITE);
         /* Reinitialize qiov, to handle unaligned WRITE SAME request
          * where final qiov may need smaller size */
         qemu_iovec_init_external(&data->qiov, &data->iov, 1);
@@ -1943,6 +1949,7 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf)
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
         block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
+                         r->req.cmd.lba * s->qdev.blocksize,
                          nb_sectors * s->qdev.blocksize,
                         BLOCK_ACCT_WRITE);
         r->req.aiocb = blk_aio_pwrite_zeroes(s->qdev.conf.blk,
@@ -1969,7 +1976,8 @@ static void scsi_disk_emulate_write_same(SCSIDiskReq *r, uint8_t *inbuf)
 
     scsi_req_ref(&r->req);
     block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,
-                     data->iov.iov_len, BLOCK_ACCT_WRITE);
+                     data->sector << BDRV_SECTOR_BITS, data->iov.iov_len,
+                     BLOCK_ACCT_WRITE);
     r->req.aiocb = blk_aio_pwritev(s->qdev.conf.blk,
                                    data->sector << BDRV_SECTOR_BITS,
                                    &data->qiov, 0,
@@ -2237,7 +2245,7 @@ static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)
     case SYNCHRONIZE_CACHE:
         /* The request is used as the AIO opaque value, so add a ref.  */
         scsi_req_ref(&r->req);
-        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, 0,
+        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct, -1, 0,
                          BLOCK_ACCT_FLUSH);
         r->req.aiocb = blk_aio_flush(s->qdev.conf.blk, scsi_aio_complete, r);
         return 0;
qemu-io-cmds.c +7 -7
index de4c1966fea..655dfae9057 100644
@@ -1538,8 +1538,8 @@ static int aio_read_f(BlockBackend *blk, int argc, char **argv)
     }
 
     clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
-    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                     BLOCK_ACCT_READ);
+    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                     ctx->qiov.size, BLOCK_ACCT_READ);
     blk_aio_preadv(blk, ctx->offset, &ctx->qiov, ctx->flags, aio_read_done,
                    ctx);
     return 0;
@@ -1693,8 +1693,8 @@ static int aio_write_f(BlockBackend *blk, int argc, char **argv)
         }
 
         clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
-        block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                         BLOCK_ACCT_WRITE);
+        block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                         ctx->qiov.size, BLOCK_ACCT_WRITE);
 
         blk_aio_pwritev(blk, ctx->offset, &ctx->qiov, ctx->flags,
                         aio_write_done, ctx);
@@ -1706,7 +1706,7 @@ static int aio_write_f(BlockBackend *blk, int argc, char **argv)
 static int aio_flush_f(BlockBackend *blk, int argc, char **argv)
 {
     BlockAcctCookie cookie;
-    block_acct_start(blk_get_stats(blk), &cookie, 0, BLOCK_ACCT_FLUSH);
+    block_acct_start(blk_get_stats(blk), &cookie, -1, 0, BLOCK_ACCT_FLUSH);
     blk_drain_all();
     block_acct_done(blk_get_stats(blk), &cookie);
     return 0;
@@ -2325,8 +2325,8 @@ static int aio_discard_f(BlockBackend *blk, int argc, char **argv)
 
     clock_gettime(CLOCK_MONOTONIC, &ctx->t1);
     ctx->qiov.size = count;
-    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->qiov.size,
-                     BLOCK_ACCT_UNMAP);
+    block_acct_start(blk_get_stats(blk), &ctx->acct, ctx->offset,
+                     ctx->qiov.size, BLOCK_ACCT_UNMAP);
     blk_aio_pdiscard(blk, ctx->offset, count, aio_discard_done, ctx);
 
     return 0;
system/dma-helpers.c +2 -2
index 0d592f64680..7bf41119ebc 100644
@@ -315,9 +315,9 @@ MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
 }
 
 void dma_acct_start(BlockBackend *blk, BlockAcctCookie *cookie,
-                    QEMUSGList *sg, enum BlockAcctType type)
+                    QEMUSGList *sg, int64_t offset, enum BlockAcctType type)
 {
-    block_acct_start(blk_get_stats(blk), cookie, sg->size, type);
+    block_acct_start(blk_get_stats(blk), cookie, offset, sg->size, type);
 }
 
 uint64_t dma_aligned_pow2_mask(uint64_t start, uint64_t end, int max_addr_bits)
tests/unit/test-block-accounting.c +1 -1
index 7aae491cfc2..0081502891c 100644
@@ -63,7 +63,7 @@ static void *reader_thread(void *opaque)
     while (!qatomic_read(&stop_workers)) {
         BlockAcctCookie cookie;
 
-        block_acct_start(stats, &cookie, 4096, BLOCK_ACCT_READ);
+        block_acct_start(stats, &cookie, -1, 4096, BLOCK_ACCT_READ);
         block_acct_done(stats, &cookie);
     }
 
Signature · 1 line
2.55.0

For the parts touching hw/nvme/*

#3 lore raw

PATCH 2/9 qapi/block: Add IoAccountingOperation enum

In reply to Hanna Czenczek

This enum gives more information than IoOperationType (which is used for the rerror/werror distinction) to identify operation types for block accounting.

---
 qapi/block.json | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
qapi/block.json +22 -0
index 46955bbb3e3..456118eb0b4 100644
@@ -603,3 +603,25 @@
            '*boundaries-zap': ['uint64'],
            '*boundaries-flush': ['uint64'] },
   'allow-preconfig': true }
+
+##
+# @IoAccountingOperation:
+#
+# A more finely grained enumeration of I/O operation types beyond what
+# `IoOperationType` provides (whose read/write distinction matches the
+# rerror/werror policy settings).
+#
+# @read: Reading data
+#
+# @write: Writing data
+#
+# @flush: Flushing data to disk
+#
+# @zone-append: Appending data to a zone of a zoned block device
+#
+# @unmap: Discarding a block of data
+#
+# Since: 11.2
+##
+{ 'enum': 'IoAccountingOperation',
+  'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
Signature · 1 line
2.55.0
#4 lore raw

Re: [PATCH 2/9] qapi/block: Add IoAccountingOperation enum

Quoted 14 lines · Hanna Czenczek

This enum gives more information than IoOperationType (which is used for the rerror/werror distinction) to identify operation types for block accounting.

---
 qapi/block.json | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
qapi/block.json +0 -0
index 46955bbb3e3..456118eb0b4 100644

qapi/block.json line 612

Quoted 10 lines
qapi/block.json +7 -0
@@ -603,3 +603,25 @@
            '*boundaries-zap': ['uint64'],
            '*boundaries-flush': ['uint64'] },
   'allow-preconfig': true }
+
+##
+# @IoAccountingOperation:
+#
+# A more finely grained enumeration of I/O operation types beyond what
+# `IoOperationType` provides (whose read/write distinction matches the
+# rerror/werror policy settings).

Why is the comparison to IoOperationType useful?

If making the connection between IoOperationType values and "rerror/werror policy setting" is useful, why isn't it made in IoOperationType's docs?

What settings exactly? Could this be a link?

Quoted 15 lines
qapi/block.json +15 -0
+#
+# @read: Reading data
+#
+# @write: Writing data
+#
+# @flush: Flushing data to disk
+#
+# @zone-append: Appending data to a zone of a zoned block device
+#
+# @unmap: Discarding a block of data
+#
+# Since: 11.2
+##
+{ 'enum': 'IoAccountingOperation',
+  'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
#5 lore raw

Re: [PATCH 2/9] qapi/block: Add IoAccountingOperation enum

Quoted 11 lines · Markus Armbruster
Quoted 9 lines · Hanna Czenczek

This enum gives more information than IoOperationType (which is used for the rerror/werror distinction) to identify operation types for block accounting.

---
  qapi/block.json | 22 ++++++++++++++++++++++
  1 file changed, 22 insertions(+)
Quoted 16 lines
Quoted 5 lines
qapi/block.json +0 -0
index 46955bbb3e3..456118eb0b4 100644

qapi/block.json line 612

Quoted 10 lines
qapi/block.json +7 -0
@@ -603,3 +603,25 @@
             '*boundaries-zap': ['uint64'],
             '*boundaries-flush': ['uint64'] },
    'allow-preconfig': true }
+
+##
+# @IoAccountingOperation:
+#
+# A more finely grained enumeration of I/O operation types beyond what
+# `IoOperationType` provides (whose read/write distinction matches the
+# rerror/werror policy settings).

Why is the comparison to IoOperationType useful?

Because the IoOperationType exists, and in my mind, it would be better to have a single enum for all types.

Now, to reason why a new one is introduced, the commit message here would be sufficient. But I felt it better to document for users also why there are two types.

Quoted 3 lines

If making the connection between IoOperationType values and "rerror/werror policy setting" is useful, why isn't it made in IoOperationType's docs?

That is true! I should move it there.

Quoted 1 line

What settings exactly? Could this be a link?

Probably. I will take the look.

(The block device’s rerror/werror settings.)

Hanna

Quoted 15 lines
Quoted 15 lines
qapi/block.json +15 -0
+#
+# @read: Reading data
+#
+# @write: Writing data
+#
+# @flush: Flushing data to disk
+#
+# @zone-append: Appending data to a zone of a zoned block device
+#
+# @unmap: Discarding a block of data
+#
+# Since: 11.2
+##
+{ 'enum': 'IoAccountingOperation',
+  'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
#6 lore raw

PATCH 3/9 qapi/block: Add BLOCK_IO_DELAY event

In reply to Hanna Czenczek

This event will be emitted when a disk operation takes longer than a pre-defined threshold (as set on the block device).

---
 qapi/block.json | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
qapi/block.json +30 -0
index 456118eb0b4..1cdaffd5520 100644
@@ -625,3 +625,33 @@
 ##
 { 'enum': 'IoAccountingOperation',
   'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
+
+##
+# @BLOCK_IO_DELAY:
+#
+# Emitted when a disk operation takes longer than the pre-defined
+# threshold (as set via the delay-alert-ms property on the block
+# device).
+#
+# Note that delays deliberately incurred by throttling do count
+# towards the operation duration.
+#
+# @qom-path: path to the device object in the QOM tree
+#
+# @operation: I/O operation
+#
+# @duration: Ongoing duration of the operation (in seconds)
+#
+# @offset: Request offset in the guest disk (in bytes), if available
+#
+# @bytes: Request length
+#
+# Since: 11.2
+##
+{ 'event': 'BLOCK_IO_DELAY',
+  'data': {
+      'qom-path': 'str',
+      'operation': 'IoAccountingOperation',
+      'duration': 'number',
+      '*offset': 'uint64',
+      'bytes': 'uint64' } }
Signature · 1 line
2.55.0
#7 lore raw

Re: [PATCH 3/9] qapi/block: Add BLOCK_IO_DELAY event

Quoted 13 lines · Hanna Czenczek

This event will be emitted when a disk operation takes longer than a pre-defined threshold (as set on the block device).

---
 qapi/block.json | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
qapi/block.json +0 -0
index 456118eb0b4..1cdaffd5520 100644

qapi/block.json line 634

Quoted 10 lines
qapi/block.json +7 -0
@@ -625,3 +625,33 @@
 ##
 { 'enum': 'IoAccountingOperation',
   'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
+
+##
+# @BLOCK_IO_DELAY:
+#
+# Emitted when a disk operation takes longer than the pre-defined
+# threshold (as set via the delay-alert-ms property on the block
+# device).

Double-quotes around delay-alert-ms, please.

"The block device" is the one at @qom-path?

As far as I can tell, this property doesn't yet exist at this point. Fine, but please mention the fact in the commit message.

Quoted 23 lines
qapi/block.json +23 -0
+#
+# Note that delays deliberately incurred by throttling do count
+# towards the operation duration.
+#
+# @qom-path: path to the device object in the QOM tree
+#
+# @operation: I/O operation
+#
+# @duration: Ongoing duration of the operation (in seconds)
+#
+# @offset: Request offset in the guest disk (in bytes), if available
+#
+# @bytes: Request length
+#
+# Since: 11.2
+##
+{ 'event': 'BLOCK_IO_DELAY',
+  'data': {
+      'qom-path': 'str',
+      'operation': 'IoAccountingOperation',
+      'duration': 'number',
+      '*offset': 'uint64',
+      'bytes': 'uint64' } }
#8 lore raw

Re: [PATCH 3/9] qapi/block: Add BLOCK_IO_DELAY event

Quoted 10 lines · Markus Armbruster
Quoted 8 lines · Hanna Czenczek

This event will be emitted when a disk operation takes longer than a pre-defined threshold (as set on the block device).

---
  qapi/block.json | 30 ++++++++++++++++++++++++++++++
  1 file changed, 30 insertions(+)
Quoted 16 lines
Quoted 5 lines
qapi/block.json +0 -0
index 456118eb0b4..1cdaffd5520 100644

qapi/block.json line 634

Quoted 10 lines
qapi/block.json +7 -0
@@ -625,3 +625,33 @@
  ##
  { 'enum': 'IoAccountingOperation',
    'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
+
+##
+# @BLOCK_IO_DELAY:
+#
+# Emitted when a disk operation takes longer than the pre-defined
+# threshold (as set via the delay-alert-ms property on the block
+# device).

Double-quotes around delay-alert-ms, please.

Sure.

Quoted 1 line

"The block device" is the one at @qom-path?

Yes, exactly.

Quoted 2 lines

As far as I can tell, this property doesn't yet exist at this point. Fine, but please mention the fact in the commit message.

I will!

Thanks for reviewing,

Hanna

Quoted 23 lines
Quoted 23 lines
qapi/block.json +23 -0
+#
+# Note that delays deliberately incurred by throttling do count
+# towards the operation duration.
+#
+# @qom-path: path to the device object in the QOM tree
+#
+# @operation: I/O operation
+#
+# @duration: Ongoing duration of the operation (in seconds)
+#
+# @offset: Request offset in the guest disk (in bytes), if available
+#
+# @bytes: Request length
+#
+# Since: 11.2
+##
+{ 'event': 'BLOCK_IO_DELAY',
+  'data': {
+      'qom-path': 'str',
+      'operation': 'IoAccountingOperation',
+      'duration': 'number',
+      '*offset': 'uint64',
+      'bytes': 'uint64' } }
#9 lore raw

Re: [PATCH 3/9] qapi/block: Add BLOCK_IO_DELAY event

Quoted 28 lines · Hanna Czenczek
Quoted 10 lines · Markus Armbruster
Quoted 8 lines · Hanna Czenczek

This event will be emitted when a disk operation takes longer than a pre-defined threshold (as set on the block device).

---
  qapi/block.json | 30 ++++++++++++++++++++++++++++++
  1 file changed, 30 insertions(+)
Quoted 16 lines
Quoted 5 lines
qapi/block.json +0 -0
index 456118eb0b4..1cdaffd5520 100644

qapi/block.json line 634

Quoted 10 lines
qapi/block.json +7 -0
@@ -625,3 +625,33 @@
  ##
  { 'enum': 'IoAccountingOperation',
    'data': [ 'read', 'write', 'flush', 'zone-append', 'unmap' ] }
+
+##
+# @BLOCK_IO_DELAY:
+#
+# Emitted when a disk operation takes longer than the pre-defined
+# threshold (as set via the delay-alert-ms property on the block
+# device).

Double-quotes around delay-alert-ms, please.

Quoted 5 lines

Sure.

Quoted 1 line

"The block device" is the one at @qom-path?

Yes, exactly.

Perhaps tweak @qom-path's description: "the block device object".

Quoted 32 lines
Quoted 2 lines

As far as I can tell, this property doesn't yet exist at this point. Fine, but please mention the fact in the commit message.

I will!

Thanks for reviewing,

Hanna

Quoted 23 lines
Quoted 23 lines
qapi/block.json +23 -0
+#
+# Note that delays deliberately incurred by throttling do count
+# towards the operation duration.
+#
+# @qom-path: path to the device object in the QOM tree
+#
+# @operation: I/O operation
+#
+# @duration: Ongoing duration of the operation (in seconds)
+#
+# @offset: Request offset in the guest disk (in bytes), if available
+#
+# @bytes: Request length
+#
+# Since: 11.2
+##
+{ 'event': 'BLOCK_IO_DELAY',
+  'data': {
+      'qom-path': 'str',
+      'operation': 'IoAccountingOperation',
+      'duration': 'number',
+      '*offset': 'uint64',
+      'bytes': 'uint64' } }
#10 lore raw

PATCH 4/9 block-backend: Public blk_get_attached_dev_path()

In reply to Hanna Czenczek

Make blk_get_attached_dev_path() public so we can use it in the I/O operation delay QMP event to identify the affected guest block device.

---
 include/system/block-backend-io.h | 9 +++++++++
 block/block-backend.c             | 6 +-----
 2 files changed, 10 insertions(+), 5 deletions(-)
include/system/block-backend-io.h +9 -0
index fd84723d9d0..63b2dd2e24f 100644
@@ -41,6 +41,15 @@ bool blk_iostatus_is_enabled(const BlockBackend *blk);
  */
 char *blk_get_attached_dev_id(BlockBackend *blk);
 
+/*
+ * Return the QOM path of the block device attached to the
+ * BlockBackend.
+ *
+ * The caller is responsible for releasing the value returned
+ * with g_free() after use.
+ */
+char *blk_get_attached_dev_path(BlockBackend *blk);
+
 BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
                                   int64_t bytes, BdrvRequestFlags flags,
                                   BlockCompletionFunc *cb, void *opaque);
block/block-backend.c +1 -5
index 37ba7e9fc40..164bda846f4 100644
@@ -1053,11 +1053,7 @@ char *blk_get_attached_dev_id(BlockBackend *blk)
     return blk_get_attached_dev_id_or_path(blk, true);
 }
 
-/*
- * The caller is responsible for releasing the value returned
- * with g_free() after use.
- */
-static char *blk_get_attached_dev_path(BlockBackend *blk)
+char *blk_get_attached_dev_path(BlockBackend *blk)
 {
     return blk_get_attached_dev_id_or_path(blk, false);
 }
Signature · 1 line
2.55.0
#11 lore raw

PATCH 5/9 block/accounting: Add BB field to latency checker

In reply to Hanna Czenczek

The BlockBackend reference is required to be able to generate the QOM path as part of emitted events.

A weak reference is enough because BlockAcctStats is tied directly to one BlockBackend, and will be deleted via block_acct_cleanup() before the BlockBackend is truly deleted.

---
 include/block/accounting.h | 3 ++-
 block/accounting.c         | 7 ++++++-
 block/block-backend.c      | 2 +-
 3 files changed, 9 insertions(+), 3 deletions(-)
include/block/accounting.h +2 -1
index 9386440ec89..025536239e6 100644
@@ -81,6 +81,7 @@ typedef struct BlockLatencyHistogram {
 
 struct BlockAcctStats {
     QemuMutex lock;
+    BlockBackend *blk;
     uint64_t nr_bytes[BLOCK_MAX_IOTYPE];
     uint64_t nr_ops[BLOCK_MAX_IOTYPE];
     uint64_t invalid_ops[BLOCK_MAX_IOTYPE];
@@ -101,7 +102,7 @@ typedef struct BlockAcctCookie {
     enum BlockAcctType type;
 } BlockAcctCookie;
 
-void block_acct_init(BlockAcctStats *stats);
+void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
                       uint32_t num_stats_intervals, Error **errp);
block/accounting.c +6 -1
index 66e5001403f..a74551d41f2 100644
@@ -33,7 +33,7 @@
 static QEMUClockType clock_type = QEMU_CLOCK_REALTIME;
 static const int qtest_latency_ns = NANOSECONDS_PER_SECOND / 1000;
 
-void block_acct_init(BlockAcctStats *stats)
+void block_acct_init(BlockBackend *blk, BlockAcctStats *stats)
 {
     qemu_mutex_init(&stats->lock);
     if (qtest_enabled()) {
@@ -41,6 +41,11 @@ void block_acct_init(BlockAcctStats *stats)
     }
     stats->account_invalid = true;
     stats->account_failed = true;
+    /*
+     * No need to blk_ref() because block_acct_cleanup() is called exactly when
+     * the BB is deleted.
+     */
+    stats->blk = blk;
 }
 
 static bool bool_from_onoffauto(OnOffAuto val, bool def)
block/block-backend.c +1 -1
index 164bda846f4..ca091a8bf5d 100644
@@ -369,7 +369,7 @@ BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm)
     blk->on_read_error = BLOCKDEV_ON_ERROR_REPORT;
     blk->on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
 
-    block_acct_init(&blk->stats);
+    block_acct_init(blk, &blk->stats);
 
     qemu_mutex_init(&blk->queued_requests_lock);
     qemu_co_queue_init(&blk->queued_requests);
Signature · 1 line
2.55.0
#12 lore raw

Re: [PATCH 5/9] block/accounting: Add BB field to latency checker

Am 31.08.2026 um 15:52 hat Hanna Czenczek geschrieben:

Quoted 8 lines

The BlockBackend reference is required to be able to generate the QOM path as part of emitted events.

A weak reference is enough because BlockAcctStats is tied directly to one BlockBackend, and will be deleted via block_acct_cleanup() before the BlockBackend is truly deleted.

The subject line is a bit confusing as there is no latency checker yet. Should it say "to BlockAcctStats"?

Quoted 10 lines
 include/block/accounting.h | 3 ++-
 block/accounting.c         | 7 ++++++-
 block/block-backend.c      | 2 +-
 3 files changed, 9 insertions(+), 3 deletions(-)
block/block-backend.c +0 -0
index 164bda846f4..ca091a8bf5d 100644

block/block-backend.c BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm) · line 372

Quoted 5 lines
block/block-backend.c +1 -1
@@ -369,7 +369,7 @@ BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm)
     blk->on_read_error = BLOCKDEV_ON_ERROR_REPORT;
     blk->on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
 
-    block_acct_init(&blk->stats);
+    block_acct_init(blk, &blk->stats);

This is the only caller. I'm not sure what other callers could look like, but now that a BlockBackend is required for it, could the second parameter ever give any useful additional information (as opposed to block_acct_init() just accessing blk->stats internally now that it has blk)?

Kevin

#13 lore raw

Re: [PATCH 5/9] block/accounting: Add BB field to latency checker

Quoted 11 lines · Kevin Wolf

Am 31.08.2026 um 15:52 hat Hanna Czenczek geschrieben:

Quoted 8 lines

The BlockBackend reference is required to be able to generate the QOM path as part of emitted events.

A weak reference is enough because BlockAcctStats is tied directly to one BlockBackend, and will be deleted via block_acct_cleanup() before the BlockBackend is truly deleted.

The subject line is a bit confusing as there is no latency checker yet. Should it say "to BlockAcctStats"?

Oops. I fixed the body, but not the subject. Yes, it absolutely should, thanks!

Quoted 12 lines
Quoted 12 lines
  include/block/accounting.h | 3 ++-
  block/accounting.c         | 7 ++++++-
  block/block-backend.c      | 2 +-
  3 files changed, 9 insertions(+), 3 deletions(-)
block/block-backend.c +0 -0
index 164bda846f4..ca091a8bf5d 100644
@@ -369,7 +369,7 @@ BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm)
      blk->on_read_error = BLOCKDEV_ON_ERROR_REPORT;
      blk->on_write_error = BLOCKDEV_ON_ERROR_ENOSPC;
 
Quoted 7 lines

block/block-backend.c BlockBackend *blk_new(AioContext *ctx, uint64_t perm, uint64_t shared_perm) · line 372

Quoted 2 lines
block/block-backend.c +1 -1
-    block_acct_init(&blk->stats);
+    block_acct_init(blk, &blk->stats);

This is the only caller. I'm not sure what other callers could look like, but now that a BlockBackend is required for it, could the second parameter ever give any useful additional information (as opposed to block_acct_init() just accessing blk->stats internally now that it has blk)?

I mean, to me personally it looks a bit nicer this way, because it makes it a bit clearer *what* is initialized.

But you’re right. Functionally, there’s absolutely no point in passing both, so I’ll cut it down (depending on what the next version of this series is going to look like…).

Hanna

#14 lore raw

PATCH 6/9 block/accounting: Emit BLOCK_IO_DELAY event

In reply to Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

So, for now, just implement the simpler solution of only notifying the management layer when the request does complete, so VMs with high latency spikes can at least be identified when they happen without having to regularly check the latency histogram.

---
 include/block/accounting.h | 10 ++++++++-
 block/accounting.c         | 42 +++++++++++++++++++++++++++++++++++++-
 blockdev.c                 |  2 +-
 hw/block/block.c           |  2 +-
 4 files changed, 52 insertions(+), 4 deletions(-)
include/block/accounting.h +9 -1
index 025536239e6..ba3a6859cf4 100644
@@ -92,6 +92,7 @@ struct BlockAcctStats {
     QSLIST_HEAD(, BlockAcctTimedStats) intervals;
     bool account_invalid;
     bool account_failed;
+    int64_t delay_threshold_ns;
     BlockLatencyHistogram latency_histogram[BLOCK_MAX_IOTYPE];
 };
 
@@ -103,9 +104,16 @@ typedef struct BlockAcctCookie {
 } BlockAcctCookie;
 
 void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);
+/**
+ * Set up accounting for a block device in @stats.
+ * @alert_ns specifies a latency so that if any request takes longer than that
+ * threshold, a BLOCK_IO_DELAY event will be generated (when that request
+ * completes). Pass 0 to disable.
+ */
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp);
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp);
 void block_acct_cleanup(BlockAcctStats *stats);
 void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
 BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
block/accounting.c +41 -1

70 lines not on this page · raw message

blockdev.c +1 -1
index 6e86c6262f9..195bac8af01 100644
@@ -618,7 +618,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
         bs->detect_zeroes = detect_zeroes;
 
         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, NULL);
+                         NULL, 0, 0, NULL);
 
         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
             blk_unref(blk);
hw/block/block.c +1 -1
index f187fa025d0..19301c6f995 100644
@@ -251,7 +251,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
 
     if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                           conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, errp)) {
+                          conf->num_stats_intervals, 0, errp)) {
         return false;
     }
     return true;
Signature · 1 line
2.55.0
#15 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 13 lines · Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

Quoted 6 lines

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

I think this patch series already couples the accounting so closely with BlockBackend (i.e. adding the offset field into the cookie struct and adding a BB pointer into the stats struct) that we might as well fully integrate the two. Then callers don't need to manually manage cookies because BlockBackend does that internally and the concerns about lifetimes go away.

Quoted 30 lines

So, for now, just implement the simpler solution of only notifying the management layer when the request does complete, so VMs with high latency spikes can at least be identified when they happen without having to regularly check the latency histogram.

---
 include/block/accounting.h | 10 ++++++++-
 block/accounting.c         | 42 +++++++++++++++++++++++++++++++++++++-
 blockdev.c                 |  2 +-
 hw/block/block.c           |  2 +-
 4 files changed, 52 insertions(+), 4 deletions(-)
include/block/accounting.h +1 -0
index 025536239e6..ba3a6859cf4 100644
@@ -92,6 +92,7 @@ struct BlockAcctStats {
     QSLIST_HEAD(, BlockAcctTimedStats) intervals;
     bool account_invalid;
     bool account_failed;
+    int64_t delay_threshold_ns;
     BlockLatencyHistogram latency_histogram[BLOCK_MAX_IOTYPE];
 };
 
@@ -103,9 +104,16 @@ typedef struct BlockAcctCookie {
 } BlockAcctCookie;
 
 void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);

include/block/accounting.h typedef struct BlockAcctCookie { · line 115

Quoted 10 lines
include/block/accounting.h +7 -1
+/**
+ * Set up accounting for a block device in @stats.
+ * @alert_ns specifies a latency so that if any request takes longer than that
+ * threshold, a BLOCK_IO_DELAY event will be generated (when that request
+ * completes). Pass 0 to disable.
+ */
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp);
+                      uint32_t num_stats_intervals, int64_t alert_ns,

There are a few names for the same thing:
- delay_threshold_ns
- alert_ns
- BLOCK_IO_DELAY

Pick one and use it consistently?

Quoted 111 lines
include/block/accounting.h +1 -0
+                      Error **errp);
 void block_acct_cleanup(BlockAcctStats *stats);
 void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
 BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
block/accounting.c +41 -1
index a74551d41f2..debf1924455 100644
@@ -27,8 +27,10 @@
 #include "block/accounting.h"
 #include "block/block_int.h"
 #include "qemu/timer.h"
+#include "system/block-backend.h"
 #include "system/qtest.h"
 #include "qapi/error.h"
+#include "qapi/qapi-events-block.h"
 
 static QEMUClockType clock_type = QEMU_CLOCK_REALTIME;
 static const int qtest_latency_ns = NANOSECONDS_PER_SECOND / 1000;
@@ -62,9 +64,35 @@ static bool bool_from_onoffauto(OnOffAuto val, bool def)
     }
 }
 
+/**
+ * Convert a BlockAcctType into its QAPI equivalent IoAccountingOperation.
+ *
+ * Must only be called for valid BlockAcctType values, i.e. specifically not for
+ * `BLOCK_ACCT_NONE`.
+ */
+static IoAccountingOperation block_acct_qapi_type(enum BlockAcctType type)
+{
+    switch (type) {
+    case BLOCK_ACCT_READ:
+        return IO_ACCOUNTING_OPERATION_READ;
+    case BLOCK_ACCT_WRITE:
+        return IO_ACCOUNTING_OPERATION_WRITE;
+    case BLOCK_ACCT_FLUSH:
+        return IO_ACCOUNTING_OPERATION_FLUSH;
+    case BLOCK_ACCT_ZONE_APPEND:
+        return IO_ACCOUNTING_OPERATION_ZONE_APPEND;
+    case BLOCK_ACCT_UNMAP:
+        return IO_ACCOUNTING_OPERATION_UNMAP;
+    case BLOCK_ACCT_NONE:
+    default:
+        g_assert_not_reached();
+    }
+}
+
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp)
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp)
 {
     stats->account_invalid = bool_from_onoffauto(account_invalid,
                                                  stats->account_invalid);
@@ -79,6 +107,7 @@ bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
             block_acct_add_interval(stats, stats_intervals[i]);
         }
     }
+    stats->delay_threshold_ns = alert_ns;
     return true;
 }
 
@@ -252,6 +281,17 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
         return;
     }
 
+    if (stats->delay_threshold_ns && latency_ns > stats->delay_threshold_ns) {
+        g_autofree char *dev_path = blk_get_attached_dev_path(stats->blk);
+        double latency = latency_ns / (double)NANOSECONDS_PER_SECOND;
+
+        qapi_event_send_block_io_delay(dev_path,
+                                       block_acct_qapi_type(cookie->type),
+                                       latency,
+                                       cookie->offset >= 0, cookie->offset,
+                                       cookie->bytes);
+    }
+
     WITH_QEMU_LOCK_GUARD(&stats->lock) {
         if (failed) {
             stats->failed_ops[cookie->type]++;
blockdev.c +1 -1
index 6e86c6262f9..195bac8af01 100644
@@ -618,7 +618,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
         bs->detect_zeroes = detect_zeroes;
 
         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, NULL);
+                         NULL, 0, 0, NULL);
 
         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
             blk_unref(blk);
hw/block/block.c +1 -1
index f187fa025d0..19301c6f995 100644
@@ -251,7 +251,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
 
     if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                           conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, errp)) {
+                          conf->num_stats_intervals, 0, errp)) {
         return false;
     }
     return true;
Signature · 1 line
2.55.0
#16 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 20 lines · Stefan Hajnoczi
Quoted 13 lines · Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

Quoted 6 lines

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

Quoted 6 lines

I think this patch series already couples the accounting so closely with BlockBackend (i.e. adding the offset field into the cookie struct and adding a BB pointer into the stats struct) that we might as well fully integrate the two. Then callers don't need to manually manage cookies because BlockBackend does that internally and the concerns about lifetimes go away.

I don’t follow how integrating them into BlockBackend automatically solves the problem.

Are you suggesting that blk_* I/O functions should do the accounting instead of the device emulation code?

Quoted 44 lines
Quoted 29 lines

So, for now, just implement the simpler solution of only notifying the management layer when the request does complete, so VMs with high latency spikes can at least be identified when they happen without having to regularly check the latency histogram.

---
  include/block/accounting.h | 10 ++++++++-
  block/accounting.c         | 42 +++++++++++++++++++++++++++++++++++++-
  blockdev.c                 |  2 +-
  hw/block/block.c           |  2 +-
  4 files changed, 52 insertions(+), 4 deletions(-)
include/block/accounting.h +1 -0
index 025536239e6..ba3a6859cf4 100644
@@ -92,6 +92,7 @@ struct BlockAcctStats {
      QSLIST_HEAD(, BlockAcctTimedStats) intervals;
      bool account_invalid;
      bool account_failed;
+    int64_t delay_threshold_ns;
      BlockLatencyHistogram latency_histogram[BLOCK_MAX_IOTYPE];
  };
 
@@ -103,9 +104,16 @@ typedef struct BlockAcctCookie {
  } BlockAcctCookie;
 
  void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);

include/block/accounting.h typedef struct BlockAcctCookie { · line 115

Quoted 10 lines
include/block/accounting.h +7 -1
+/**
+ * Set up accounting for a block device in @stats.
+ * @alert_ns specifies a latency so that if any request takes longer than that
+ * threshold, a BLOCK_IO_DELAY event will be generated (when that request
+ * completes). Pass 0 to disable.
+ */
  bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                        enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp);
+                      uint32_t num_stats_intervals, int64_t alert_ns,

There are a few names for the same thing:
- delay_threshold_ns
- alert_ns
- BLOCK_IO_DELAY

Quoted 1 line

Pick one and use it consistently?

Sure.

Hanna

Quoted 111 lines
Quoted 111 lines
include/block/accounting.h +1 -0
+                      Error **errp);
  void block_acct_cleanup(BlockAcctStats *stats);
  void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
  BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
block/accounting.c +41 -1
index a74551d41f2..debf1924455 100644
@@ -27,8 +27,10 @@
  #include "block/accounting.h"
  #include "block/block_int.h"
  #include "qemu/timer.h"
+#include "system/block-backend.h"
  #include "system/qtest.h"
  #include "qapi/error.h"
+#include "qapi/qapi-events-block.h"
 
  static QEMUClockType clock_type = QEMU_CLOCK_REALTIME;
  static const int qtest_latency_ns = NANOSECONDS_PER_SECOND / 1000;
@@ -62,9 +64,35 @@ static bool bool_from_onoffauto(OnOffAuto val, bool def)
      }
  }
 
+/**
+ * Convert a BlockAcctType into its QAPI equivalent IoAccountingOperation.
+ *
+ * Must only be called for valid BlockAcctType values, i.e. specifically not for
+ * `BLOCK_ACCT_NONE`.
+ */
+static IoAccountingOperation block_acct_qapi_type(enum BlockAcctType type)
+{
+    switch (type) {
+    case BLOCK_ACCT_READ:
+        return IO_ACCOUNTING_OPERATION_READ;
+    case BLOCK_ACCT_WRITE:
+        return IO_ACCOUNTING_OPERATION_WRITE;
+    case BLOCK_ACCT_FLUSH:
+        return IO_ACCOUNTING_OPERATION_FLUSH;
+    case BLOCK_ACCT_ZONE_APPEND:
+        return IO_ACCOUNTING_OPERATION_ZONE_APPEND;
+    case BLOCK_ACCT_UNMAP:
+        return IO_ACCOUNTING_OPERATION_UNMAP;
+    case BLOCK_ACCT_NONE:
+    default:
+        g_assert_not_reached();
+    }
+}
+
  bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                        enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp)
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp)
  {
      stats->account_invalid = bool_from_onoffauto(account_invalid,
                                                   stats->account_invalid);
@@ -79,6 +107,7 @@ bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
              block_acct_add_interval(stats, stats_intervals[i]);
          }
      }
+    stats->delay_threshold_ns = alert_ns;
      return true;
  }
 
@@ -252,6 +281,17 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
          return;
      }
 
+    if (stats->delay_threshold_ns && latency_ns > stats->delay_threshold_ns) {
+        g_autofree char *dev_path = blk_get_attached_dev_path(stats->blk);
+        double latency = latency_ns / (double)NANOSECONDS_PER_SECOND;
+
+        qapi_event_send_block_io_delay(dev_path,
+                                       block_acct_qapi_type(cookie->type),
+                                       latency,
+                                       cookie->offset >= 0, cookie->offset,
+                                       cookie->bytes);
+    }
+
      WITH_QEMU_LOCK_GUARD(&stats->lock) {
          if (failed) {
              stats->failed_ops[cookie->type]++;
blockdev.c +1 -1
index 6e86c6262f9..195bac8af01 100644
@@ -618,7 +618,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
          bs->detect_zeroes = detect_zeroes;
 
          block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, NULL);
+                         NULL, 0, 0, NULL);
 
          if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
              blk_unref(blk);
hw/block/block.c +1 -1
index f187fa025d0..19301c6f995 100644
@@ -251,7 +251,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
 
      if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                            conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, errp)) {
+                          conf->num_stats_intervals, 0, errp)) {
          return false;
      }
      return true;
Signature · 1 line
2.55.0
#17 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 28 lines · Hanna Czenczek
Quoted 20 lines · Stefan Hajnoczi
Quoted 13 lines · Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

Quoted 6 lines

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

Quoted 6 lines

I think this patch series already couples the accounting so closely with BlockBackend (i.e. adding the offset field into the cookie struct and adding a BB pointer into the stats struct) that we might as well fully integrate the two. Then callers don't need to manually manage cookies because BlockBackend does that internally and the concerns about lifetimes go away.

Quoted 3 lines

I don’t follow how integrating them into BlockBackend automatically solves the problem.

Are you suggesting that blk_* I/O functions should do the accounting instead of the device emulation code?

The thing is, AFAIU, doing that would cause changes in behavior, because the hardware device requests don’t always line up with the BB requests.

What I could do would be to abandon the cookie-based approach altogether, of course; instead creating a completely different tracking object in those BB functions and put those into a list. And then we could decide at a later point if we want to integrate cookies with that. The only downside I see is that this would mean the latency reporting would not line up with the requests reported in the stats, or the histogram.

Hanna

#18 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 32 lines · Hanna Czenczek
Quoted 31 lines · Hanna Czenczek
Quoted 29 lines · Stefan Hajnoczi
Quoted 15 lines · Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep
all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit
the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

Quoted 7 lines

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is
hardly a guarantee this will be kept in order in the future.

I think this patch series already couples the accounting so closely with BlockBackend (i.e. adding the offset field into the cookie struct and adding a BB pointer into the stats struct) that we might as well fully integrate the two. Then callers don't need to manually manage cookies because BlockBackend does that internally and the concerns about lifetimes go away.

Quoted 5 lines
Quoted 5 lines

I don’t follow how integrating them into BlockBackend automatically solves the problem.

Are you suggesting that blk_* I/O functions should do the accounting instead of the device emulation code?

Yes.

Quoted 3 lines

The thing is, AFAIU, doing that would cause changes in behavior, because the hardware device requests don’t always line up with the BB requests.

Did you find a fundamental incompatibility that rules out letting the block layer handles stats for blk_aio_*()?

Quoted 6 lines

What I could do would be to abandon the cookie-based approach altogether, of course; instead creating a completely different tracking object in those BB functions and put those into a list. And then we could decide at a later point if we want to integrate cookies with that. The only downside I see is that this would mean the latency reporting would not line up with the requests reported in the stats, or the histogram.

The tracking object could be a timer! :)

Stefan

#19 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 32 lines · Stefan Hajnoczi
Quoted 31 lines · Hanna Czenczek
Quoted 30 lines · Hanna Czenczek
Quoted 29 lines · Stefan Hajnoczi
Quoted 15 lines · Hanna Czenczek

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep
all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit
the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

Quoted 7 lines

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is
hardly a guarantee this will be kept in order in the future.

I think this patch series already couples the accounting so closely with BlockBackend (i.e. adding the offset field into the cookie struct and adding a BB pointer into the stats struct) that we might as well fully integrate the two. Then callers don't need to manually manage cookies because BlockBackend does that internally and the concerns about lifetimes go away.

Quoted 6 lines
Quoted 5 lines
Quoted 5 lines

I don’t follow how integrating them into BlockBackend automatically solves the problem.

Are you suggesting that blk_* I/O functions should do the accounting instead of the device emulation code?

Yes.

OK, I see.

Quoted 4 lines
Quoted 2 lines

The thing is, AFAIU, doing that would cause changes in behavior, because the hardware device requests don’t always line up with the BB requests.

Did you find a fundamental incompatibility that rules out letting the block layer handles stats for blk_aio_*()?

I mean, a simple thing is that reset requests are currently just not accounted, but they would be accounted then. Or repeated requests after VM stop/cont.

There is also the fact that rerror/werror set to IGNORE means errors are currently accounted as 'done', not 'failed'. That makes… a little sense in the device models, but not really much sense in BB, I feel like.

So I am not sure what you mean by “fundamental incompatibility”. I’m sure if we make it sufficiently ugly, we could reproduce all current peculiarities. We could use the chance to make it cleaner, but that would change the interface, and “cleaner” is always in the eye of the beholder. (Besides the fact that I feel like you are trying to have me open a can of worms, I feel like. :) )

Quoted 7 lines
Quoted 6 lines

What I could do would be to abandon the cookie-based approach altogether, of course; instead creating a completely different tracking object in those BB functions and put those into a list. And then we could decide at a later point if we want to integrate cookies with that. The only downside I see is that this would mean the latency reporting would not line up with the requests reported in the stats, or the histogram.

The tracking object could be a timer! :)

The problem is not timer or sleep, the problem is the lifecycle.

Hanna

#20 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

In reply to Hanna Czenczek

Am 31.08.2026 um 15:52 hat Hanna Czenczek geschrieben:

Quoted 20 lines

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

Quoted 6 lines

So, for now, just implement the simpler solution of only notifying the management layer when the request does complete, so VMs with high latency spikes can at least be identified when they happen without having to regularly check the latency histogram.

Checking only at request completion for now is fine with me; however, the documentation the previous patches added (And possibly their commit messages? Not sure any more.) suggests that the event is emitted while the request is still in flight. So these description need to change to be consistent with the actual behaviour.

Quoted 11 lines
 include/block/accounting.h | 10 ++++++++-
 block/accounting.c         | 42 +++++++++++++++++++++++++++++++++++++-
 blockdev.c                 |  2 +-
 hw/block/block.c           |  2 +-
 4 files changed, 52 insertions(+), 4 deletions(-)
include/block/accounting.h +0 -0
index 025536239e6..ba3a6859cf4 100644

include/block/accounting.h struct BlockAcctStats { · line 95

Quoted 4 lines
include/block/accounting.h +1 -0
@@ -92,6 +92,7 @@ struct BlockAcctStats {
     QSLIST_HEAD(, BlockAcctTimedStats) intervals;
     bool account_invalid;
     bool account_failed;
+    int64_t delay_threshold_ns;

Why signed?

Quoted 54 lines
include/block/accounting.h +8 -1
     BlockLatencyHistogram latency_histogram[BLOCK_MAX_IOTYPE];
 };
 
@@ -103,9 +104,16 @@ typedef struct BlockAcctCookie {
 } BlockAcctCookie;
 
 void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);
+/**
+ * Set up accounting for a block device in @stats.
+ * @alert_ns specifies a latency so that if any request takes longer than that
+ * threshold, a BLOCK_IO_DELAY event will be generated (when that request
+ * completes). Pass 0 to disable.
+ */
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp);
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp);
 void block_acct_cleanup(BlockAcctStats *stats);
 void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
 BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
block/accounting.c +16 -0
index a74551d41f2..debf1924455 100644
@@ -27,8 +27,10 @@
 #include "block/accounting.h"
 #include "block/block_int.h"
 #include "qemu/timer.h"
+#include "system/block-backend.h"
 #include "system/qtest.h"
 #include "qapi/error.h"
+#include "qapi/qapi-events-block.h"
 
 static QEMUClockType clock_type = QEMU_CLOCK_REALTIME;
 static const int qtest_latency_ns = NANOSECONDS_PER_SECOND / 1000;
@@ -62,9 +64,35 @@ static bool bool_from_onoffauto(OnOffAuto val, bool def)
     }
 }
 
+/**
+ * Convert a BlockAcctType into its QAPI equivalent IoAccountingOperation.
+ *
+ * Must only be called for valid BlockAcctType values, i.e. specifically not for
+ * `BLOCK_ACCT_NONE`.
+ */
+static IoAccountingOperation block_acct_qapi_type(enum BlockAcctType type)
+{
+    switch (type) {
+    case BLOCK_ACCT_READ:
+        return IO_ACCOUNTING_OPERATION_READ;
+    case BLOCK_ACCT_WRITE:
+        return IO_ACCOUNTING_OPERATION_WRITE;
+    case BLOCK_ACCT_FLUSH:

block/accounting.c static bool bool_from_onoffauto(OnOffAuto val, bool def) · line 90

Quoted 10 lines
block/accounting.c +10 -0
+        return IO_ACCOUNTING_OPERATION_FLUSH;
+    case BLOCK_ACCT_ZONE_APPEND:
+        return IO_ACCOUNTING_OPERATION_ZONE_APPEND;
+    case BLOCK_ACCT_UNMAP:
+        return IO_ACCOUNTING_OPERATION_UNMAP;
+    case BLOCK_ACCT_NONE:
+    default:
+        g_assert_not_reached();
+    }
+}

Wouldn't it be nice if QAPI could generate the shorter BlockAcctType with BLOCK_ACCT_* on the C side while still keeping the nicer IoAccountingOperation name externally? :-)

(Not a request to change it now, but a wishlist item for Markus.)

Though actually BLOCK_ACCT_* seems to already be possible with 'prefix'. Maybe we could live with the longer IoAccountingOperation type name everywhere and avoid having two separate enums?

Quoted 17 lines
block/accounting.c +3 -1
 bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                       enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp)
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp)
 {
     stats->account_invalid = bool_from_onoffauto(account_invalid,
                                                  stats->account_invalid);
@@ -79,6 +107,7 @@ bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
             block_acct_add_interval(stats, stats_intervals[i]);
         }
     }
+    stats->delay_threshold_ns = alert_ns;
     return true;
 }
 

block/accounting.c static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie, · line 286

Quoted 6 lines
block/accounting.c +3 -0
@@ -252,6 +281,17 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
         return;
     }
 
+    if (stats->delay_threshold_ns && latency_ns > stats->delay_threshold_ns) {
+        g_autofree char *dev_path = blk_get_attached_dev_path(stats->blk);
+        double latency = latency_ns / (double)NANOSECONDS_PER_SECOND;

Wouldn't it be both easier and more reliable to just expose an integer latency-ns in QAPI? I think all other time related values in the block layer interfaces work this way, too.

block/accounting.c static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie, · line 297

Quoted 10 lines
block/accounting.c +7 -0
+        qapi_event_send_block_io_delay(dev_path,
+                                       block_acct_qapi_type(cookie->type),
+                                       latency,
+                                       cookie->offset >= 0, cookie->offset,
+                                       cookie->bytes);
+    }
+
     WITH_QEMU_LOCK_GUARD(&stats->lock) {
         if (failed) {
             stats->failed_ops[cookie->type]++;

Kevin

#21 lore raw

Re: [PATCH 6/9] block/accounting: Emit BLOCK_IO_DELAY event

Quoted 26 lines · Kevin Wolf

Am 31.08.2026 um 15:52 hat Hanna Czenczek geschrieben:

Quoted 25 lines

When a request finishes with a higher latency than a predefined threshold, emit the BLOCK_IO_DELAY event.

Note there would be an alternative, more precise solution: We could keep all active cookies per BlockBackend in a list and repeatedly iterate over it in a background coroutine (woken on a timer so it would wake always exactly when the next request would time out, so it generally stays asleep until there is actually a timeout). This way, we could emit the event exactly when a request crosses the delay threshold, while it is still running; and we could hypothetically even take actions like pausing the VM until the request is done so the guest operating system is shielded from extreme latency spikes.

In practice, this is very complicated because latency cookies are created and finalized all over the place, so it is very hard to guarantee that every block_acct_start() is matched by the right finalization to ensure that cookies are properly removed from the list when they are done. Even if we fix all non-matching places now, there is hardly a guarantee this will be kept in order in the future.

So, for now, just implement the simpler solution of only notifying the management layer when the request does complete, so VMs with high latency spikes can at least be identified when they happen without having to regularly check the latency histogram.

Quoted 6 lines
Quoted 1 line

Checking only at request completion for now is fine with me; however, the documentation the previous patches added (And possibly their commit messages? Not sure any more.) suggests that the event is emitted while the request is still in flight. So these description need to change to be consistent with the actual behaviour.

I tried being a little bit ambiguous so that behavior could change in the future.

But now that you make me think about it, that was a terrible idea. I should fix it to reflect the current behavior and explicitly state that it might do something else, too, in the future. (*If* we think changing behavior is OK, then it should at least be explicit now.)

Quoted 6 lines
Quoted 6 lines
  include/block/accounting.h | 10 ++++++++-
  block/accounting.c         | 42 +++++++++++++++++++++++++++++++++++++-
  blockdev.c                 |  2 +-
  hw/block/block.c           |  2 +-
  4 files changed, 52 insertions(+), 4 deletions(-)
Quoted 10 lines

include/block/accounting.h struct BlockAcctStats { · line 95

Quoted 9 lines
include/block/accounting.h +1 -0
index 025536239e6..ba3a6859cf4 100644
@@ -92,6 +92,7 @@ struct BlockAcctStats {
      QSLIST_HEAD(, BlockAcctTimedStats) intervals;
      bool account_invalid;
      bool account_failed;
+    int64_t delay_threshold_ns;

Why signed?

Because block/accounting.c uses int64_t for all latency values (except for block_acct_queue_depth()).

Quoted 68 lines
Quoted 54 lines
include/block/accounting.h +8 -1
      BlockLatencyHistogram latency_histogram[BLOCK_MAX_IOTYPE];
  };
 
@@ -103,9 +104,16 @@ typedef struct BlockAcctCookie {
  } BlockAcctCookie;
 
  void block_acct_init(BlockBackend *blk, BlockAcctStats *stats);
+/**
+ * Set up accounting for a block device in @stats.
+ * @alert_ns specifies a latency so that if any request takes longer than that
+ * threshold, a BLOCK_IO_DELAY event will be generated (when that request
+ * completes). Pass 0 to disable.
+ */
  bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                        enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp);
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp);
  void block_acct_cleanup(BlockAcctStats *stats);
  void block_acct_add_interval(BlockAcctStats *stats, unsigned interval_length);
  BlockAcctTimedStats *block_acct_interval_next(BlockAcctStats *stats,
block/accounting.c +16 -0
index a74551d41f2..debf1924455 100644
@@ -27,8 +27,10 @@
  #include "block/accounting.h"
  #include "block/block_int.h"
  #include "qemu/timer.h"
+#include "system/block-backend.h"
  #include "system/qtest.h"
  #include "qapi/error.h"
+#include "qapi/qapi-events-block.h"
 
  static QEMUClockType clock_type = QEMU_CLOCK_REALTIME;
  static const int qtest_latency_ns = NANOSECONDS_PER_SECOND / 1000;
@@ -62,9 +64,35 @@ static bool bool_from_onoffauto(OnOffAuto val, bool def)
      }
  }
 
+/**
+ * Convert a BlockAcctType into its QAPI equivalent IoAccountingOperation.
+ *
+ * Must only be called for valid BlockAcctType values, i.e. specifically not for
+ * `BLOCK_ACCT_NONE`.
+ */
+static IoAccountingOperation block_acct_qapi_type(enum BlockAcctType type)
+{
+    switch (type) {
+    case BLOCK_ACCT_READ:
+        return IO_ACCOUNTING_OPERATION_READ;
+    case BLOCK_ACCT_WRITE:
+        return IO_ACCOUNTING_OPERATION_WRITE;
+    case BLOCK_ACCT_FLUSH:

block/accounting.c static bool bool_from_onoffauto(OnOffAuto val, bool def) · line 90

Quoted 10 lines
block/accounting.c +10 -0
+        return IO_ACCOUNTING_OPERATION_FLUSH;
+    case BLOCK_ACCT_ZONE_APPEND:
+        return IO_ACCOUNTING_OPERATION_ZONE_APPEND;
+    case BLOCK_ACCT_UNMAP:
+        return IO_ACCOUNTING_OPERATION_UNMAP;
+    case BLOCK_ACCT_NONE:
+    default:
+        g_assert_not_reached();
+    }
+}

Wouldn't it be nice if QAPI could generate the shorter BlockAcctType with BLOCK_ACCT_* on the C side while still keeping the nicer IoAccountingOperation name externally? :-)

Quoted 5 lines

(Not a request to change it now, but a wishlist item for Markus.)

Though actually BLOCK_ACCT_* seems to already be possible with 'prefix'. Maybe we could live with the longer IoAccountingOperation type name everywhere and avoid having two separate enums?

Probably.

(If not, then IoAccountingOperation were not doing what it’s supposed to be doing.)

I’ll take a look.

Quoted 20 lines
Quoted 20 lines
block/accounting.c +3 -1
  bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
                        enum OnOffAuto account_failed, uint32_t *stats_intervals,
-                      uint32_t num_stats_intervals, Error **errp)
+                      uint32_t num_stats_intervals, int64_t alert_ns,
+                      Error **errp)
  {
      stats->account_invalid = bool_from_onoffauto(account_invalid,
                                                   stats->account_invalid);
@@ -79,6 +107,7 @@ bool block_acct_setup(BlockAcctStats *stats, enum OnOffAuto account_invalid,
              block_acct_add_interval(stats, stats_intervals[i]);
          }
      }
+    stats->delay_threshold_ns = alert_ns;
      return true;
  }
 
@@ -252,6 +281,17 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
          return;
      }
 
Quoted 6 lines

block/accounting.c static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie, · line 286

Quoted 3 lines
block/accounting.c +3 -0
+    if (stats->delay_threshold_ns && latency_ns > stats->delay_threshold_ns) {
+        g_autofree char *dev_path = blk_get_attached_dev_path(stats->blk);
+        double latency = latency_ns / (double)NANOSECONDS_PER_SECOND;

Wouldn't it be both easier and more reliable to just expose an integer latency-ns in QAPI? I think all other time related values in the block layer interfaces work this way, too.

Yup, noted to use nanoseconds exclusively.

Quoted 10 lines

block/accounting.c static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie, · line 297

Quoted 10 lines
block/accounting.c +7 -0
+        qapi_event_send_block_io_delay(dev_path,
+                                       block_acct_qapi_type(cookie->type),
+                                       latency,
+                                       cookie->offset >= 0, cookie->offset,
+                                       cookie->bytes);
+    }
+
      WITH_QEMU_LOCK_GUARD(&stats->lock) {
          if (failed) {
              stats->failed_ops[cookie->type]++;
Quoted 2 lines

Kevin

Thanks for reviewing!

Hanna

#22 lore raw

PATCH 7/9 block: Add delay-alert-ms property

In reply to Hanna Czenczek

This device property allows setting up an I/O latency threshold for when to emit a delay QMP event.

---
 include/hw/block/block.h   |  5 ++++-
 blockdev.c                 | 16 +++++++++++++++-
 hw/block/block.c           |  4 +++-
 tests/qemu-iotests/172.out | 38 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 60 insertions(+), 3 deletions(-)
include/hw/block/block.h +4 -1
index df941df19f2..e7e401dd303 100644
@@ -36,6 +36,7 @@ typedef struct BlockConf {
     BlockdevOnError werror;
     uint32_t num_stats_intervals;
     uint32_t *stats_intervals;
+    uint32_t delay_alert_ms;
 } BlockConf;
 
 static inline unsigned int get_physical_block_exp(BlockConf *conf)
@@ -83,7 +84,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
                             _conf.account_failed, ON_OFF_AUTO_AUTO),    \
     DEFINE_PROP_ARRAY("stats-intervals", _state,                        \
                      _conf.num_stats_intervals, _conf.stats_intervals,  \
-                     qdev_prop_uint32, uint32_t)
+                     qdev_prop_uint32, uint32_t),                       \
+    DEFINE_PROP_UINT32("delay-alert-ms", _state, _conf.delay_alert_ms,  \
+                       0)                                               \
 
 #define DEFINE_BLOCK_PROPERTIES(_state, _conf)                          \
     DEFINE_PROP_DRIVE("drive", _state, _conf.blk),                      \
blockdev.c +15 -1
index 195bac8af01..9c76e89ef38 100644
@@ -496,6 +496,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
     BlockdevDetectZeroesOptions detect_zeroes =
         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
     const char *throttling_group = NULL;
+    uint64_t delay_alert_ns;
 
     /* Check common options by copying from bs_opts to opts, all other options
      * stay in bs_opts for processing by bdrv_open(). */
@@ -580,6 +581,14 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
 
+    delay_alert_ns = qemu_opt_get_number(opts, "delay-alert-ms", 0);
+    if (delay_alert_ns > (uint64_t)INT64_MAX / SCALE_MS) {
+        error_setg(errp, "delay-alert-ms must not exceed %" PRId64,
+                   INT64_MAX / SCALE_MS);
+        goto early_err;
+    }
+    delay_alert_ns *= SCALE_MS;
+
     /* init */
     if ((!file || !*file) && !qdict_size(bs_opts)) {
         BlockBackendRootState *blk_rs;
@@ -618,7 +627,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
         bs->detect_zeroes = detect_zeroes;
 
         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, 0, NULL);
+                         NULL, 0, delay_alert_ns, NULL);
 
         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
             blk_unref(blk);
@@ -3753,6 +3762,11 @@ QemuOptsList qemu_common_drive_opts = {
             .type = QEMU_OPT_BOOL,
             .help = "whether to account for failed I/O operations "
                     "in the statistics",
+        },{
+            .name = "delay-alert-ms",
+            .type = QEMU_OPT_NUMBER,
+            .help = "threshold in ms when to emit an I/O operation "
+                    "delay QMP event",
         },
         { /* end of list */ }
     },
hw/block/block.c +3 -1
index 19301c6f995..be0ea89cb79 100644
@@ -207,6 +207,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
     BlockBackend *blk = conf->blk;
     BlockdevOnError rerror, werror;
     uint64_t perm, shared_perm;
+    uint64_t delay_alert_ns;
     bool wce;
     int ret;
 
@@ -249,9 +250,10 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
     blk_set_enable_write_cache(blk, wce);
     blk_set_on_error(blk, rerror, werror);
 
+    delay_alert_ns = (uint64_t)conf->delay_alert_ms * SCALE_MS;
     if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                           conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, 0, errp)) {
+                          conf->num_stats_intervals, delay_alert_ns, errp)) {
         return false;
     }
     return true;
tests/qemu-iotests/172.out +38 -0
index a023cd407de..ea6a1875eb3 100644
@@ -31,6 +31,7 @@ Testing:
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -61,6 +62,7 @@ Testing: -fda TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -98,6 +100,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -113,6 +116,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -154,6 +158,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -169,6 +174,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -211,6 +217,7 @@ Testing: -fdb
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -226,6 +233,7 @@ Testing: -fdb
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -256,6 +264,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -293,6 +302,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -308,6 +318,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -349,6 +360,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -364,6 +376,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -409,6 +422,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -446,6 +460,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,unit=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -483,6 +498,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -498,6 +514,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -549,6 +566,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -564,6 +582,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -606,6 +625,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -621,6 +641,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -663,6 +684,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 1 (0x1)
@@ -678,6 +700,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -720,6 +743,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 1 (0x1)
@@ -735,6 +759,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -786,6 +811,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -801,6 +827,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -843,6 +870,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -858,6 +886,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -906,6 +935,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -global floppy.drive=none0 -device
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -973,6 +1003,7 @@ Testing: -device floppy
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 Testing: -device floppy,drive-type=120
@@ -1000,6 +1031,7 @@ Testing: -device floppy,drive-type=120
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "120"
 
 Testing: -device floppy,drive-type=144
@@ -1027,6 +1059,7 @@ Testing: -device floppy,drive-type=144
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 
 Testing: -device floppy,drive-type=288
@@ -1054,6 +1087,7 @@ Testing: -device floppy,drive-type=288
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -1084,6 +1118,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "120"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1121,6 +1156,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1161,6 +1197,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,logical
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1198,6 +1235,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,physica
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
Signature · 1 line
2.55.0
#23 lore raw

Re: [PATCH 7/9] block: Add delay-alert-ms property

Quoted 24 lines · Hanna Czenczek

This device property allows setting up an I/O latency threshold for when to emit a delay QMP event.

---
 include/hw/block/block.h   |  5 ++++-
 blockdev.c                 | 16 +++++++++++++++-
 hw/block/block.c           |  4 +++-
 tests/qemu-iotests/172.out | 38 ++++++++++++++++++++++++++++++++++++++
 4 files changed, 60 insertions(+), 3 deletions(-)
include/hw/block/block.h +1 -0
index df941df19f2..e7e401dd303 100644
@@ -36,6 +36,7 @@ typedef struct BlockConf {
     BlockdevOnError werror;
     uint32_t num_stats_intervals;
     uint32_t *stats_intervals;
+    uint32_t delay_alert_ms;
 } BlockConf;
 
 static inline unsigned int get_physical_block_exp(BlockConf *conf)

include/hw/block/block.h static inline unsigned int get_physical_block_exp(BlockConf *conf) · line 89

Quoted 7 lines
include/hw/block/block.h +3 -1
@@ -83,7 +84,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
                             _conf.account_failed, ON_OFF_AUTO_AUTO),    \
     DEFINE_PROP_ARRAY("stats-intervals", _state,                        \
                      _conf.num_stats_intervals, _conf.stats_intervals,  \
-                     qdev_prop_uint32, uint32_t)
+                     qdev_prop_uint32, uint32_t),                       \
+    DEFINE_PROP_UINT32("delay-alert-ms", _state, _conf.delay_alert_ms,  \
+                       0)                                               \

The latency histogram feature uses nanoseconds (64-bit integer) whereas this patch series uses delay-alert-ms (uint32) and a double floating-point seconds value in the QMP event. Maybe stick to 64-bit integer nanoseconds everywhere for consistency?

Quoted 386 lines
include/hw/block/block.h +0 -0
 #define DEFINE_BLOCK_PROPERTIES(_state, _conf)                          \
     DEFINE_PROP_DRIVE("drive", _state, _conf.blk),                      \
blockdev.c +15 -1
index 195bac8af01..9c76e89ef38 100644
@@ -496,6 +496,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
     BlockdevDetectZeroesOptions detect_zeroes =
         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
     const char *throttling_group = NULL;
+    uint64_t delay_alert_ns;
 
     /* Check common options by copying from bs_opts to opts, all other options
      * stay in bs_opts for processing by bdrv_open(). */
@@ -580,6 +581,14 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
     read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
 
+    delay_alert_ns = qemu_opt_get_number(opts, "delay-alert-ms", 0);
+    if (delay_alert_ns > (uint64_t)INT64_MAX / SCALE_MS) {
+        error_setg(errp, "delay-alert-ms must not exceed %" PRId64,
+                   INT64_MAX / SCALE_MS);
+        goto early_err;
+    }
+    delay_alert_ns *= SCALE_MS;
+
     /* init */
     if ((!file || !*file) && !qdict_size(bs_opts)) {
         BlockBackendRootState *blk_rs;
@@ -618,7 +627,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
         bs->detect_zeroes = detect_zeroes;
 
         block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, 0, NULL);
+                         NULL, 0, delay_alert_ns, NULL);
 
         if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
             blk_unref(blk);
@@ -3753,6 +3762,11 @@ QemuOptsList qemu_common_drive_opts = {
             .type = QEMU_OPT_BOOL,
             .help = "whether to account for failed I/O operations "
                     "in the statistics",
+        },{
+            .name = "delay-alert-ms",
+            .type = QEMU_OPT_NUMBER,
+            .help = "threshold in ms when to emit an I/O operation "
+                    "delay QMP event",
         },
         { /* end of list */ }
     },
hw/block/block.c +3 -1
index 19301c6f995..be0ea89cb79 100644
@@ -207,6 +207,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
     BlockBackend *blk = conf->blk;
     BlockdevOnError rerror, werror;
     uint64_t perm, shared_perm;
+    uint64_t delay_alert_ns;
     bool wce;
     int ret;
 
@@ -249,9 +250,10 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
     blk_set_enable_write_cache(blk, wce);
     blk_set_on_error(blk, rerror, werror);
 
+    delay_alert_ns = (uint64_t)conf->delay_alert_ms * SCALE_MS;
     if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                           conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, 0, errp)) {
+                          conf->num_stats_intervals, delay_alert_ns, errp)) {
         return false;
     }
     return true;
tests/qemu-iotests/172.out +38 -0
index a023cd407de..ea6a1875eb3 100644
@@ -31,6 +31,7 @@ Testing:
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -61,6 +62,7 @@ Testing: -fda TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -98,6 +100,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -113,6 +116,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -154,6 +158,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -169,6 +174,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -211,6 +217,7 @@ Testing: -fdb
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -226,6 +233,7 @@ Testing: -fdb
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -256,6 +264,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -293,6 +302,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -308,6 +318,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -349,6 +360,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -364,6 +376,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -409,6 +422,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -446,6 +460,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,unit=1
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -483,6 +498,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -498,6 +514,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -549,6 +566,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -564,6 +582,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -606,6 +625,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -621,6 +641,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -663,6 +684,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 1 (0x1)
@@ -678,6 +700,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -720,6 +743,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 1 (0x1)
@@ -735,6 +759,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -786,6 +811,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -801,6 +827,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -843,6 +870,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
               dev: floppy, id ""
                 unit = 0 (0x0)
@@ -858,6 +886,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/unattached/device[N]
@@ -906,6 +935,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -global floppy.drive=none0 -device
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -973,6 +1003,7 @@ Testing: -device floppy
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 Testing: -device floppy,drive-type=120
@@ -1000,6 +1031,7 @@ Testing: -device floppy,drive-type=120
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "120"
 
 Testing: -device floppy,drive-type=144
@@ -1027,6 +1059,7 @@ Testing: -device floppy,drive-type=144
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 
 Testing: -device floppy,drive-type=288
@@ -1054,6 +1087,7 @@ Testing: -device floppy,drive-type=288
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 
 
@@ -1084,6 +1118,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "120"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1121,6 +1156,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "288"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1161,6 +1197,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,logical
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
@@ -1198,6 +1235,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,physica
                 account-invalid = "auto"
                 account-failed = "auto"
                 stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                 drive-type = "144"
 none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
     Attached to:      /machine/peripheral-anon/device[N]
Signature · 1 line
2.55.0
#24 lore raw

Re: [PATCH 7/9] block: Add delay-alert-ms property

Quoted 23 lines · Stefan Hajnoczi
Quoted 22 lines · Hanna Czenczek

This device property allows setting up an I/O latency threshold for when to emit a delay QMP event.

---
  include/hw/block/block.h   |  5 ++++-
  blockdev.c                 | 16 +++++++++++++++-
  hw/block/block.c           |  4 +++-
  tests/qemu-iotests/172.out | 38 ++++++++++++++++++++++++++++++++++++++
  4 files changed, 60 insertions(+), 3 deletions(-)
include/hw/block/block.h +1 -0
index df941df19f2..e7e401dd303 100644
@@ -36,6 +36,7 @@ typedef struct BlockConf {
      BlockdevOnError werror;
      uint32_t num_stats_intervals;
      uint32_t *stats_intervals;
+    uint32_t delay_alert_ms;
  } BlockConf;
 
Quoted 13 lines

include/hw/block/block.h static inline unsigned int get_physical_block_exp(BlockConf *conf) · line 89

Quoted 9 lines
include/hw/block/block.h +3 -1
  static inline unsigned int get_physical_block_exp(BlockConf *conf)
@@ -83,7 +84,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
                              _conf.account_failed, ON_OFF_AUTO_AUTO),    \
      DEFINE_PROP_ARRAY("stats-intervals", _state,                        \
                       _conf.num_stats_intervals, _conf.stats_intervals,  \
-                     qdev_prop_uint32, uint32_t)
+                     qdev_prop_uint32, uint32_t),                       \
+    DEFINE_PROP_UINT32("delay-alert-ms", _state, _conf.delay_alert_ms,  \
+                       0)                                               \

The latency histogram feature uses nanoseconds (64-bit integer) whereas this patch series uses delay-alert-ms (uint32) and a double floating-point seconds value in the QMP event. Maybe stick to 64-bit integer nanoseconds everywhere for consistency?

I don’t have technical objections because doing so is easy, of course. Personally, I found nanoseconds really unwieldy to specify here. But I suppose if @block-latency-histogram-set does the same, then I might as well.

Hanna

Quoted 386 lines
Quoted 386 lines
include/hw/block/block.h +0 -0
  #define DEFINE_BLOCK_PROPERTIES(_state, _conf)                          \
      DEFINE_PROP_DRIVE("drive", _state, _conf.blk),                      \
blockdev.c +15 -1
index 195bac8af01..9c76e89ef38 100644
@@ -496,6 +496,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
      BlockdevDetectZeroesOptions detect_zeroes =
          BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
      const char *throttling_group = NULL;
+    uint64_t delay_alert_ns;
 
      /* Check common options by copying from bs_opts to opts, all other options
       * stay in bs_opts for processing by bdrv_open(). */
@@ -580,6 +581,14 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
 
      read_only = qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false);
 
+    delay_alert_ns = qemu_opt_get_number(opts, "delay-alert-ms", 0);
+    if (delay_alert_ns > (uint64_t)INT64_MAX / SCALE_MS) {
+        error_setg(errp, "delay-alert-ms must not exceed %" PRId64,
+                   INT64_MAX / SCALE_MS);
+        goto early_err;
+    }
+    delay_alert_ns *= SCALE_MS;
+
      /* init */
      if ((!file || !*file) && !qdict_size(bs_opts)) {
          BlockBackendRootState *blk_rs;
@@ -618,7 +627,7 @@ static BlockBackend *blockdev_init(const char *file, QDict *bs_opts,
          bs->detect_zeroes = detect_zeroes;
 
          block_acct_setup(blk_get_stats(blk), account_invalid, account_failed,
-                         NULL, 0, 0, NULL);
+                         NULL, 0, delay_alert_ns, NULL);
 
          if (!parse_stats_intervals(blk_get_stats(blk), interval_list, errp)) {
              blk_unref(blk);
@@ -3753,6 +3762,11 @@ QemuOptsList qemu_common_drive_opts = {
              .type = QEMU_OPT_BOOL,
              .help = "whether to account for failed I/O operations "
                      "in the statistics",
+        },{
+            .name = "delay-alert-ms",
+            .type = QEMU_OPT_NUMBER,
+            .help = "threshold in ms when to emit an I/O operation "
+                    "delay QMP event",
          },
          { /* end of list */ }
      },
hw/block/block.c +3 -1
index 19301c6f995..be0ea89cb79 100644
@@ -207,6 +207,7 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
      BlockBackend *blk = conf->blk;
      BlockdevOnError rerror, werror;
      uint64_t perm, shared_perm;
+    uint64_t delay_alert_ns;
      bool wce;
      int ret;
 
@@ -249,9 +250,10 @@ bool blkconf_apply_backend_options(BlockConf *conf, bool readonly,
      blk_set_enable_write_cache(blk, wce);
      blk_set_on_error(blk, rerror, werror);
 
+    delay_alert_ns = (uint64_t)conf->delay_alert_ms * SCALE_MS;
      if (!block_acct_setup(blk_get_stats(blk), conf->account_invalid,
                            conf->account_failed, conf->stats_intervals,
-                          conf->num_stats_intervals, 0, errp)) {
+                          conf->num_stats_intervals, delay_alert_ns, errp)) {
          return false;
      }
      return true;
tests/qemu-iotests/172.out +38 -0
index a023cd407de..ea6a1875eb3 100644
@@ -31,6 +31,7 @@ Testing:
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
 
 
@@ -61,6 +62,7 @@ Testing: -fda TEST_DIR/t.qcow2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -98,6 +100,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -113,6 +116,7 @@ Testing: -fdb TEST_DIR/t.qcow2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
  floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -154,6 +158,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -169,6 +174,7 @@ Testing: -fda TEST_DIR/t.qcow2 -fdb TEST_DIR/t.qcow2.2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -211,6 +217,7 @@ Testing: -fdb
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -226,6 +233,7 @@ Testing: -fdb
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
 
 
@@ -256,6 +264,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -293,6 +302,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -308,6 +318,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2,index=1
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
  floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -349,6 +360,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -364,6 +376,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=floppy,file=TEST_DIR/t
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -409,6 +422,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -446,6 +460,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,unit=1
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -483,6 +498,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -498,6 +514,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qco
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -549,6 +566,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -564,6 +582,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -606,6 +625,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -621,6 +641,7 @@ Testing: -fda TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -663,6 +684,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 1 (0x1)
@@ -678,6 +700,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -720,6 +743,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 1 (0x1)
@@ -735,6 +759,7 @@ Testing: -fdb TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.qcow2.2 -device fl
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy1 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -786,6 +811,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -801,6 +827,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -843,6 +870,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
                dev: floppy, id ""
                  unit = 0 (0x0)
@@ -858,6 +886,7 @@ Testing: -drive if=floppy,file=TEST_DIR/t.qcow2 -drive if=none,file=TEST_DIR/t.q
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  floppy0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/unattached/device[N]
@@ -906,6 +935,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -global floppy.drive=none0 -device
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -973,6 +1003,7 @@ Testing: -device floppy
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
 
  Testing: -device floppy,drive-type=120
@@ -1000,6 +1031,7 @@ Testing: -device floppy,drive-type=120
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "120"
 
  Testing: -device floppy,drive-type=144
@@ -1027,6 +1059,7 @@ Testing: -device floppy,drive-type=144
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
 
  Testing: -device floppy,drive-type=288
@@ -1054,6 +1087,7 @@ Testing: -device floppy,drive-type=288
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
 
 
@@ -1084,6 +1118,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "120"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -1121,6 +1156,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,drive-t
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "288"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -1161,6 +1197,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,logical
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
@@ -1198,6 +1235,7 @@ Testing: -drive if=none,file=TEST_DIR/t.qcow2 -device floppy,drive=none0,physica
                  account-invalid = "auto"
                  account-failed = "auto"
                  stats-intervals = <null>
+                delay-alert-ms = 0 (0x0)
                  drive-type = "144"
  none0 (NODE_NAME): TEST_DIR/t.qcow2 (qcow2)
      Attached to:      /machine/peripheral-anon/device[N]
Signature · 1 line
2.55.0
#25 lore raw

Re: [PATCH 7/9] block: Add delay-alert-ms property

Am 16.09.2026 um 10:17 hat Hanna Czenczek geschrieben:

Quoted 37 lines · Stefan Hajnoczi
Quoted 27 lines · Hanna Czenczek
Quoted 26 lines

This device property allows setting up an I/O latency threshold for when to emit a delay QMP event.

---
  include/hw/block/block.h   |  5 ++++-
  blockdev.c                 | 16 +++++++++++++++-
  hw/block/block.c           |  4 +++-
  tests/qemu-iotests/172.out | 38 ++++++++++++++++++++++++++++++++++++++
  4 files changed, 60 insertions(+), 3 deletions(-)
include/hw/block/block.h +1 -0
index df941df19f2..e7e401dd303 100644
@@ -36,6 +36,7 @@ typedef struct BlockConf {
      BlockdevOnError werror;
      uint32_t num_stats_intervals;
      uint32_t *stats_intervals;
+    uint32_t delay_alert_ms;
  } BlockConf;
  static inline unsigned int get_physical_block_exp(BlockConf *conf)
@@ -83,7 +84,9 @@ static inline unsigned int get_physical_block_exp(BlockConf *conf)
                              _conf.account_failed, ON_OFF_AUTO_AUTO),    \
      DEFINE_PROP_ARRAY("stats-intervals", _state,                        \
                       _conf.num_stats_intervals, _conf.stats_intervals,  \
Quoted 8 lines

include/hw/block/block.h static inline unsigned int get_physical_block_exp(BlockConf *conf) · line 89

Quoted 4 lines
include/hw/block/block.h +3 -1
-                     qdev_prop_uint32, uint32_t)
+                     qdev_prop_uint32, uint32_t),                       \
+    DEFINE_PROP_UINT32("delay-alert-ms", _state, _conf.delay_alert_ms,  \
+                       0)                                               \

The latency histogram feature uses nanoseconds (64-bit integer) whereas this patch series uses delay-alert-ms (uint32) and a double floating-point seconds value in the QMP event. Maybe stick to 64-bit integer nanoseconds everywhere for consistency?

Quoted 3 lines

I don’t have technical objections because doing so is easy, of course. Personally, I found nanoseconds really unwieldy to specify here. But I suppose if @block-latency-histogram-set does the same, then I might as well.

I don't expect this to be used much by human users, and for a machine interface, what makes things unwieldy is having to keep track of which value has which unit instead of just sticking to one unit everywhere.

I had the same comment before seeing that Stefan already pointed it out.

Kevin

#26 lore raw

PATCH 8/9 block/accounting: Move latency_ns override down

In reply to Hanna Czenczek

I am not quite sure why latency_ns is overridden by a fixed value in qtest mode because personally, I find it much better if I can individually change requests' latency by modifying the qtest clock.

But I'm not going to change existing behavior for the histogram and such, so I will just move this override after the latency has been evaluated regarding a potential BLOCK_IO_DELAY event.

---
 block/accounting.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
block/accounting.c +4 -4
index debf1924455..223becd2e04 100644
@@ -271,10 +271,6 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
     int64_t time_ns = qemu_clock_get_ns(clock_type);
     int64_t latency_ns = time_ns - cookie->start_time_ns;
 
-    if (qtest_enabled()) {
-        latency_ns = qtest_latency_ns;
-    }
-
     assert(cookie->type < BLOCK_MAX_IOTYPE);
 
     if (cookie->type == BLOCK_ACCT_NONE) {
@@ -292,6 +288,10 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
                                        cookie->bytes);
     }
 
+    if (qtest_enabled()) {
+        latency_ns = qtest_latency_ns;
+    }
+
     WITH_QEMU_LOCK_GUARD(&stats->lock) {
         if (failed) {
             stats->failed_ops[cookie->type]++;
Signature · 1 line
2.55.0
#27 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Quoted 3 lines · Hanna Czenczek

I am not quite sure why latency_ns is overridden by a fixed value in qtest mode because personally, I find it much better if I can individually change requests' latency by modifying the qtest clock.

It looks like tests/qemu-iotests/136 relies on a hardcoded constant so it can check min/max/avg against known values.

Quoted 4 lines

But I'm not going to change existing behavior for the histogram and such, so I will just move this override after the latency has been evaluated regarding a potential BLOCK_IO_DELAY event.

That's fine if you aren't taking the same testing approach as tests/qemu-iotests/136. I think the benefit of hardcoding the value for testing is that it would become possible to trigger the latency threshold without worrying about timing in the test environment.

Quoted 35 lines
---
 block/accounting.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
block/accounting.c +4 -4
index debf1924455..223becd2e04 100644
@@ -271,10 +271,6 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
     int64_t time_ns = qemu_clock_get_ns(clock_type);
     int64_t latency_ns = time_ns - cookie->start_time_ns;
 
-    if (qtest_enabled()) {
-        latency_ns = qtest_latency_ns;
-    }
-
     assert(cookie->type < BLOCK_MAX_IOTYPE);
 
     if (cookie->type == BLOCK_ACCT_NONE) {
@@ -292,6 +288,10 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
                                        cookie->bytes);
     }
 
+    if (qtest_enabled()) {
+        latency_ns = qtest_latency_ns;
+    }
+
     WITH_QEMU_LOCK_GUARD(&stats->lock) {
         if (failed) {
             stats->failed_ops[cookie->type]++;
Signature · 1 line
2.55.0
#28 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Quoted 7 lines · Stefan Hajnoczi
Quoted 3 lines · Hanna Czenczek

I am not quite sure why latency_ns is overridden by a fixed value in qtest mode because personally, I find it much better if I can individually change requests' latency by modifying the qtest clock.

It looks like tests/qemu-iotests/136 relies on a hardcoded constant so it can check min/max/avg against known values.

Quoted 7 lines
Quoted 3 lines

But I'm not going to change existing behavior for the histogram and such, so I will just move this override after the latency has been evaluated regarding a potential BLOCK_IO_DELAY event.

That's fine if you aren't taking the same testing approach as tests/qemu-iotests/136. I think the benefit of hardcoding the value for testing is that it would become possible to trigger the latency threshold without worrying about timing in the test environment.

FWIW, as far as I understand, in qtest mode, clock_type is QEMU_CLOCK_VIRTUAL, so it is not dependent on the test environment anyway, but on the qtest clock. That’s why I don’t understand the fixed latency value, but maybe it was just easier this way for 136 because this way it does not have to do a clock_step for each request.

Hanna

Quoted 34 lines
Quoted 34 lines
---
  block/accounting.c | 8 ++++----
  1 file changed, 4 insertions(+), 4 deletions(-)
block/accounting.c +4 -4
index debf1924455..223becd2e04 100644
@@ -271,10 +271,6 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
      int64_t time_ns = qemu_clock_get_ns(clock_type);
      int64_t latency_ns = time_ns - cookie->start_time_ns;
 
-    if (qtest_enabled()) {
-        latency_ns = qtest_latency_ns;
-    }
-
      assert(cookie->type < BLOCK_MAX_IOTYPE);
 
      if (cookie->type == BLOCK_ACCT_NONE) {
@@ -292,6 +288,10 @@ static void block_account_one_io(BlockAcctStats *stats, BlockAcctCookie *cookie,
                                         cookie->bytes);
      }
 
+    if (qtest_enabled()) {
+        latency_ns = qtest_latency_ns;
+    }
+
      WITH_QEMU_LOCK_GUARD(&stats->lock) {
          if (failed) {
              stats->failed_ops[cookie->type]++;
Signature · 1 line
2.55.0
#29 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Quoted 16 lines · Hanna Czenczek
Quoted 7 lines · Stefan Hajnoczi
Quoted 3 lines · Hanna Czenczek

I am not quite sure why latency_ns is overridden by a fixed value in qtest mode because personally, I find it much better if I can individually change requests' latency by modifying the qtest clock.

It looks like tests/qemu-iotests/136 relies on a hardcoded constant so it can check min/max/avg against known values.

Quoted 7 lines
Quoted 3 lines

But I'm not going to change existing behavior for the histogram and such, so I will just move this override after the latency has been evaluated regarding a potential BLOCK_IO_DELAY event.

That's fine if you aren't taking the same testing approach as tests/qemu-iotests/136. I think the benefit of hardcoding the value for testing is that it would become possible to trigger the latency threshold without worrying about timing in the test environment.

Quoted 5 lines

FWIW, as far as I understand, in qtest mode, clock_type is QEMU_CLOCK_VIRTUAL, so it is not dependent on the test environment anyway, but on the qtest clock. That’s why I don’t understand the fixed latency value, but maybe it was just easier this way for 136 because this way it does not have to do a clock_step for each request.

Yes, I think you're right. I'm not sure either. :/

Stefan

#30 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Am 21.09.2026 um 22:42 hat Stefan Hajnoczi geschrieben:

Quoted 17 lines · Hanna Czenczek
Quoted 16 lines · Stefan Hajnoczi
Quoted 14 lines · Hanna Czenczek
Quoted 3 lines

I am not quite sure why latency_ns is overridden by a fixed value in qtest mode because personally, I find it much better if I can individually change requests' latency by modifying the qtest clock.

It looks like tests/qemu-iotests/136 relies on a hardcoded constant so it can check min/max/avg against known values.

Quoted 3 lines

But I'm not going to change existing behavior for the histogram and such, so I will just move this override after the latency has been evaluated regarding a potential BLOCK_IO_DELAY event.

That's fine if you aren't taking the same testing approach as tests/qemu-iotests/136. I think the benefit of hardcoding the value for testing is that it would become possible to trigger the latency threshold without worrying about timing in the test environment.

Quoted 7 lines
Quoted 5 lines

FWIW, as far as I understand, in qtest mode, clock_type is QEMU_CLOCK_VIRTUAL, so it is not dependent on the test environment anyway, but on the qtest clock. That’s why I don’t understand the fixed latency value, but maybe it was just easier this way for 136 because this way it does not have to do a clock_step for each request.

Yes, I think you're right. I'm not sure either. :/

What's even stranger is that both things were introduced in the same commit. But it seems clearly related to 136 because the change was made right before the test was added.

Berto, do you remember why you didn't rely just on clock_step?

I suppose we could just try to change the behaviour and fix up 136. Behaviour under qtest is something I'd be okay with changing.

Kevin

#31 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Quoted 7 lines · Kevin Wolf

Am 21.09.2026 um 22:42 hat Stefan Hajnoczi geschrieben:

Quoted 1 line · Hanna Czenczek

What's even stranger is that both things were introduced in the same commit. But it seems clearly related to 136 because the change was made right before the test was added.

Berto, do you remember why you didn't rely just on clock_step?

No, sorry, I don't remember :-/ I guess I wasn't familiar with that function? 136 was one of the first tests that I wrote.

Berto

#32 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Am 22.09.2026 um 15:44 hat Alberto Garcia geschrieben:

Quoted 11 lines · Kevin Wolf
Quoted 7 lines

Am 21.09.2026 um 22:42 hat Stefan Hajnoczi geschrieben:

Quoted 1 line · Hanna Czenczek

What's even stranger is that both things were introduced in the same commit. But it seems clearly related to 136 because the change was made right before the test was added.

Berto, do you remember why you didn't rely just on clock_step?

No, sorry, I don't remember :-/ I guess I wasn't familiar with that function? 136 was one of the first tests that I wrote.

I thought so at first, too, but then I saw that other places in the same test do use it.

Anyway, thanks for the quick reply. Then let's just try out what breaks if we change it. :-)

Kevin

#33 lore raw

Re: [PATCH 8/9] block/accounting: Move latency_ns override down

Quoted 8 lines · Kevin Wolf

Am 22.09.2026 um 15:44 hat Alberto Garcia geschrieben:

Quoted 7 lines · Kevin Wolf
Quoted 6 lines

Am 21.09.2026 um 22:42 hat Stefan Hajnoczi geschrieben:

Quoted 1 line · Hanna Czenczek

What's even stranger is that both things were introduced in the same commit. But it seems clearly related to 136 because the change was made right before the test was added.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Berto, do you remember why you didn't rely just on clock_step?

No, sorry, I don't remember :-/ I guess I wasn't familiar with that function? 136 was one of the first tests that I wrote.

I thought so at first, too, but then I saw that other places in the same test do use it.

Anyway, thanks for the quick reply. Then let's just try out what breaks if we change it. :-)

Yup, I’ll take a look.

(Thanks for chiming in, Berto!)

Hanna

#34 lore raw

PATCH 9/9 iotests: Add delay-alert test

In reply to Hanna Czenczek

Test delay-alert-ms via HMP qemu-io (break, aio_read/write, resume) on a null node (with blkdebug).

---
 tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
 tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
 2 files changed, 182 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/delay-alert
 create mode 100644 tests/qemu-iotests/tests/delay-alert.out
tests/qemu-iotests/tests/delay-alert new file +136 -0
new file mode 100755
index 00000000000..d98f537e802
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+# group: rw
+#
+# Test the I/O delay QMP event.
+#
+# Copyright (C) 2026 Red Hat, Inc.
+#
+# SPDX-License-Identifier: GPL-2.0-or-later
+#
+# Creator/Owner: Hanna Czenczek <[email protected]>
+
+import asyncio
+import iotests
+from iotests import filter_qmp_event, log
+
+DELAY_ALERT_MS = 5000 # ms
+EPSILON_MS = 50 # ms -- small delta that can safely be added/subtracted
+NS_PER_MS = 1000 * 1000
+
+qtest_clock = 0 # ms
+
+iotests.script_initialize()
+
+def vm_qemu_io(qvm, virtio_blk_id, cmd):
+    log(f'[HMP] qemu-io to {virtio_blk_id}: {cmd}')
+    cmd = f'qemu-io -d {virtio_blk_id}/virtio-backend "{cmd}"'
+    log(qvm.qmp('human-monitor-command', command_line=cmd))
+
+def advance_clock_to(qvm, clock_ms):
+    # Retain the current absolute clock time so we can step *to* a specific
+    # time via `clock_step`. pylint does not like global much, but this is a
+    # test script, and not using global would just make this more complicated.
+    global qtest_clock # pylint: disable=global-statement
+
+    msecs = clock_ms - qtest_clock
+    log(f'[qtest] clock_step {msecs}ms to {clock_ms}ms')
+    qvm.qtest(f'clock_step {msecs * NS_PER_MS}')
+    qtest_clock += msecs
+
+def assert_no_event(qvm, event_name):
+    try:
+        evt = qvm.event_wait(event_name, timeout=0.1)
+        assert evt is None, f'Unexpected {event_name} event: {evt}'
+    except asyncio.TimeoutError:
+        pass
+    log(f'(No {event_name} event)')
+
+with iotests.VM() as vm:
+    # Cannot use null-co.latency-ns, as that uses realtime (not qtest time)
+    # Need to use raw to get the read_aio event working
+    vm.add_blockdev(vm.qmp_to_opts({
+        'driver': 'raw',
+        'node-name': 'test-node',
+        'file': {
+            'driver': 'blkdebug',
+            'image': {
+                'driver': 'null-co',
+            },
+        },
+    }))
+
+    vm.launch()
+
+    log(f'[QMP] device_add id=vblk delay-alert-ms={DELAY_ALERT_MS}')
+    log(vm.qmp('device_add', {
+        'driver': 'virtio-blk',
+        'id': 'vblk',
+        'drive': 'test-node',
+        'delay-alert-ms': DELAY_ALERT_MS,
+    }))
+
+    try:
+        # Test different operation types. Flushing and discarding would also be
+        # nice but `aio_flush` does not actually execute a flush, and there is
+        # no blkdebug event for discarding.
+
+        vm_qemu_io(vm, 'vblk', 'break read_aio read_0')
+        vm_qemu_io(vm, 'vblk', 'aio_read 0k 4k')
+        vm_qemu_io(vm, 'vblk', 'wait_break read_0')
+
+        vm_qemu_io(vm, 'vblk', 'break write_aio write_0')
+        vm_qemu_io(vm, 'vblk', 'aio_write 4k 4k')
+        vm_qemu_io(vm, 'vblk', 'wait_break write_0')
+
+        vm_qemu_io(vm, 'vblk', 'break read_aio read_1')
+        vm_qemu_io(vm, 'vblk', 'aio_read 8k 4k')
+        vm_qemu_io(vm, 'vblk', 'wait_break read_1')
+
+        vm_qemu_io(vm, 'vblk', 'break write_aio write_1')
+        vm_qemu_io(vm, 'vblk', 'aio_write 12k 4k')
+        vm_qemu_io(vm, 'vblk', 'wait_break write_1')
+
+        # Assert there is no event before the step
+        advance_clock_to(vm, DELAY_ALERT_MS - EPSILON_MS)
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+
+        # Even when a request finishes here
+        vm_qemu_io(vm, 'vblk', 'resume read_0')
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+
+        # Crossing the threshold alone does not cause an event to fire
+        advance_clock_to(vm, DELAY_ALERT_MS + EPSILON_MS)
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+
+        # Only when the request finishes past the threshold do we see one
+        vm_qemu_io(vm, 'vblk', 'resume write_0')
+        event = vm.event_wait('BLOCK_IO_DELAY')
+        assert event is not None
+        log(event, filters=[filter_qmp_event])
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+
+        # Check that we get the event immediately on completion
+        vm_qemu_io(vm, 'vblk', 'resume read_1')
+        event = vm.event_wait('BLOCK_IO_DELAY')
+        assert event is not None
+        log(event, filters=[filter_qmp_event])
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+
+        # And the same for the final request, but add another bit of delay
+        advance_clock_to(vm, DELAY_ALERT_MS + 2 * EPSILON_MS)
+        vm_qemu_io(vm, 'vblk', 'resume write_1')
+        event = vm.event_wait('BLOCK_IO_DELAY')
+        assert event is not None
+        log(event, filters=[filter_qmp_event])
+        assert_no_event(vm, 'BLOCK_IO_DELAY')
+    except Exception as exc:
+        # The VM will not be able to quit without these requests
+        # finished, which (without this block) would make the test
+        # hang instead of exit if something unexpected goes wrong
+        vm_qemu_io(vm, 'vblk', 'resume read_0')
+        vm_qemu_io(vm, 'vblk', 'resume write_0')
+        vm_qemu_io(vm, 'vblk', 'resume read_1')
+        vm_qemu_io(vm, 'vblk', 'resume write_1')
+        raise exc
+
+    vm.shutdown()
tests/qemu-iotests/tests/delay-alert.out new file +46 -0

46 lines not on this page · raw message

Signature · 1 line
2.55.0
Reviewed-by on v1 9/9
#35 lore raw

Re: [PATCH 9/9] iotests: Add delay-alert test

Quoted 10 lines · Hanna Czenczek

Test delay-alert-ms via HMP qemu-io (break, aio_read/write, resume) on a null node (with blkdebug).

---
 tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
 tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
 2 files changed, 182 insertions(+)
 create mode 100755 tests/qemu-iotests/tests/delay-alert
 create mode 100644 tests/qemu-iotests/tests/delay-alert.out
#36 lore raw
In reply to Hanna Czenczek
Quoted 10 lines · Hanna Czenczek

Based-on: <[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

Quoted 8 lines

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

The API is already weird because devices use:

  block_acct_failed(blk_get_stats(s->blk), &req->acct);

i.e. why does the device have to reach into s->blk to access the stats? If the stats belong to s->blk, then s->blk should do the accounting during the request lifetime.

This would require a redesign of not just the cookie API, but also the error policy API. There is also a wrinkle in that virtio-blk merges I/O requests and accounts the merges.

Quoted 8 lines

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

Does this achieve the goal of warning when requests exceed a threshold? When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Quoted 52 lines

(PS: The nice thing about throwing an alert while the request is still going on would be that it could allow us to also stop the VM in case of excessive latency, before the request completes, so the guest would be shielded from such excessive latency. This might be useful for Windows guests that just have a maximum request lantency before throwing a BSOD.)

Hanna Czenczek (9):
block/accounting: Add offset to BlockAcctCookie qapi/block: Add IoAccountingOperation enum qapi/block: Add BLOCK_IO_DELAY event
block-backend: Public blk_get_attached_dev_path() block/accounting: Add BB field to latency checker block/accounting: Emit BLOCK_IO_DELAY event
block: Add delay-alert-ms property block/accounting: Move latency_ns override down
iotests: Add delay-alert test

 qapi/block.json                          |  52 +++++++++
 include/block/accounting.h               |  20 +++-
 include/hw/block/block.h                 |   5 +-
 include/system/block-backend-io.h        |   9 ++
 include/system/dma.h                     |   2 +-
 block/accounting.c                       |  60 ++++++++--
 block/block-backend.c                    |   8 +-
 blockdev.c                               |  16 ++-
 hw/block/block.c                         |   4 +-
 hw/block/dataplane/xen-block.c           |   4 +-
 hw/block/virtio-blk.c                    |  15 +--
 hw/ide/ahci.c                            |   6 +-
 hw/ide/atapi.c                           |   9 +-
 hw/ide/core.c                            |   9 +-
 hw/ide/macio.c                           |  15 ++-
 hw/nvme/ctrl.c                           |  43 ++++---
 hw/nvme/dif.c                            |   8 +-
 hw/scsi/scsi-disk.c                      |  28 +++--
 qemu-io-cmds.c                           |  14 +--
 system/dma-helpers.c                     |   4 +-
 tests/unit/test-block-accounting.c       |   2 +-
 tests/qemu-iotests/172.out               |  38 +++++++
 tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
 tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
 24 files changed, 472 insertions(+), 81 deletions(-)
 create mode 100755 tests/qemu-iotests/tests/delay-alert
 create mode 100644 tests/qemu-iotests/tests/delay-alert.out
Signature · 1 line
2.55.0
#37 lore raw
Quoted 15 lines · Stefan Hajnoczi
Quoted 14 lines · Hanna Czenczek

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

Quoted 11 lines
Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 5 lines
Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Yes, because it is not statically proven to be so.

Quoted 4 lines

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

I don't follow what you mean concretely. If you are suggesting a list of requests in BlockAcctStats, then that is exactly what I had.

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

I.e. it’s not like our functions current look like

````
run_co_ide_request() {
    start_cookie();
    run_co_request();
    finalize_cookie();
}
```

Where the pairing of start and finalize are obvious; instead, start and stop are in very different parts of the code, in all device emulation code.

Quoted 12 lines

The API is already weird because devices use:

   block_acct_failed(blk_get_stats(s->blk), &req->acct);

i.e. why does the device have to reach into s->blk to access the stats? If the stats belong to s->blk, then s->blk should do the accounting during the request lifetime.

This would require a redesign of not just the cookie API, but also the error policy API. There is also a wrinkle in that virtio-blk merges I/O requests and accounts the merges.

Quoted 7 lines
Quoted 6 lines

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

Does this achieve the goal of warning when requests exceed a threshold?

According to https://redhat.atlassian.net/browse/RHEL-141617?focusedCommentId=18127333 (and the following two comments), yes.

Quoted 3 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

Hanna

Quoted 50 lines
Quoted 50 lines

(PS: The nice thing about throwing an alert while the request is still going on would be that it could allow us to also stop the VM in case of excessive latency, before the request completes, so the guest would be shielded from such excessive latency. This might be useful for Windows guests that just have a maximum request lantency before throwing a BSOD.)

Hanna Czenczek (9):
block/accounting: Add offset to BlockAcctCookie qapi/block: Add IoAccountingOperation enum qapi/block: Add BLOCK_IO_DELAY event
block-backend: Public blk_get_attached_dev_path() block/accounting: Add BB field to latency checker block/accounting: Emit BLOCK_IO_DELAY event
block: Add delay-alert-ms property block/accounting: Move latency_ns override down
iotests: Add delay-alert test

  qapi/block.json                          |  52 +++++++++
  include/block/accounting.h               |  20 +++-
  include/hw/block/block.h                 |   5 +-
  include/system/block-backend-io.h        |   9 ++
  include/system/dma.h                     |   2 +-
  block/accounting.c                       |  60 ++++++++--
  block/block-backend.c                    |   8 +-
  blockdev.c                               |  16 ++-
  hw/block/block.c                         |   4 +-
  hw/block/dataplane/xen-block.c           |   4 +-
  hw/block/virtio-blk.c                    |  15 +--
  hw/ide/ahci.c                            |   6 +-
  hw/ide/atapi.c                           |   9 +-
  hw/ide/core.c                            |   9 +-
  hw/ide/macio.c                           |  15 ++-
  hw/nvme/ctrl.c                           |  43 ++++---
  hw/nvme/dif.c                            |   8 +-
  hw/scsi/scsi-disk.c                      |  28 +++--
  qemu-io-cmds.c                           |  14 +--
  system/dma-helpers.c                     |   4 +-
  tests/unit/test-block-accounting.c       |   2 +-
  tests/qemu-iotests/172.out               |  38 +++++++
  tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
  tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
  24 files changed, 472 insertions(+), 81 deletions(-)

create mode 100755 tests/qemu-iotests/tests/delay-alert create mode 100644 tests/qemu-iotests/tests/delay-alert.out

Signature · 1 line
2.55.0
#38 lore raw
Quoted 24 lines · Hanna Czenczek
Quoted 15 lines · Stefan Hajnoczi
Quoted 14 lines · Hanna Czenczek

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 8 lines

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

I wasn't thinking about the lifecycle here, but about the current limitation that users aren't notified until request completion. Requests can be stuck for a very long time or forever. Using a timer solves the timeliness problem.

Quoted 19 lines
Quoted 11 lines
Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 5 lines
Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Yes, because it is not statically proven to be so.

Quoted 7 lines
Quoted 4 lines

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

I don't follow what you mean concretely. If you are suggesting a list of requests in BlockAcctStats, then that is exactly what I had.

I meant that each I/O request should contain its own cookie and there is never a need to create a cookie separately from the request. That way the lifetime issue is solved.

This would require API changes because device emulation code currently has some of the logic for cookies. Devices would no longer call block_acct_done() once they have called blk_aio_pwritev(), for example. I haven't looked in detail and am not sure if it's feasible.

Quoted 4 lines

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Quoted 31 lines

I.e. it’s not like our functions current look like

````
run_co_ide_request() {
    start_cookie();
    run_co_request();
    finalize_cookie();
}
```

Where the pairing of start and finalize are obvious; instead, start and stop are in very different parts of the code, in all device emulation code.

Quoted 18 lines

The API is already weird because devices use:

   block_acct_failed(blk_get_stats(s->blk), &req->acct);

i.e. why does the device have to reach into s->blk to access the stats? If the stats belong to s->blk, then s->blk should do the accounting during the request lifetime.

This would require a redesign of not just the cookie API, but also the error policy API. There is also a wrinkle in that virtio-blk merges I/O requests and accounts the merges.

Quoted 6 lines

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

Quoted 5 lines
Quoted 1 line

Does this achieve the goal of warning when requests exceed a threshold?

According to
https://redhat.atlassian.net/browse/RHEL-141617?focusedCommentId=18127333
(and the following two comments), yes.

The issue says one purpose of this feature is to pause the guest to avoid BSODs. This won't work if the request has to finish first, because the BSOD occurs sometime after the treshold is reached but before QEMU or any other component can react to the QMP event.

Quoted 10 lines
Quoted 4 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

What does the current approach solve that is not already possible with the block latency histogram?

Libvirt could add an API to notify when a particular threshold is reached without any QEMU changes.

Stefan

Quoted 54 lines

Hanna

Quoted 50 lines
Quoted 50 lines

(PS: The nice thing about throwing an alert while the request is still going on would be that it could allow us to also stop the VM in case of excessive latency, before the request completes, so the guest would be shielded from such excessive latency. This might be useful for Windows guests that just have a maximum request lantency before throwing a BSOD.)

Hanna Czenczek (9):
block/accounting: Add offset to BlockAcctCookie qapi/block: Add IoAccountingOperation enum qapi/block: Add BLOCK_IO_DELAY event
block-backend: Public blk_get_attached_dev_path() block/accounting: Add BB field to latency checker block/accounting: Emit BLOCK_IO_DELAY event
block: Add delay-alert-ms property block/accounting: Move latency_ns override down
iotests: Add delay-alert test

  qapi/block.json                          |  52 +++++++++
  include/block/accounting.h               |  20 +++-
  include/hw/block/block.h                 |   5 +-
  include/system/block-backend-io.h        |   9 ++
  include/system/dma.h                     |   2 +-
  block/accounting.c                       |  60 ++++++++--
  block/block-backend.c                    |   8 +-
  blockdev.c                               |  16 ++-
  hw/block/block.c                         |   4 +-
  hw/block/dataplane/xen-block.c           |   4 +-
  hw/block/virtio-blk.c                    |  15 +--
  hw/ide/ahci.c                            |   6 +-
  hw/ide/atapi.c                           |   9 +-
  hw/ide/core.c                            |   9 +-
  hw/ide/macio.c                           |  15 ++-
  hw/nvme/ctrl.c                           |  43 ++++---
  hw/nvme/dif.c                            |   8 +-
  hw/scsi/scsi-disk.c                      |  28 +++--
  qemu-io-cmds.c                           |  14 +--
  system/dma-helpers.c                     |   4 +-
  tests/unit/test-block-accounting.c       |   2 +-
  tests/qemu-iotests/172.out               |  38 +++++++
  tests/qemu-iotests/tests/delay-alert     | 136 +++++++++++++++++++++++
  tests/qemu-iotests/tests/delay-alert.out |  46 ++++++++
  24 files changed, 472 insertions(+), 81 deletions(-)

create mode 100755 tests/qemu-iotests/tests/delay-alert create mode 100644 tests/qemu-iotests/tests/delay-alert.out

Signature · 1 line
2.55.0
#39 lore raw

Am 21.09.2026 um 22:41 hat Stefan Hajnoczi geschrieben:

Quoted 34 lines · Hanna Czenczek
Quoted 24 lines · Stefan Hajnoczi
Quoted 15 lines · Hanna Czenczek
Quoted 14 lines

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 8 lines

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

Quoted 4 lines

I wasn't thinking about the lifecycle here, but about the current limitation that users aren't notified until request completion. Requests can be stuck for a very long time or forever. Using a timer solves the timeliness problem.

I think we'll need to do this eventually. There was also talk about stopping the VM if a request hangs for too long, which will definitely need a timer.

But I think this specific series can work without it for now. Once we do have the timer anyway, reporting the latency right when the threshold is crossed can still be done.

We should be careful with the wording in the documentation to allow both behaviours so we can make this change in the future.

Quoted 41 lines
Quoted 19 lines
Quoted 11 lines
Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 5 lines
Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Yes, because it is not statically proven to be so.

Quoted 7 lines
Quoted 4 lines

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

I don't follow what you mean concretely. If you are suggesting a list of requests in BlockAcctStats, then that is exactly what I had.

I meant that each I/O request should contain its own cookie and there is never a need to create a cookie separately from the request. That way the lifetime issue is solved.

This would require API changes because device emulation code currently has some of the logic for cookies. Devices would no longer call block_acct_done() once they have called blk_aio_pwritev(), for example. I haven't looked in detail and am not sure if it's feasible.

Quoted 4 lines

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

Quoted 5 lines

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Apart from cases where requests are completed entirely within the device (like for all block_acct_invalid() callers), there are also cases where a single device-level requests involves multiple backend-level requests. I was thinking of IDE TRIM initially, but actually I think splitting can happen for any request that uses the DMA helpers.

Conversely, virtio-blk can merge requests, so you get a single request in the backend that covers multiple requests in the device.

Kevin

#40 lore raw
Quoted 15 lines · Kevin Wolf

Am 21.09.2026 um 22:41 hat Stefan Hajnoczi geschrieben:

Quoted 8 lines · Hanna Czenczek
Quoted 6 lines · Stefan Hajnoczi
Quoted 1 line · Hanna Czenczek

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

Quoted 5 lines

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Quoted 8 lines

Apart from cases where requests are completed entirely within the device (like for all block_acct_invalid() callers), there are also cases where a single device-level requests involves multiple backend-level requests. I was thinking of IDE TRIM initially, but actually I think splitting can happen for any request that uses the DMA helpers.

Conversely, virtio-blk can merge requests, so you get a single request in the backend that covers multiple requests in the device.

Sticking to the requests as seen by the device seems like the cleanest solution rather than cheating and counting host requests in some places.

The idea to move the accounting into blk_aio_*() doesn't work well in light of this.

Stefan

#41 lore raw
Quoted 20 lines · Stefan Hajnoczi
Quoted 19 lines · Kevin Wolf

Am 21.09.2026 um 22:41 hat Stefan Hajnoczi geschrieben:

Quoted 7 lines · Hanna Czenczek
Quoted 6 lines · Stefan Hajnoczi
Quoted 1 line · Hanna Czenczek

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

Quoted 5 lines

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Apart from cases where requests are completed entirely within the device (like for all block_acct_invalid() callers), there are also cases where a single device-level requests involves multiple backend-level requests. I was thinking of IDE TRIM initially, but actually I think splitting can happen for any request that uses the DMA helpers.

Quoted 7 lines
Quoted 2 lines

Conversely, virtio-blk can merge requests, so you get a single request in the backend that covers multiple requests in the device.

Sticking to the requests as seen by the device seems like the cleanest solution rather than cheating and counting host requests in some places.

The idea to move the accounting into blk_aio_*() doesn't work well in light of this.

Does this mean you would be against separating delay monitoring from the rest of accounting?

Because to me that still sounds reasonable: To do delay monitoring in the BB layer, separate from accounting cookies, to have a simple lifecycle and timely reporting.

(And as you did say, if one wants the guest-device-request-level delay information, the histogram is there O:) )

Hanna

#42 lore raw
Quoted 23 lines · Hanna Czenczek
Quoted 22 lines · Stefan Hajnoczi
Quoted 21 lines · Kevin Wolf

Am 21.09.2026 um 22:41 hat Stefan Hajnoczi geschrieben:

Quoted 7 lines · Hanna Czenczek
Quoted 6 lines · Stefan Hajnoczi
Quoted 1 line · Hanna Czenczek

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

Quoted 5 lines

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Apart from cases where requests are completed entirely within the device (like for all block_acct_invalid() callers), there are also cases where a single device-level requests involves multiple backend-level requests. I was thinking of IDE TRIM initially, but actually I think splitting can happen for any request that uses the DMA helpers.

Conversely, virtio-blk can merge requests, so you get a single request in the backend that covers multiple requests in the device.

Quoted 8 lines
Quoted 5 lines

Sticking to the requests as seen by the device seems like the cleanest solution rather than cheating and counting host requests in some places.

The idea to move the accounting into blk_aio_*() doesn't work well in light of this.

Does this mean you would be against separating delay monitoring from the rest of accounting?

I'm not against it. I just don't think we can push accounting down into the block layer since accounting operates at the emulated device's request level and there isn't a 1:1 correspondence between block layer I/O requests and device level requests.

Quoted 3 lines

Because to me that still sounds reasonable: To do delay monitoring in the BB layer, separate from accounting cookies, to have a simple lifecycle and timely reporting.

Yes.

Stefan

#43 lore raw
In reply to Stefan Hajnoczi
Quoted 32 lines · Stefan Hajnoczi
Quoted 23 lines · Hanna Czenczek
Quoted 15 lines · Stefan Hajnoczi
Quoted 14 lines · Hanna Czenczek

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 8 lines

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

Quoted 4 lines

I wasn't thinking about the lifecycle here, but about the current limitation that users aren't notified until request completion. Requests can be stuck for a very long time or forever. Using a timer solves the timeliness problem.

I still don’t follow. The lifecycle *is* the problem if the timeliness. How to implement repeated querying is not the problem.

FWIW, the series that I had with timely waking did use a timer. But the timer is just not the problem.

Quoted 22 lines
Quoted 22 lines
Quoted 11 lines
Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 5 lines
Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Yes, because it is not statically proven to be so.

Quoted 4 lines

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

Quoted 5 lines
Quoted 2 lines

I don't follow what you mean concretely. If you are suggesting a list of requests in BlockAcctStats, then that is exactly what I had.

I meant that each I/O request should contain its own cookie and there is never a need to create a cookie separately from the request. That way the lifetime issue is solved.

Okay, I understood with your other email, because to me, “I/O request” sounded like some kind of object and I couldn’t think of any. My mind did not jump to the fact that you meant the actual execution thread of the request, i.e. code, not structure.

Quoted 4 lines

This would require API changes because device emulation code currently has some of the logic for cookies. Devices would no longer call block_acct_done() once they have called blk_aio_pwritev(), for example. I haven't looked in detail and am not sure if it's feasible.

As said in the other email, doing this would most likely change behavior because we can’t or don’t want to reproduce all currently existing quirks. Which may be good or bad. Bad for me in any case because it would be more work, but, well…

Quoted 41 lines
Quoted 4 lines

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Quoted 31 lines

I.e. it’s not like our functions current look like

````
run_co_ide_request() {
     start_cookie();
     run_co_request();
     finalize_cookie();
}
```

Where the pairing of start and finalize are obvious; instead, start and stop are in very different parts of the code, in all device emulation code.

Quoted 18 lines

The API is already weird because devices use:

    block_acct_failed(blk_get_stats(s->blk), &req->acct);

i.e. why does the device have to reach into s->blk to access the stats? If the stats belong to s->blk, then s->blk should do the accounting during the request lifetime.

This would require a redesign of not just the cookie API, but also the error policy API. There is also a wrinkle in that virtio-blk merges I/O requests and accounts the merges.

Quoted 6 lines

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Does this achieve the goal of warning when requests exceed a threshold?

According to
https://redhat.atlassian.net/browse/RHEL-141617?focusedCommentId=18127333
(and the following two comments), yes.

The issue says one purpose of this feature is to pause the guest to avoid BSODs. This won't work if the request has to finish first, because the BSOD occurs sometime after the treshold is reached but before QEMU or any other component can react to the QMP event.

I know. I linked to a specific comment chain that says it is enough for now.

Whether the pausing is something anyone actually would ever want is a completely different story, honestly. It is an idea I had for the original design, but nothing that has actually ever been requested.

Quoted 10 lines
Quoted 8 lines
Quoted 3 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

What does the current approach solve that is not already possible with the block latency histogram?

See what I linked above. Apparently having to repeatedly query the histogram repeatedly is not deemed nice enough.

Hanna

Quoted 4 lines

Libvirt could add an API to notify when a particular threshold is reached without any QEMU changes.

Stefan

#44 lore raw

Am 23.09.2026 um 12:48 hat Hanna Czenczek geschrieben:

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
Quoted 3 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

What does the current approach solve that is not already possible with the block latency histogram?

See what I linked above. Apparently having to repeatedly query the histogram repeatedly is not deemed nice enough.

It's the difference between an event and active polling. I would agree that active polling isn't the right answer in most cases.

Kevin

#45 lore raw
In reply to Hanna Czenczek
Quoted 38 lines · Hanna Czenczek
Quoted 32 lines · Stefan Hajnoczi
Quoted 23 lines · Hanna Czenczek
Quoted 15 lines · Stefan Hajnoczi
Quoted 14 lines · Hanna Czenczek

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 8 lines

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

Quoted 4 lines

I wasn't thinking about the lifecycle here, but about the current limitation that users aren't notified until request completion. Requests can be stuck for a very long time or forever. Using a timer solves the timeliness problem.

Quoted 5 lines

I still don’t follow. The lifecycle *is* the problem if the timeliness. How to implement repeated querying is not the problem.

FWIW, the series that I had with timely waking did use a timer. But the timer is just not the problem.

Regarding the lifecycle, I don't see a fundamental problem. It's possible to add a timer to block layer I/O requests and know for certain that leaks, use-after-free, etc are not possible because the caller doesn't need to juggle anything. Even if the caller has to juggle something, this is a C codebase where APIs are not always safe. That's not a blocker as long as they API design allows disciplined users to use it correctly. If I misunderstood your concerns and there is a fundamental reason why the lifetime cannot be made correct, maybe you can explain?

Quoted 104 lines
Quoted 22 lines
Quoted 22 lines
Quoted 11 lines
Quoted 11 lines

(which makes sense), then that would require that every cookie set up is also finalized when the request is done, because if we don't, results could well be catastrophic:
- Either we use cookies as-is, which are often allocated on the stack or in some other structure managed by the device; then this would result in use-after-free,
- Or we allocate something specifically for this checking, so lingering requests would at most create spurious latency events and memory leaks, but this would require an additional heap allocation per request that we would probably want to avoid.

Quoted 5 lines
Quoted 3 lines

So ideally we could use latency cookies and could statically verify that they are always finalized when the request is done, but doing this in C may well be impossible.

I think you are saying that the cookie API is unsafe because cookie lifetime is not bounded by the request lifetime?

Yes, because it is not statically proven to be so.

Quoted 4 lines

Maybe the block_acct_*() API can be integrated into the actual request so there is no way to leak the cookie. In other words, directly associate requests with a BlockAcctStats and stop requiring the user to manually manage a separate BlockAcctCookie.

Quoted 5 lines
Quoted 2 lines

I don't follow what you mean concretely. If you are suggesting a list of requests in BlockAcctStats, then that is exactly what I had.

I meant that each I/O request should contain its own cookie and there is never a need to create a cookie separately from the request. That way the lifetime issue is solved.

Okay, I understood with your other email, because to me, “I/O request” sounded like some kind of object and I couldn’t think of any. My mind did not jump to the fact that you meant the actual execution thread of the request, i.e. code, not structure.

Quoted 4 lines

This would require API changes because device emulation code currently has some of the logic for cookies. Devices would no longer call block_acct_done() once they have called blk_aio_pwritev(), for example. I haven't looked in detail and am not sure if it's feasible.

As said in the other email, doing this would most likely change behavior because we can’t or don’t want to reproduce all currently existing quirks. Which may be good or bad. Bad for me in any case because it would be more work, but, well…

Quoted 41 lines
Quoted 4 lines

The problem is that if the destructor has to be called explicitly, we may forget to do so; and accounting is done on the device emulation level, so there is no central place where the pairing of constructor and destructor would be obvious and trivial to verify.

This is the part I'm asking about: can accounting be done by the block layer? There might be cases that are purely handled in device emulation code without a call into the block layer. In that case the accounting still needs to be done in device emulation code. But when device emulation calls blk_aio_*(), it should not do accounting itself.

Quoted 31 lines

I.e. it’s not like our functions current look like

````
run_co_ide_request() {
     start_cookie();
     run_co_request();
     finalize_cookie();
}
```

Where the pairing of start and finalize are obvious; instead, start and stop are in very different parts of the code, in all device emulation code.

Quoted 18 lines

The API is already weird because devices use:

    block_acct_failed(blk_get_stats(s->blk), &req->acct);

i.e. why does the device have to reach into s->blk to access the stats? If the stats belong to s->blk, then s->blk should do the accounting during the request lifetime.

This would require a redesign of not just the cookie API, but also the error policy API. There is also a wrinkle in that virtio-blk merges I/O requests and accounts the merges.

Quoted 6 lines

So, because it is basically impossible (or at least it would be very hard, and presumably require a large refactoring) to guarantee, without additional heap allocations, that a list of active requests won’t run into catastrophic use-after-frees, this series does the much simpler version first, which is to just raise an event when a request *finishes* and took more than a user-defined latency threshold.

Quoted 8 lines
Quoted 4 lines
Quoted 1 line

Does this achieve the goal of warning when requests exceed a threshold?

According to
https://redhat.atlassian.net/browse/RHEL-141617?focusedCommentId=18127333
(and the following two comments), yes.

The issue says one purpose of this feature is to pause the guest to avoid BSODs. This won't work if the request has to finish first, because the BSOD occurs sometime after the treshold is reached but before QEMU or any other component can react to the QMP event.

I know. I linked to a specific comment chain that says it is enough for now.

Whether the pausing is something anyone actually would ever want is a completely different story, honestly. It is an idea I had for the original design, but nothing that has actually ever been requested.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Quoted 8 lines
Quoted 5 lines
Quoted 3 lines

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

What does the current approach solve that is not already possible with the block latency histogram?

See what I linked above. Apparently having to repeatedly query the histogram repeatedly is not deemed nice enough.

Why at the QEMU level though? Libvirt can offer an event based on the block histogram.

The utility of this new feature is not clear to me. How is this QMP event actually going to be used? Usually a feature has a clear use case and the cost of committing to the QMP API and maintaining backwards compatibility is easy to justify. In this case I'm not sure what the real use case is or whether this is something someone thought might be nice to have but may never use - we'll have to maintain it forever either way.

(Timeliness makes the need for this feature clear to me. QEMU has to be involved either by pausing the guest itself or by emitting a QMP event. This is why I'm particularly interested in timeliness.)

Stefan

#46 lore raw

Am 24.09.2026 um 17:17 hat Stefan Hajnoczi geschrieben:

Quoted 45 lines · Hanna Czenczek
Quoted 38 lines · Stefan Hajnoczi
Quoted 32 lines · Hanna Czenczek
Quoted 23 lines · Stefan Hajnoczi
Quoted 15 lines · Hanna Czenczek
Quoted 14 lines

Based-on:<[email protected]>
[PATCH 0/6] hw/[block]: Fix missing accounting Fri, 24 Jul 2026 17:23:09 +0200

Hi,

I’m told there are installations where storage is very slow, and some would like the VM stack to report this proactively. To do so, we should (via QAPI events) report on extremely slow I/O requests.

We already have the latency histogram, but this is not deemed sufficient because it is not proactively reporting and would require repeated querying. Therefore, this series introduces the event still.

Quoted 7 lines
Quoted 4 lines

Now, from a user's perspective, it would be nice if this event could be raised exactly when an I/O request crosses the user-defined threshold, but this would require keeping all active requests in a list and checking it periodically. Now, if we used latency cookies for this

Did you consider a per-request timer? The QEMUTimerList active_timers sorted list does not support efficient insertion, but improving it would benefit all timer API users.

Quoted 8 lines

I'm not sure how that would address the problem. Does that not just move the list elsewhere?

I.e. it still has the problem that every request needs to be put into a list (starting a timer), and be removed when the request is done, or the timer will fire and the below problems would occur if the request is done but we failed to remove it (either use-after-free; or spurious events plus memory leaks on top of a heap allocation per request).

Quoted 4 lines

I wasn't thinking about the lifecycle here, but about the current limitation that users aren't notified until request completion. Requests can be stuck for a very long time or forever. Using a timer solves the timeliness problem.

Quoted 5 lines

I still don’t follow. The lifecycle *is* the problem if the timeliness. How to implement repeated querying is not the problem.

FWIW, the series that I had with timely waking did use a timer. But the timer is just not the problem.

Quoted 9 lines

Regarding the lifecycle, I don't see a fundamental problem. It's possible to add a timer to block layer I/O requests and know for certain that leaks, use-after-free, etc are not possible because the caller doesn't need to juggle anything. Even if the caller has to juggle something, this is a C codebase where APIs are not always safe. That's not a blocker as long as they API design allows disciplined users to use it correctly. If I misunderstood your concerns and there is a fundamental reason why the lifetime cannot be made correct, maybe you can explain?

I don't think there is a fundamental reason other than that humans are bad at writing correct C code, but that this is based more on Hanna's finding that our existing code has bugs in this respect and she isn't sure if she caught all of them.

The current consequence of missing the end of a request is that it isn't accounted for, and that's it. After the change, it means that a timer callback will fire long after the request is gone, and therefore work on a stale pointer, so it may turn into memory corruption and crashes.

Maybe this can be mitigated by not referencing data bound to the request lifetime, but just keeping a copy of type/offset/length or whatever is needed for emitting the QAPI event, at the cost of a heap allocation as Hanna explained in the cover letter. It would still mean that a bogus timeout is reported.

So I agree that we'd want to have those cases fixed before depending on correct block_acct_start()/block_account_one_io() pairing.

And I'm afraid that Hanna is also right that it might be impossible to get this done by static analysis in our callback-heavy device implementations. If the full request control flow were in a coroutine, TSA could probably do it, but I don't think it can work with our actual code. Maybe simple cases like virtio-blk could be covered with the latest TSA improvements coming from the kernel (I would have to check if they cover callbacks well enough), but the scsi-disk state machine looks too complicated for this.

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 3 lines

When an I/O request hangs for a long time, the management tool will be unable to detect that the threshold has been exceeded in a timely manner.

Yes. But why would that be a real problem?

Given the request so far is only to notify users of their storage block showing problematic latencies at all, there is no need to provide the alerts in actual real time.

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines

What does the current approach solve that is not already possible with the block latency histogram?

See what I linked above. Apparently having to repeatedly query the histogram repeatedly is not deemed nice enough.

Why at the QEMU level though? Libvirt can offer an event based on the block histogram.

At what intervals should libvirt poll QEMU? And why should polling be better than using an event?

Quoted 7 lines

The utility of this new feature is not clear to me. How is this QMP event actually going to be used? Usually a feature has a clear use case and the cost of committing to the QMP API and maintaining backwards compatibility is easy to justify. In this case I'm not sure what the real use case is or whether this is something someone thought might be nice to have but may never use - we'll have to maintain it forever either way.

The idea is to show a warning to the user that their storage has latency issues and they need to look into that. Ideally before the latency reaches critical values that result in errors.

Quoted 3 lines

(Timeliness makes the need for this feature clear to me. QEMU has to be involved either by pausing the guest itself or by emitting a QMP event. This is why I'm particularly interested in timeliness.)

If you want to prevent a in-flight request from timing out in the guest, then yes, QEMU would have pause the guest. I think emitting a QMP event alone wouldn't be good enough for this. (Even more so considering that a 'stop' command actually involves draining all requests.)

Kevin