All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH] vhost: mask the in-order used-ring log cursor
@ 2026-11-22 13:19 ` YanXin Li via B4 Relay
  0 siblings, 0 replies; 9+ messages in thread
From: YanXin Li @ 2026-11-22 13:19 UTC (permalink / raw)
  To: Michael S. Tsirkin, Jason Wang, Eugenio Pérez
  Cc: Linfeng Sun, Fang Xieyan, kvm, virtualization, netdev,
	linux-kernel, stable

vhost_add_used_n_in_order() plays the batch of used-ring writes back a
second time for dirty logging.  Commit e244725e86be ("vhost: fix used
ring index wrap in vhost_add_used_n_in_order") masked the index in the
descriptor-publishing loop.  The dirty-logging loop introduced by
bfcde6b64769 still uses the single-subtraction form

    next = start + nheads[i];
    if (next >= vq->num)
        next -= vq->num;

If the guest refills the available ring while get_rx_bufs() collects
one mergeable-RX packet, that packet can consume more heads than
vq->num.  get_rx_bufs() permits up to UIO_MAXIOV = 1024 descriptor
chains in one call, so a single subtraction is not enough.  For
vq->num = 32, last_used_idx = 0 and nheads[0] = 64, next becomes
64 - 32 = 32, which is still equal to vq->num and out of bounds.  The
next iteration then logs

    used = vq->used->ring + 32;
    log_used(vq, 4 + 32 * 8, 8);

which starts past the end of the 260-byte ring body (4 + 32 * 8).
For a used ring placed inside page 7 at guest address 0x7ef8 (so the
entire 262-byte ring occupies [0x7ef8, 0x7ffe) and
vq_log_used_access_ok() validates only log_base[0]), log_used()
marks [0x7ffc, 0x8004) as dirty.  log_write() then sets a bit in
log_base[1] for page 8, past the single validated byte.  On a
vhost-net RX queue configured with VIRTIO_F_IN_ORDER,
VIRTIO_NET_F_MRG_RXBUF,
VHOST_F_LOG_ALL, VHOST_VRING_F_LOG, vq->num = 32, and
log_guest_addr = 0x7ef8, delivering one 8 KiB frame consuming 64
mergeable buffers followed by one 1-buffer frame in the same
count = 2 flush writes

    log_base[1] = 0x01

where log_base[0] = 0x80 is the only byte the kernel was entitled to
touch.  A guest attached to a vhost-net backend with dirty-page
logging enabled (for example during live migration) and a small RX
ring can therefore corrupt dirty-log bitmap memory that the VMM owns
outside the region registered for this ring.

Wrap the logging loop index the same way the first loop does:

    next = (start + nheads[i]) & (vq->num - 1);

vhost_vring_set_num() already enforces that vq->num is a nonzero
power of two, so this is well defined for every accepted ring size.
The coalescing invariant is preserved: if a run is not flushed,
next == start + 1.  When start == vq->num - 1, start + 1 == vq->num,
whereas the masked next is always less than vq->num.  The run is
therefore flushed before the cursor wraps.
With this change the same vhost-net configuration publishes
used->idx = 65 and confines the dirty log to log_base[0] = 0x80,
leaving log_base[1] = 0x00.  The mask keeps next in [0, vq->num) for
every accepted power-of-two ring size.  As a bounded cross-check of
the index arithmetic, a Z3 model over ring sizes {1, 2, 4, 8, 16, 32}
and buffer counts in [1, 64] finds an out-of-range result for the old
subtraction (vq->num = 16, start = 15, nheads = 17) and none for the
mask within those bounds.

Runtime verification and fix validation were performed in an x86-64
QEMU/KVM guest running mainline after v7.4-rc3, with Generic KASAN,
UBSAN, lockdep, and DEBUG_OBJECTS.

Fixes: bfcde6b64769 ("vhost: fix dirty logging for in-order used ring entries")
Cc: stable@vger.kernel.org
Signed-off-by: YanXin Li <fadouse@pm.me>
---
 drivers/vhost/vhost.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c
index dc973287567..80b887e1511 100644
--- a/drivers/vhost/vhost.c
+++ b/drivers/vhost/vhost.c
@@ -3206,9 +3206,7 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
 				log_start = start;
 			log_count++;
 
-			next = start + nheads[i];
-			if (next >= vq->num)
-				next -= vq->num;
+			next = (start + nheads[i]) & (vq->num - 1);
 			if (i + 1 == count || next != start + 1) {
 				used = vq->used->ring + log_start;
 				log_used(vq,

---
base-commit: c44104f3642da720164042623e4832836aefdd8e
change-id: 20261122-b4-06-vhost-in-order-log-oob-v1-35efdba8fbab-43734ad10f0a

Best regards,
--  
YanXin Li <fadouse@pm.me>


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH] vhost: mask the in-order used-ring log cursor
@ 2026-11-22 13:19 ` YanXin Li via B4 Relay
  0 siblings, 0 replies; 9+ messages in thread
From: YanXin Li via B4 Relay @ 2026-11-22 13:19 UTC (permalink / raw)
  To: Michael S. Tsirkin, Jason Wang, Eugenio Pérez
  Cc: Linfeng Sun, Fang Xieyan, kvm, virtualization, netdev,
	linux-kernel, stable

From: YanXin Li <fadouse@pm.me>

vhost_add_used_n_in_order() plays the batch of used-ring writes back a
second time for dirty logging.  Commit e244725e86be ("vhost: fix used
ring index wrap in vhost_add_used_n_in_order") masked the index in the
descriptor-publishing loop.  The dirty-logging loop introduced by
bfcde6b64769 still uses the single-subtraction form

    next = start + nheads[i];
    if (next >= vq->num)
        next -= vq->num;

If the guest refills the available ring while get_rx_bufs() collects
one mergeable-RX packet, that packet can consume more heads than
vq->num.  get_rx_bufs() permits up to UIO_MAXIOV = 1024 descriptor
chains in one call, so a single subtraction is not enough.  For
vq->num = 32, last_used_idx = 0 and nheads[0] = 64, next becomes
64 - 32 = 32, which is still equal to vq->num and out of bounds.  The
next iteration then logs

    used = vq->used->ring + 32;
    log_used(vq, 4 + 32 * 8, 8);

which starts past the end of the 260-byte ring body (4 + 32 * 8).
For a used ring placed inside page 7 at guest address 0x7ef8 (so the
entire 262-byte ring occupies [0x7ef8, 0x7ffe) and
vq_log_used_access_ok() validates only log_base[0]), log_used()
marks [0x7ffc, 0x8004) as dirty.  log_write() then sets a bit in
log_base[1] for page 8, past the single validated byte.  On a
vhost-net RX queue configured with VIRTIO_F_IN_ORDER,
VIRTIO_NET_F_MRG_RXBUF,
VHOST_F_LOG_ALL, VHOST_VRING_F_LOG, vq->num = 32, and
log_guest_addr = 0x7ef8, delivering one 8 KiB frame consuming 64
mergeable buffers followed by one 1-buffer frame in the same
count = 2 flush writes

    log_base[1] = 0x01

where log_base[0] = 0x80 is the only byte the kernel was entitled to
touch.  A guest attached to a vhost-net backend with dirty-page
logging enabled (for example during live migration) and a small RX
ring can therefore corrupt dirty-log bitmap memory that the VMM owns
outside the region registered for this ring.

Wrap the logging loop index the same way the first loop does:

    next = (start + nheads[i]) & (vq->num - 1);

vhost_vring_set_num() already enforces that vq->num is a nonzero
power of two, so this is well defined for every accepted ring size.
The coalescing invariant is preserved: if a run is not flushed,
next == start + 1.  When start == vq->num - 1, start + 1 == vq->num,
whereas the masked next is always less than vq->num.  The run is
therefore flushed before the cursor wraps.
With this change the same vhost-net configuration publishes
used->idx = 65 and confines the dirty log to log_base[0] = 0x80,
leaving log_base[1] = 0x00.  The mask keeps next in [0, vq->num) for
every accepted power-of-two ring size.  As a bounded cross-check of
the index arithmetic, a Z3 model over ring sizes {1, 2, 4, 8, 16, 32}
and buffer counts in [1, 64] finds an out-of-range result for the old
subtraction (vq->num = 16, start = 15, nheads = 17) and none for the
mask within those bounds.

Runtime verification and fix validation were performed in an x86-64
QEMU/KVM guest running mainline after v7.4-rc3, with Generic KASAN,
UBSAN, lockdep, and DEBUG_OBJECTS.

Fixes: bfcde6b64769 ("vhost: fix dirty logging for in-order used ring entries")
Cc: stable@vger.kernel.org
Signed-off-by: YanXin Li <fadouse@pm.me>
---
 drivers/vhost/vhost.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c
index dc973287567..80b887e1511 100644
--- a/drivers/vhost/vhost.c
+++ b/drivers/vhost/vhost.c
@@ -3206,9 +3206,7 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
 				log_start = start;
 			log_count++;
 
-			next = start + nheads[i];
-			if (next >= vq->num)
-				next -= vq->num;
+			next = (start + nheads[i]) & (vq->num - 1);
 			if (i + 1 == count || next != start + 1) {
 				used = vq->used->ring + log_start;
 				log_used(vq,

---
base-commit: c44104f3642da720164042623e4832836aefdd8e
change-id: 20261122-b4-06-vhost-in-order-log-oob-v1-35efdba8fbab-43734ad10f0a

Best regards,
--  
YanXin Li <fadouse@pm.me>



^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-22 13:19 ` YanXin Li via B4 Relay
  (?)
@ 2026-11-22 13:22 ` sashiko-bot
  -1 siblings, 0 replies; 9+ messages in thread
From: sashiko-bot @ 2026-11-22 13:22 UTC (permalink / raw)
  To: YanXin Li; +Cc: virtualization, Michael S. Tsirkin, Eugenio Perez

> From: YanXin Li <fadouse@pm.me>
> 
> vhost_add_used_n_in_order() plays the batch of used-ring writes back a
> second time for dirty logging.  Commit e244725e86be ("vhost: fix used
> ring index wrap in vhost_add_used_n_in_order") masked the index in the
> descriptor-publishing loop.  The dirty-logging loop introduced by
> bfcde6b64769 still uses the single-subtraction form
> 
>     next = start + nheads[i];
>     if (next >= vq->num)
>         next -= vq->num;
> 
> If the guest refills the available ring while get_rx_bufs() collects
> one mergeable-RX packet, that packet can consume more heads than
> vq->num.  get_rx_bufs() permits up to UIO_MAXIOV = 1024 descriptor
> [ ... ]
> UBSAN, lockdep, and DEBUG_OBJECTS.
> 
> Fixes: bfcde6b64769 ("vhost: fix dirty logging for in-order used ring entries")
> Cc: stable@vger.kernel.org
> Signed-off-by: YanXin Li <fadouse@pm.me>

Sashiko has reviewed this patch and found no issues.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261122-b4-06-vhost-in-order-log-oob-v1-35efdba8fbab-v1-1-fc1253d60351@pm.me?part=1

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-22 13:19 ` YanXin Li via B4 Relay
  (?)
  (?)
@ 2026-11-23  7:51 ` Jiaming Fan
  2026-11-23 12:31   ` fadouse
  -1 siblings, 1 reply; 9+ messages in thread
From: Jiaming Fan @ 2026-11-23  7:51 UTC (permalink / raw)
  To: YanXin Li
  Cc: Michael S. Tsirkin, Jason Wang, Eugenio Pérez, Linfeng Sun,
	Fang Xieyan, kvm, virtualization, netdev, linux-kernel, stable

> If the guest refills the available ring while get_rx_bufs() collects
> one mergeable-RX packet, that packet can consume more heads than
> vq->num.

The mask looks right to me. What I don't follow is how `nheads[0]`
gets to 64 on a 32-entry queue. Those buffers haven't been returned to
the driver yet, so what can it put back on the ring? Can this happen
with a conforming driver, or does the test guest reuse descriptors
that are still in flight?

Could you share the RX test program you used?

Thanks,
Jiaming Fan


^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-22 13:19 ` YanXin Li via B4 Relay
                   ` (2 preceding siblings ...)
  (?)
@ 2026-11-23 12:26 ` Eugenio Perez Martin
  2026-11-23 12:44   ` fadouse
  -1 siblings, 1 reply; 9+ messages in thread
From: Eugenio Perez Martin @ 2026-11-23 12:26 UTC (permalink / raw)
  To: fadouse
  Cc: Michael S. Tsirkin, Jason Wang, Linfeng Sun, Fang Xieyan, kvm,
	virtualization, netdev, linux-kernel, stable

On Sun, Nov 22, 2026 at 2:20 PM YanXin Li via B4 Relay
<devnull+fadouse.pm.me@kernel.org> wrote:
>
> From: YanXin Li <fadouse@pm.me>
>
> vhost_add_used_n_in_order() plays the batch of used-ring writes back a
> second time for dirty logging.  Commit e244725e86be ("vhost: fix used
> ring index wrap in vhost_add_used_n_in_order") masked the index in the
> descriptor-publishing loop.  The dirty-logging loop introduced by
> bfcde6b64769 still uses the single-subtraction form
>
>     next = start + nheads[i];
>     if (next >= vq->num)
>         next -= vq->num;
>
> If the guest refills the available ring while get_rx_bufs() collects
> one mergeable-RX packet, that packet can consume more heads than
> vq->num.

Although I'm ok with the proposed patch as hardening or optimization,
this sounds more like a bug in get_rx_bufs. Where are the memory
addresses for these pieces stored if there are no more buffers in the
virtqueue? Or is it able to loop through the vq?

> get_rx_bufs() permits up to UIO_MAXIOV = 1024 descriptor
> chains in one call, so a single subtraction is not enough.  For
> vq->num = 32, last_used_idx = 0 and nheads[0] = 64, next becomes
> 64 - 32 = 32, which is still equal to vq->num and out of bounds.  The
> next iteration then logs
>
>     used = vq->used->ring + 32;
>     log_used(vq, 4 + 32 * 8, 8);
>
> which starts past the end of the 260-byte ring body (4 + 32 * 8).
> For a used ring placed inside page 7 at guest address 0x7ef8 (so the
> entire 262-byte ring occupies [0x7ef8, 0x7ffe) and
> vq_log_used_access_ok() validates only log_base[0]), log_used()
> marks [0x7ffc, 0x8004) as dirty.  log_write() then sets a bit in
> log_base[1] for page 8, past the single validated byte.  On a
> vhost-net RX queue configured with VIRTIO_F_IN_ORDER,
> VIRTIO_NET_F_MRG_RXBUF,
> VHOST_F_LOG_ALL, VHOST_VRING_F_LOG, vq->num = 32, and
> log_guest_addr = 0x7ef8, delivering one 8 KiB frame consuming 64
> mergeable buffers followed by one 1-buffer frame in the same
> count = 2 flush writes
>
>     log_base[1] = 0x01
>
> where log_base[0] = 0x80 is the only byte the kernel was entitled to
> touch.  A guest attached to a vhost-net backend with dirty-page
> logging enabled (for example during live migration) and a small RX
> ring can therefore corrupt dirty-log bitmap memory that the VMM owns
> outside the region registered for this ring.
>
> Wrap the logging loop index the same way the first loop does:
>
>     next = (start + nheads[i]) & (vq->num - 1);
>
> vhost_vring_set_num() already enforces that vq->num is a nonzero
> power of two, so this is well defined for every accepted ring size.
> The coalescing invariant is preserved: if a run is not flushed,
> next == start + 1.  When start == vq->num - 1, start + 1 == vq->num,
> whereas the masked next is always less than vq->num.  The run is
> therefore flushed before the cursor wraps.
> With this change the same vhost-net configuration publishes
> used->idx = 65 and confines the dirty log to log_base[0] = 0x80,
> leaving log_base[1] = 0x00.  The mask keeps next in [0, vq->num) for
> every accepted power-of-two ring size.  As a bounded cross-check of
> the index arithmetic, a Z3 model over ring sizes {1, 2, 4, 8, 16, 32}
> and buffer counts in [1, 64] finds an out-of-range result for the old
> subtraction (vq->num = 16, start = 15, nheads = 17) and none for the
> mask within those bounds.
>
> Runtime verification and fix validation were performed in an x86-64
> QEMU/KVM guest running mainline after v7.4-rc3, with Generic KASAN,
> UBSAN, lockdep, and DEBUG_OBJECTS.
>

Can you post the reproducer? Even better if it is integrated in
tools/virtio/vhost_net_test.c.

Thanks!

> Fixes: bfcde6b64769 ("vhost: fix dirty logging for in-order used ring entries")
> Cc: stable@vger.kernel.org
> Signed-off-by: YanXin Li <fadouse@pm.me>
> ---
>  drivers/vhost/vhost.c | 4 +---
>  1 file changed, 1 insertion(+), 3 deletions(-)
>
> diff --git a/drivers/vhost/vhost.c b/drivers/vhost/vhost.c
> index dc973287567..80b887e1511 100644
> --- a/drivers/vhost/vhost.c
> +++ b/drivers/vhost/vhost.c
> @@ -3206,9 +3206,7 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
>                                 log_start = start;
>                         log_count++;
>
> -                       next = start + nheads[i];
> -                       if (next >= vq->num)
> -                               next -= vq->num;
> +                       next = (start + nheads[i]) & (vq->num - 1);
>                         if (i + 1 == count || next != start + 1) {
>                                 used = vq->used->ring + log_start;
>                                 log_used(vq,
>
> ---
> base-commit: c44104f3642da720164042623e4832836aefdd8e
> change-id: 20261122-b4-06-vhost-in-order-log-oob-v1-35efdba8fbab-43734ad10f0a
>
> Best regards,
> --
> YanXin Li <fadouse@pm.me>
>
>
>


^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-23  7:51 ` Jiaming Fan
@ 2026-11-23 12:31   ` fadouse
  0 siblings, 0 replies; 9+ messages in thread
From: fadouse @ 2026-11-23 12:31 UTC (permalink / raw)
  To: Jiaming Fan
  Cc: Michael S. Tsirkin, Jason Wang, Eugenio Pérez, Linfeng Sun,
	Fang Xieyan, kvm, virtualization, netdev, linux-kernel, stable


[-- Attachment #1.1: Type: text/plain, Size: 8715 bytes --]

Hi Jiaming,

> The mask looks right to me. What I don't follow is how `nheads[0]`
> gets to 64 on a 32-entry queue. Those buffers haven't been returned to
> the driver yet, so what can it put back on the ring? Can this happen
> with a conforming driver, or does the test guest reuse descriptors
> that are still in flight?

It is a non-conforming guest reusing in-flight ring slots; a conforming
driver would not advance avail->idx past last_used_idx + vq->num.

vhost accepts this because vhost_get_avail_idx() checks against
vq->last_avail_idx rather than vq->last_used_idx:

  if (unlikely((u16)(avail_idx - vq->last_avail_idx) > vq->num))

With vq->num = 32 and an 8180-byte frame (+ 12B vnet hdr = 64 x 128B
buffers) followed by a 64-byte frame (1 buffer):

  1. Guest publishes avail->idx = 32 and kicks.  get_rx_bufs() runs dry
     at 32 buffers and calls vhost_discard_vq_desc(), rewinding
     last_avail_idx to 0 while leaving vq->avail_idx = 32 cached.
  2. Guest advances avail->idx to 64 and kicks again.
     vhost_get_vq_desc_n() consumes cached 0..31 (last_avail_idx -> 32,
     last_used_idx still 0), then refreshes avail->idx = 64:
     (u16)(64 - 32) == 32 <= vq->num passes, so get_rx_bufs() collects
     32..63 into the same frame (nheads[0] = 64).
  3. The test polls buf0[12] (with pages 1..31 dropped via
     madvise(MADV_DONTNEED) to widen the copy window) and tries to
     publish avail->idx = 65 during the frame-0 copy so handle_rx() can
     pick up the 1-buffer frame and flush both in a single
     vhost_add_used_n_in_order() batch (count = 2, nheads = {64, 1}).

(Minor correction to my commit message: without VIRTIO_RING_F_EVENT_IDX
the used ring is 260 bytes at [0x7ef8, 0x7ffc) rather than 262 bytes;
vq_log_used_access_ok() still validates only log_base[0], and the
unmasked flush logs [0x7ffc, 0x8004) into log_base[1].)

> Could you share the RX test program you used?

Build with `gcc -O2 -Wall -Wextra test_vhost_inorder.c -o test_vhost_inorder`
and run as root (exit 2 = bug reproduced, 0 = fixed, 3 = timing retry):

----8<----
// SPDX-License-Identifier: GPL-2.0
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/if_tun.h>
#include <linux/vhost.h>
#include <linux/virtio_config.h>
#include <linux/virtio_net.h>
#include <linux/virtio_ring.h>
#include <net/if.h>
#include <netpacket/packet.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <unistd.h>

#define GUEST_MEM_SIZE	(16UL * 1024 * 1024)
#define IOVA_DESC	0x0000
#define IOVA_AVAIL	0x1000
#define IOVA_USED	0x7ef8
#define BUF_IOVA_BASE	0x20000
#define VQ_NUM		32
#define BUF_LEN		128
#define FRAME0_LEN	8180	/* + 12B vnet hdr = 64 * 128B */
#define FRAME1_LEN	64
#define NHEADS0		64
#define TOTAL_AVAIL	65

typedef uint8_t  u8;
typedef uint16_t u16;
typedef uint64_t u64;

static void die(const char *msg)
{
	fprintf(stderr, "%s: %s\n", msg, strerror(errno));
	exit(1);
}

static void publish_avail(struct vring_avail *avail, u16 v)
{
	__atomic_store_n(&avail->idx, v, __ATOMIC_RELEASE);
}

static void kick(int efd)
{
	u64 one = 1;

	if (write(efd, &one, sizeof(one)) != sizeof(one))
		die("kick");
}

int main(void)
{
	int vfd, tfd, pkt, sock, kick_fd, call_fd, ifindex;
	struct ifreq ifr = {};
	struct vring_desc *desc;
	struct vring_avail *avail;
	struct vring_used *used;
	struct sockaddr_ll sll = {};
	unsigned char frame0[FRAME0_LEN], frame1[FRAME1_LEN];
	struct {
		struct vhost_memory m;
		struct vhost_memory_region r[1];
	} memtable = {
		.m = { .nregions = 1 },
		.r = { { .guest_phys_addr = 0, .memory_size = GUEST_MEM_SIZE } },
	};
	struct vhost_vring_state vs = {};
	struct vhost_vring_addr va = {};
	struct vhost_vring_file vf = {};
	u64 features, log_base_ptr;
	void *guest_mem;
	unsigned char *log_base;
	u8 *buf0;

	guest_mem = mmap(NULL, GUEST_MEM_SIZE, PROT_READ | PROT_WRITE,
			 MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
	if (guest_mem == MAP_FAILED)
		die("mmap guest_mem");
	log_base = mmap(NULL, 4096, PROT_READ | PROT_WRITE,
			MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
	if (log_base == MAP_FAILED)
		die("mmap log_base");

	desc  = (struct vring_desc *)((u8 *)guest_mem + IOVA_DESC);
	avail = (struct vring_avail *)((u8 *)guest_mem + IOVA_AVAIL);
	used  = (struct vring_used *)((u8 *)guest_mem + IOVA_USED);
	buf0  = (u8 *)guest_mem + BUF_IOVA_BASE;

	for (int i = 0; i < VQ_NUM; i++) {
		desc[i] = (struct vring_desc){
			.addr  = BUF_IOVA_BASE + 4096 * i,
			.len   = BUF_LEN,
			.flags = VRING_DESC_F_WRITE,
		};
		avail->ring[i] = i;
	}
	for (int i = 1; i < VQ_NUM; i++)
		madvise((u8 *)guest_mem + BUF_IOVA_BASE + 4096 * i,
			4096, MADV_DONTNEED);

	tfd = open("/dev/net/tun", O_RDWR);
	if (tfd < 0)
		die("open /dev/net/tun");
	ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_VNET_HDR;
	snprintf(ifr.ifr_name, IFNAMSIZ, "vh%d", getpid() % 1000);
	if (ioctl(tfd, TUNSETIFF, &ifr))
		die("TUNSETIFF");
	{
		int hdr_sz = 12;

		if (ioctl(tfd, TUNSETVNETHDRSZ, &hdr_sz))
			die("TUNSETVNETHDRSZ");
	}
	{
		char path[128];
		int fd;

		snprintf(path, sizeof(path),
			 "/proc/sys/net/ipv6/conf/%s/disable_ipv6",
			 ifr.ifr_name);
		fd = open(path, O_WRONLY);
		if (fd >= 0) {
			if (write(fd, "1", 1) < 0) {}
			close(fd);
		}
	}

	sock = socket(AF_INET, SOCK_DGRAM, 0);
	if (sock < 0)
		die("socket");
	if (ioctl(sock, SIOCGIFFLAGS, &ifr))
		die("SIOCGIFFLAGS");
	ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
	if (ioctl(sock, SIOCSIFFLAGS, &ifr))
		die("SIOCSIFFLAGS");
	if (ioctl(sock, SIOCGIFINDEX, &ifr))
		die("SIOCGIFINDEX");
	ifindex = ifr.ifr_ifindex;
	ifr.ifr_mtu = 9000;
	if (ioctl(sock, SIOCSIFMTU, &ifr))
		die("SIOCSIFMTU");

	pkt = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
	if (pkt < 0)
		die("socket packet");
	sll.sll_family = AF_PACKET;
	sll.sll_protocol = htons(ETH_P_ALL);
	sll.sll_ifindex = ifindex;
	if (bind(pkt, (struct sockaddr *)&sll, sizeof(sll)))
		die("bind");

	vfd = open("/dev/vhost-net", O_RDWR);
	if (vfd < 0)
		die("open /dev/vhost-net");
	if (ioctl(vfd, VHOST_SET_OWNER, 0))
		die("VHOST_SET_OWNER");
	memtable.r[0].userspace_addr = (u64)guest_mem;
	if (ioctl(vfd, VHOST_SET_MEM_TABLE, &memtable))
		die("VHOST_SET_MEM_TABLE");
	log_base_ptr = (u64)log_base;
	if (ioctl(vfd, VHOST_SET_LOG_BASE, &log_base_ptr))
		die("VHOST_SET_LOG_BASE");

	features = (1ULL << VIRTIO_NET_F_MRG_RXBUF) |
		   (1ULL << VIRTIO_F_IN_ORDER) |
		   (1ULL << VHOST_F_LOG_ALL);
	if (ioctl(vfd, VHOST_SET_FEATURES, &features))
		die("VHOST_SET_FEATURES");

	kick_fd = eventfd(0, 0);
	call_fd = eventfd(0, 0);
	if (kick_fd < 0 || call_fd < 0)
		die("eventfd");

	vs.num = VQ_NUM;
	if (ioctl(vfd, VHOST_SET_VRING_NUM, &vs))
		die("VHOST_SET_VRING_NUM");
	vs.num = 0;
	if (ioctl(vfd, VHOST_SET_VRING_BASE, &vs))
		die("VHOST_SET_VRING_BASE");

	va.flags = 1U << VHOST_VRING_F_LOG;
	va.desc_user_addr = (u64)desc;
	va.avail_user_addr = (u64)avail;
	va.used_user_addr = (u64)used;
	va.log_guest_addr = IOVA_USED;
	if (ioctl(vfd, VHOST_SET_VRING_ADDR, &va))
		die("VHOST_SET_VRING_ADDR");

	vf.fd = kick_fd;
	if (ioctl(vfd, VHOST_SET_VRING_KICK, &vf))
		die("VHOST_SET_VRING_KICK");
	vf.fd = call_fd;
	if (ioctl(vfd, VHOST_SET_VRING_CALL, &vf))
		die("VHOST_SET_VRING_CALL");
	vf.fd = tfd;
	if (ioctl(vfd, VHOST_NET_SET_BACKEND, &vf))
		die("VHOST_NET_SET_BACKEND");

	memset(frame0, 0xAB, sizeof(frame0));
	memset(frame1, 0xCD, sizeof(frame1));
	frame0[12] = frame1[12] = 0x08;
	frame0[13] = frame1[13] = 0x00;
	if (sendto(pkt, frame0, sizeof(frame0), 0, NULL, 0) != sizeof(frame0))
		die("sendto frame0");
	if (sendto(pkt, frame1, sizeof(frame1), 0, NULL, 0) != sizeof(frame1))
		die("sendto frame1");

	publish_avail(avail, VQ_NUM);
	kick(kick_fd);
	usleep(100 * 1000);
	publish_avail(avail, NHEADS0);
	kick(kick_fd);

	for (int i = 0; i < 5000000 && *(volatile u8 *)(buf0 + 12) == 0; i++)
		;
	publish_avail(avail, TOTAL_AVAIL);

	for (int i = 0; i < 30 && used->idx < TOTAL_AVAIL; i++)
		usleep(100 * 1000);

	printf("avail->idx=%u used->idx=%u log_base[0]=0x%02x log_base[1]=0x%02x\n",
	       avail->idx, used->idx, log_base[0], log_base[1]);
	if (used->idx != TOTAL_AVAIL)
		return 3;
	return log_base[1] ? 2 : 0;
}
---->8----

unpatched: avail->idx=65 used->idx=65 log_base[0]=0x80 log_base[1]=0x01 (exit 2)
patched:   avail->idx=65 used->idx=65 log_base[0]=0x80 log_base[1]=0x00 (exit 0)

Thanks,
YanXin

[-- Attachment #1.2: publickey - fadouse@pm.me - 0x99485AA3.asc --]
[-- Type: application/pgp-keys, Size: 820 bytes --]

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 323 bytes --]

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-23 12:26 ` Eugenio Perez Martin
@ 2026-11-23 12:44   ` fadouse
  2026-11-27 16:51     ` Jiaming Fan
  0 siblings, 1 reply; 9+ messages in thread
From: fadouse @ 2026-11-23 12:44 UTC (permalink / raw)
  To: Eugenio Perez Martin
  Cc: Michael S. Tsirkin, Jason Wang, Linfeng Sun, Fang Xieyan, kvm,
	virtualization, netdev, linux-kernel, stable


[-- Attachment #1.1: Type: text/plain, Size: 2122 bytes --]

Hi Eugenio,

> Although I'm ok with the proposed patch as hardening or optimization,
> this sounds more like a bug in get_rx_bufs. Where are the memory
> addresses for these pieces stored if there are no more buffers in the
> virtqueue? Or is it able to loop through the vq?

Yes — get_rx_bufs() loops around the same virtqueue when a
non-conforming guest advances avail->idx while earlier descriptors are
still in flight.  handle_rx() passes quota = UIO_MAXIOV (1024) for
mergeable RX, and each vhost_get_vq_desc_n() call appends the
translated buffer addresses into vq->iov (also sized to UIO_MAXIOV).
Because vhost_get_avail_idx() compares avail_idx against
vq->last_avail_idx rather than vq->last_used_idx, it rejects only when

  (u16)(avail_idx - vq->last_avail_idx) > vq->num

so the guest can reuse the 32 ring slots mid-packet and get_rx_bufs()
appends those addresses again into vq->iov[32..63], returning
headcount = 64.

Bounding get_rx_bufs() (e.g. capping its quota against vq->num, or
checking in-flight descriptors more broadly) is certainly worth
looking at separately, while keeping the mask in
vhost_add_used_n_in_order() keeps the dirty-logging cursor consistent
with the publishing loop from commit e244725e86be.  If you think a
follow-up check in get_rx_bufs() makes sense, I'm happy to look into
that as a separate patch.

> Can you post the reproducer? Even better if it is integrated in
> tools/virtio/vhost_net_test.c.

I just posted the standalone C reproducer in my reply to Jiaming in
this thread.  Note that tools/virtio/vhost_net_test.c drives the ring
through the conforming vring_new_virtqueue() / virtqueue_add_inbuf()
API, whereas reproducing this requires a raw vring advancing avail->idx
past last_used_idx + vq->num with VIRTIO_F_IN_ORDER |
VIRTIO_NET_F_MRG_RXBUF | VHOST_F_LOG_ALL and VHOST_VRING_F_LOG set in
VHOST_SET_VRING_ADDR.  If you'd still like a raw-vring test case added
under tools/virtio/, I'm happy to include it in a v2 (along with fixing
the minor 262 -> 260 byte used-ring size typo in the commit message).

Thanks,
YanXin

[-- Attachment #1.2: publickey - fadouse@pm.me - 0x99485AA3.asc --]
[-- Type: application/pgp-keys, Size: 820 bytes --]

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 323 bytes --]

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-23 12:44   ` fadouse
@ 2026-11-27 16:51     ` Jiaming Fan
  2026-12-01  8:34       ` fadouse
  0 siblings, 1 reply; 9+ messages in thread
From: Jiaming Fan @ 2026-11-27 16:51 UTC (permalink / raw)
  To: fadouse, Eugenio Perez Martin
  Cc: Michael S. Tsirkin, Jason Wang, virtualization, kvm

> Bounding get_rx_bufs() (e.g. capping its quota against vq->num, or
> checking in-flight descriptors more broadly) is certainly worth
> looking at separately, while keeping the mask in
> vhost_add_used_n_in_order() keeps the dirty-logging cursor consistent
> with the publishing loop from commit e244725e86be.

Hmm, I'd actually go the other way round. Isn't the cap the real fix
here? The mask feels more like hardening to me.

Though the cap changes things for a packet that can't fit even a full
ring. If I read it right, today get_rx_bufs() runs out of descriptors,
rewinds and waits for a refill that never comes, since the guest has
nothing left to post, so the queue just sits there. With the cap it
hits the quota instead and the packet goes down the overrun path and
gets dropped. Probably better, but it's a behavior change, so it'd
need some care not to regress anything... a bit tricky I guess.


^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH] vhost: mask the in-order used-ring log cursor
  2026-11-27 16:51     ` Jiaming Fan
@ 2026-12-01  8:34       ` fadouse
  0 siblings, 0 replies; 9+ messages in thread
From: fadouse @ 2026-12-01  8:34 UTC (permalink / raw)
  To: Jiaming Fan
  Cc: Eugenio Perez Martin, Michael S. Tsirkin, Jason Wang,
	virtualization, kvm


[-- Attachment #1.1: Type: text/plain, Size: 1195 bytes --]

Fair point — capping get_rx_bufs() addresses the RX source of
headcount > vq->num, though the two loops in vhost_add_used_n_in_order()
still shouldn't wrap the same index differently (e244725e86be already
masked the publishing loop for TX, where vhost_tx_batch() can still pass
nheads[0] up to VHOST_NET_BATCH on a 32-entry ring and only avoids the
logging-loop OOB because count == 1).

On the cap behavior, with quota = min(UIO_MAXIOV, vq->num) that's right
for small rings (vq->num <= UIO_MAXIOV) assuming single-segment chains:
hitting d == vq->num before reaching quota still rewinds and waits as
before (and multi-segment chains hitting seg >= UIO_MAXIOV still bail
out with -ENOBUFS), whereas reaching quota with datalen > 0 takes the
UIO_MAXIOV + 1 overrun path and drops the packet (which also does a
1-byte MSG_TRUNC recvmsg into the first rewound buffer, vq->iov[0]).

Because of that behavior change on full-ring overruns, keeping the
one-line mask separate for stable (zero change for conforming guests)
seems safer. I'll send a cleaned-up v2 for the mask patch shortly, and
I'm happy to look at bounding get_rx_bufs() as a separate follow-up.

Thanks,
YanXin

[-- Attachment #1.2: publickey - fadouse@pm.me - 0x99485AA3.asc --]
[-- Type: application/pgp-keys, Size: 820 bytes --]

[-- Attachment #2: OpenPGP digital signature --]
[-- Type: application/pgp-signature, Size: 323 bytes --]

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2026-12-01  8:34 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-22 13:19 [PATCH] vhost: mask the in-order used-ring log cursor YanXin Li
2026-11-22 13:19 ` YanXin Li via B4 Relay
2026-11-22 13:22 ` sashiko-bot
2026-11-23  7:51 ` Jiaming Fan
2026-11-23 12:31   ` fadouse
2026-11-23 12:26 ` Eugenio Perez Martin
2026-11-23 12:44   ` fadouse
2026-11-27 16:51     ` Jiaming Fan
2026-12-01  8:34       ` fadouse

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.