Skip to contentSkip to conversation

net: introduce read_poll/write_poll

PATCH In review Cindy Lu 3 participants 17 messages Feb 7 – Mar 4 Networking

lore
Share & tools
lore

Cindy Lu

author
#0 lore raw

PATCH 1/12 net: introduce read_poll/write_poll

From: Jason Wang <[email protected]>

The existing NetClientInfo::poll() callback enables or disables both read and write polling together. However, some use cases (such as filter-redirector with enable_when_stopped) need finer control to enable only read polling while the VM is stopped, without affecting write polling.

This patch adds separate read_poll() and write_poll() callbacks to NetClientInfo, allowing independent control of read and write fd handlers.

Changes:
- Add NetReadPoll and NetWritePoll typedefs to net/net.h
- Add read_poll and write_poll fields to NetClientInfo
- Rename internal functions (e.g., tap_read_poll -> tap_update_read_poll) to avoid name collision with the new callbacks
- Implement read_poll/write_poll callbacks for tap, af-xdp, l2tpv3, and netmap backends

This infrastructure will be used by filter-redirector to selectively enable backend read polling when the VM is stopped, allowing network traffic to be drained into the netfilter chain during migration pre-switchover.

---
 include/net/net.h |  4 ++++
 net/af-xdp.c      | 32 +++++++++++++++++++++++---------
 net/l2tpv3.c      | 38 ++++++++++++++++++++++++++------------
 net/netmap.c      | 30 ++++++++++++++++++++++--------
 net/tap.c         | 36 +++++++++++++++++++++++++-----------
 5 files changed, 100 insertions(+), 40 deletions(-)
include/net/net.h +4 -0
index 72b476ee1d..d2b2e6fc44 100644
@@ -55,6 +55,8 @@ typedef struct NetOffloads {
 /* Net clients */
 
 typedef void (NetPoll)(NetClientState *, bool enable);
+typedef void (NetReadPoll)(NetClientState *, bool enable);
+typedef void (NetWritePoll)(NetClientState *, bool enable);
 typedef bool (NetCanReceive)(NetClientState *);
 typedef int (NetStart)(NetClientState *);
 typedef int (NetLoad)(NetClientState *);
@@ -96,6 +98,8 @@ typedef struct NetClientInfo {
     LinkStatusChanged *link_status_changed;
     QueryRxFilter *query_rx_filter;
     NetPoll *poll;
+    NetReadPoll *read_poll;
+    NetWritePoll *write_poll;
     HasUfo *has_ufo;
     HasUso *has_uso;
     HasTunnel *has_tunnel;
net/af-xdp.c +23 -9
index 14f302ea21..b6e50b698f 100644
@@ -72,7 +72,7 @@ static void af_xdp_update_fd_handler(AFXDPState *s)
 }
 
 /* Update the read handler. */
-static void af_xdp_read_poll(AFXDPState *s, bool enable)
+static void af_xdp_update_read_poll(AFXDPState *s, bool enable)
 {
     if (s->read_poll != enable) {
         s->read_poll = enable;
@@ -81,7 +81,7 @@ static void af_xdp_read_poll(AFXDPState *s, bool enable)
 }
 
 /* Update the write handler. */
-static void af_xdp_write_poll(AFXDPState *s, bool enable)
+static void af_xdp_update_write_poll(AFXDPState *s, bool enable)
 {
     if (s->write_poll != enable) {
         s->write_poll = enable;
@@ -100,6 +100,18 @@ static void af_xdp_poll(NetClientState *nc, bool enable)
     }
 }
 
+static void af_xdp_read_poll(NetClientState *nc, bool enable)
+{
+    AFXDPState *s = DO_UPCAST(AFXDPState, nc, nc);
+    af_xdp_update_read_poll(s, enable);
+}
+
+static void af_xdp_write_poll(NetClientState *nc, bool enable)
+{
+    AFXDPState *s = DO_UPCAST(AFXDPState, nc, nc);
+    af_xdp_update_write_poll(s, enable);
+}
+
 static void af_xdp_complete_tx(AFXDPState *s)
 {
     uint32_t idx = 0;
@@ -135,7 +147,7 @@ static void af_xdp_writable(void *opaque)
      * and kernel needs a wake up.
      */
     if (!s->outstanding_tx || !xsk_ring_prod__needs_wakeup(&s->tx)) {
-        af_xdp_write_poll(s, false);
+        af_xdp_update_write_poll(s, false);
     }
 
     /* Flush any buffered packets. */
@@ -163,7 +175,7 @@ static ssize_t af_xdp_receive(NetClientState *nc,
          * Out of buffers or space in tx ring.  Poll until we can write.
          * This will also kick the Tx, if it was waiting on CQ.
          */
-        af_xdp_write_poll(s, true);
+        af_xdp_update_write_poll(s, true);
         return 0;
     }
 
@@ -178,7 +190,7 @@ static ssize_t af_xdp_receive(NetClientState *nc,
     s->outstanding_tx++;
 
     if (xsk_ring_prod__needs_wakeup(&s->tx)) {
-        af_xdp_write_poll(s, true);
+        af_xdp_update_write_poll(s, true);
     }
 
     return size;
@@ -192,7 +204,7 @@ static void af_xdp_send_completed(NetClientState *nc, ssize_t len)
 {
     AFXDPState *s = DO_UPCAST(AFXDPState, nc, nc);
 
-    af_xdp_read_poll(s, true);
+    af_xdp_update_read_poll(s, true);
 }
 
 static void af_xdp_fq_refill(AFXDPState *s, uint32_t n)
@@ -215,7 +227,7 @@ static void af_xdp_fq_refill(AFXDPState *s, uint32_t n)
 
     if (xsk_ring_prod__needs_wakeup(&s->fq)) {
         /* Receive was blocked by not having enough buffers.  Wake it up. */
-        af_xdp_read_poll(s, true);
+        af_xdp_update_read_poll(s, true);
     }
 }
 
@@ -246,7 +258,7 @@ static void af_xdp_send(void *opaque)
              * The peer does not receive anymore.  Packet is queued, stop
              * reading from the backend until af_xdp_send_completed().
              */
-            af_xdp_read_poll(s, false);
+            af_xdp_update_read_poll(s, false);
 
             /* Return unused descriptors to not break the ring cache. */
             xsk_ring_cons__cancel(&s->rx, n_rx - i - 1);
@@ -438,6 +450,8 @@ static NetClientInfo net_af_xdp_info = {
     .size = sizeof(AFXDPState),
     .receive = af_xdp_receive,
     .poll = af_xdp_poll,
+    .read_poll = af_xdp_read_poll,
+    .write_poll = af_xdp_write_poll,
     .cleanup = af_xdp_cleanup,
 };
 
@@ -571,7 +585,7 @@ int net_init_af_xdp(const Netdev *netdev,
         }
     }
 
-    af_xdp_read_poll(s, true); /* Initially only poll for reads. */
+    af_xdp_update_read_poll(s, true); /* Initially only poll for reads. */
 
     return 0;
 
net/l2tpv3.c +26 -12
index cdfc641aa6..9f24982a94 100644
@@ -143,7 +143,7 @@ static void l2tpv3_update_fd_handler(NetL2TPV3State *s)
                         s);
 }
 
-static void l2tpv3_read_poll(NetL2TPV3State *s, bool enable)
+static void l2tpv3_update_read_poll(NetL2TPV3State *s, bool enable)
 {
     if (s->read_poll != enable) {
         s->read_poll = enable;
@@ -151,7 +151,7 @@ static void l2tpv3_read_poll(NetL2TPV3State *s, bool enable)
     }
 }
 
-static void l2tpv3_write_poll(NetL2TPV3State *s, bool enable)
+static void l2tpv3_update_write_poll(NetL2TPV3State *s, bool enable)
 {
     if (s->write_poll != enable) {
         s->write_poll = enable;
@@ -162,21 +162,33 @@ static void l2tpv3_write_poll(NetL2TPV3State *s, bool enable)
 static void l2tpv3_writable(void *opaque)
 {
     NetL2TPV3State *s = opaque;
-    l2tpv3_write_poll(s, false);
+    l2tpv3_update_write_poll(s, false);
     qemu_flush_queued_packets(&s->nc);
 }
 
 static void l2tpv3_send_completed(NetClientState *nc, ssize_t len)
 {
     NetL2TPV3State *s = DO_UPCAST(NetL2TPV3State, nc, nc);
-    l2tpv3_read_poll(s, true);
+    l2tpv3_update_read_poll(s, true);
 }
 
 static void l2tpv3_poll(NetClientState *nc, bool enable)
 {
     NetL2TPV3State *s = DO_UPCAST(NetL2TPV3State, nc, nc);
-    l2tpv3_write_poll(s, enable);
-    l2tpv3_read_poll(s, enable);
+    l2tpv3_update_write_poll(s, enable);
+    l2tpv3_update_read_poll(s, enable);
+}
+
+static void l2tpv3_read_poll(NetClientState *nc, bool enable)
+{
+    NetL2TPV3State *s = DO_UPCAST(NetL2TPV3State, nc, nc);
+    l2tpv3_update_read_poll(s, enable);
+}
+
+static void l2tpv3_write_poll(NetClientState *nc, bool enable)
+{
+    NetL2TPV3State *s = DO_UPCAST(NetL2TPV3State, nc, nc);
+    l2tpv3_update_write_poll(s, enable);
 }
 
 static void l2tpv3_form_header(NetL2TPV3State *s)
@@ -252,7 +264,7 @@ static ssize_t net_l2tpv3_receive_dgram_iov(NetClientState *nc,
         /* signal upper layer that socket buffer is full */
         ret = -errno;
         if (ret == -EAGAIN || ret == -ENOBUFS) {
-            l2tpv3_write_poll(s, true);
+            l2tpv3_update_write_poll(s, true);
             ret = 0;
         }
     }
@@ -295,7 +307,7 @@ static ssize_t net_l2tpv3_receive_dgram(NetClientState *nc,
         ret = -errno;
         if (ret == -EAGAIN || ret == -ENOBUFS) {
             /* signal upper layer that socket buffer is full */
-            l2tpv3_write_poll(s, true);
+            l2tpv3_update_write_poll(s, true);
             ret = 0;
         }
     }
@@ -369,7 +381,7 @@ static void net_l2tpv3_process_queue(NetL2TPV3State *s)
                             l2tpv3_send_completed
                         );
                     if (size == 0) {
-                        l2tpv3_read_poll(s, false);
+                        l2tpv3_update_read_poll(s, false);
                     }
                     bad_read = false;
                 } else {
@@ -497,8 +509,8 @@ static void net_l2tpv3_cleanup(NetClientState *nc)
 {
     NetL2TPV3State *s = DO_UPCAST(NetL2TPV3State, nc, nc);
     qemu_purge_queued_packets(nc);
-    l2tpv3_read_poll(s, false);
-    l2tpv3_write_poll(s, false);
+    l2tpv3_update_read_poll(s, false);
+    l2tpv3_update_write_poll(s, false);
     if (s->fd >= 0) {
         close(s->fd);
     }
@@ -514,6 +526,8 @@ static NetClientInfo net_l2tpv3_info = {
     .receive = net_l2tpv3_receive_dgram,
     .receive_iov = net_l2tpv3_receive_dgram_iov,
     .poll = l2tpv3_poll,
+    .read_poll = l2tpv3_read_poll,
+    .write_poll = l2tpv3_write_poll,
     .cleanup = net_l2tpv3_cleanup,
 };
 
@@ -715,7 +729,7 @@ int net_init_l2tpv3(const Netdev *netdev,
     s->fd = fd;
     s->counter = 0;
 
-    l2tpv3_read_poll(s, true);
+    l2tpv3_update_read_poll(s, true);
 
     qemu_set_info_str(&s->nc, "l2tpv3: connected");
     return 0;
net/netmap.c +22 -8
index 6cd8f2bdc5..2e2a95a256 100644
@@ -113,7 +113,7 @@ static void netmap_update_fd_handler(NetmapState *s)
 }
 
 /* Update the read handler. */
-static void netmap_read_poll(NetmapState *s, bool enable)
+static void netmap_update_read_poll(NetmapState *s, bool enable)
 {
     if (s->read_poll != enable) { /* Do nothing if not changed. */
         s->read_poll = enable;
@@ -122,7 +122,7 @@ static void netmap_read_poll(NetmapState *s, bool enable)
 }
 
 /* Update the write handler. */
-static void netmap_write_poll(NetmapState *s, bool enable)
+static void netmap_update_write_poll(NetmapState *s, bool enable)
 {
     if (s->write_poll != enable) {
         s->write_poll = enable;
@@ -141,6 +141,18 @@ static void netmap_poll(NetClientState *nc, bool enable)
     }
 }
 
+static void netmap_read_poll(NetClientState *nc, bool enable)
+{
+    NetmapState *s = DO_UPCAST(NetmapState, nc, nc);
+    netmap_update_read_poll(s, enable);
+}
+
+static void netmap_write_poll(NetClientState *nc, bool enable)
+{
+    NetmapState *s = DO_UPCAST(NetmapState, nc, nc);
+    netmap_update_write_poll(s, enable);
+}
+
 /*
  * The fd_write() callback, invoked if the fd is marked as
  * writable after a poll. Unregister the handler and flush any
@@ -150,7 +162,7 @@ static void netmap_writable(void *opaque)
 {
     NetmapState *s = opaque;
 
-    netmap_write_poll(s, false);
+    netmap_update_write_poll(s, false);
     qemu_flush_queued_packets(&s->nc);
 }
 
@@ -175,7 +187,7 @@ static ssize_t netmap_receive_iov(NetClientState *nc,
          * ones), but without publishing any new slots to be processed
          * (e.g., we don't advance ring->head). */
         ring->cur = tail;
-        netmap_write_poll(s, true);
+        netmap_update_write_poll(s, true);
         return 0;
     }
 
@@ -195,7 +207,7 @@ static ssize_t netmap_receive_iov(NetClientState *nc,
                 /* We ran out of netmap slots while splitting the
                    iovec fragments. */
                 ring->cur = tail;
-                netmap_write_poll(s, true);
+                netmap_update_write_poll(s, true);
                 return 0;
             }
 
@@ -242,7 +254,7 @@ static void netmap_send_completed(NetClientState *nc, ssize_t len)
 {
     NetmapState *s = DO_UPCAST(NetmapState, nc, nc);
 
-    netmap_read_poll(s, true);
+    netmap_update_read_poll(s, true);
 }
 
 static void netmap_send(void *opaque)
@@ -289,7 +301,7 @@ static void netmap_send(void *opaque)
         if (iovsize == 0) {
             /* The peer does not receive anymore. Packet is queued, stop
              * reading from the backend until netmap_send_completed(). */
-            netmap_read_poll(s, false);
+            netmap_update_read_poll(s, false);
             break;
         }
     }
@@ -384,6 +396,8 @@ static NetClientInfo net_netmap_info = {
     .receive = netmap_receive,
     .receive_iov = netmap_receive_iov,
     .poll = netmap_poll,
+    .read_poll = netmap_read_poll,
+    .write_poll = netmap_write_poll,
     .cleanup = netmap_cleanup,
     .has_ufo = netmap_has_vnet_hdr,
     .has_vnet_hdr = netmap_has_vnet_hdr,
@@ -418,7 +432,7 @@ int net_init_netmap(const Netdev *netdev,
     s->rx = NETMAP_RXRING(nmd->nifp, 0);
     s->vnet_hdr_len = 0;
     pstrcpy(s->ifname, sizeof(s->ifname), netmap_opts->ifname);
-    netmap_read_poll(s, true); /* Initially only poll for reads. */
+    netmap_update_read_poll(s, true); /* Initially only poll for reads. */
 
     return 0;
 }
net/tap.c +25 -11
index abe3b2d036..c2e7e4d1d8 100644
@@ -99,13 +99,13 @@ static void tap_update_fd_handler(TAPState *s)
                         s);
 }
 
-static void tap_read_poll(TAPState *s, bool enable)
+static void tap_update_read_poll(TAPState *s, bool enable)
 {
     s->read_poll = enable;
     tap_update_fd_handler(s);
 }
 
-static void tap_write_poll(TAPState *s, bool enable)
+static void tap_update_write_poll(TAPState *s, bool enable)
 {
     s->write_poll = enable;
     tap_update_fd_handler(s);
@@ -115,7 +115,7 @@ static void tap_writable(void *opaque)
 {
     TAPState *s = opaque;
 
-    tap_write_poll(s, false);
+    tap_update_write_poll(s, false);
 
     qemu_flush_queued_packets(&s->nc);
 }
@@ -127,7 +127,7 @@ static ssize_t tap_write_packet(TAPState *s, const struct iovec *iov, int iovcnt
     len = RETRY_ON_EINTR(writev(s->fd, iov, iovcnt));
 
     if (len == -1 && errno == EAGAIN) {
-        tap_write_poll(s, true);
+        tap_update_write_poll(s, true);
         return 0;
     }
 
@@ -174,7 +174,7 @@ ssize_t tap_read_packet(int tapfd, uint8_t *buf, int maxlen)
 static void tap_send_completed(NetClientState *nc, ssize_t len)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
-    tap_read_poll(s, true);
+    tap_update_read_poll(s, true);
 }
 
 static void tap_send(void *opaque)
@@ -212,7 +212,7 @@ static void tap_send(void *opaque)
 
         size = qemu_send_packet_async(&s->nc, buf, size, tap_send_completed);
         if (size == 0) {
-            tap_read_poll(s, false);
+            tap_update_read_poll(s, false);
             break;
         } else if (size < 0) {
             break;
@@ -334,8 +334,8 @@ static void tap_cleanup(NetClientState *nc)
     tap_exit_notify(&s->exit, NULL);
     qemu_remove_exit_notifier(&s->exit);
 
-    tap_read_poll(s, false);
-    tap_write_poll(s, false);
+    tap_update_read_poll(s, false);
+    tap_update_write_poll(s, false);
     close(s->fd);
     s->fd = -1;
 }
@@ -343,8 +343,20 @@ static void tap_cleanup(NetClientState *nc)
 static void tap_poll(NetClientState *nc, bool enable)
 {
     TAPState *s = DO_UPCAST(TAPState, nc, nc);
-    tap_read_poll(s, enable);
-    tap_write_poll(s, enable);
+    tap_update_read_poll(s, enable);
+    tap_update_write_poll(s, enable);
+}
+
+static void tap_read_poll(NetClientState *nc, bool enable)
+{
+    TAPState *s = DO_UPCAST(TAPState, nc, nc);
+    tap_update_read_poll(s, enable);
+}
+
+static void tap_write_poll(NetClientState *nc, bool enable)
+{
+    TAPState *s = DO_UPCAST(TAPState, nc, nc);
+    tap_update_write_poll(s, enable);
 }
 
 static bool tap_set_steering_ebpf(NetClientState *nc, int prog_fd)
@@ -382,6 +394,8 @@ static NetClientInfo net_tap_info = {
     .receive = tap_receive,
     .receive_iov = tap_receive_iov,
     .poll = tap_poll,
+    .read_poll = tap_read_poll,
+    .write_poll = tap_write_poll,
     .cleanup = tap_cleanup,
     .has_ufo = tap_has_ufo,
     .has_uso = tap_has_uso,
@@ -425,7 +439,7 @@ static TAPState *net_tap_fd_init(NetClientState *peer,
     if (vnet_hdr) {
         tap_fd_set_vnet_hdr_len(s->fd, s->host_vnet_hdr_len);
     }
-    tap_read_poll(s, true);
+    tap_update_read_poll(s, true);
     s->vhost_net = NULL;
 
     s->exit.notify = tap_exit_notify;
Signature · 1 line
2.52.0
author
#1 lore raw

PATCH 2/12 net/filter-mirror: add enable_when_stopped option for filter-redirector

From: Jason Wang <[email protected]>

Add a QAPI option 'enable_when_stopped' for filter-redirector that allows it to continue receiving data from netdev when VM is stopped.

When enabled, a VM state change handler activates the netdev's read_poll() when VM stops, allowing the netdev to continue reading data and passing it through filter-redirector to the chardev output.

This is useful for scenarios where filter-redirector needs to process network traffic even when the VM is paused.

Usage:
-object filter-redirector,id=f0,netdev=net0,queue=tx,\
outdev=chardev0,enable_when_stopped=true

---
 net/filter-mirror.c                  |  38 ++++++++++
 qapi/qom.json                        |   7 +-
 tests/qtest/test-filter-redirector.c | 106 +++++++++++++++++++++++++++
 3 files changed, 150 insertions(+), 1 deletion(-)
net/filter-mirror.c +38 -0
index aa2ab452fd..e1a0650abd 100644
@@ -21,6 +21,7 @@
 #include "qemu/iov.h"
 #include "qemu/sockets.h"
 #include "block/aio-wait.h"
+#include "system/runstate.h"
 
 #define TYPE_FILTER_MIRROR "filter-mirror"
 typedef struct MirrorState MirrorState;
@@ -41,6 +42,8 @@ struct MirrorState {
     CharFrontend chr_out;
     SocketReadState rs;
     bool vnet_hdr;
+    bool enable_when_stopped;
+    VMChangeStateEntry *vmsentry;
 };
 
 typedef struct FilterSendCo {
@@ -251,6 +254,7 @@ static void filter_redirector_cleanup(NetFilterState *nf)
 
     qemu_chr_fe_deinit(&s->chr_in, false);
     qemu_chr_fe_deinit(&s->chr_out, false);
+    qemu_del_vm_change_state_handler(s->vmsentry);
 }
 
 static void filter_mirror_setup(NetFilterState *nf, Error **errp)
@@ -282,6 +286,18 @@ static void redirector_rs_finalize(SocketReadState *rs)
     redirector_to_filter(nf, rs->buf, rs->packet_len);
 }
 
+static void filter_redirector_vm_state_change(void *opaque, bool running,
+                                              RunState state)
+{
+    NetFilterState *nf = opaque;
+    MirrorState *s = FILTER_REDIRECTOR(nf);
+    NetClientState *nc = nf->netdev;
+
+    if (!running && s->enable_when_stopped && nc->info->read_poll) {
+        nc->info->read_poll(nc, true);
+    }
+}
+
 static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(nf);
@@ -331,6 +347,9 @@ static void filter_redirector_setup(NetFilterState *nf, Error **errp)
             return;
         }
     }
+
+    s->vmsentry = qemu_add_vm_change_state_handler(
+        filter_redirector_vm_state_change, nf);
 }
 
 static void filter_redirector_status_changed(NetFilterState *nf, Error **errp)
@@ -437,6 +456,22 @@ static void filter_redirector_set_vnet_hdr(Object *obj,
     s->vnet_hdr = value;
 }
 
+static bool filter_redirector_get_enable_when_stopped(Object *obj, Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    return s->enable_when_stopped;
+}
+
+static void filter_redirector_set_enable_when_stopped(Object *obj,
+                                                      bool value,
+                                                      Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    s->enable_when_stopped = value;
+}
+
 static void filter_mirror_class_init(ObjectClass *oc, const void *data)
 {
     NetFilterClass *nfc = NETFILTER_CLASS(oc);
@@ -463,6 +498,9 @@ static void filter_redirector_class_init(ObjectClass *oc, const void *data)
     object_class_property_add_bool(oc, "vnet_hdr_support",
                                    filter_redirector_get_vnet_hdr,
                                    filter_redirector_set_vnet_hdr);
+    object_class_property_add_bool(oc, "enable_when_stopped",
+                                   filter_redirector_get_enable_when_stopped,
+                                   filter_redirector_set_enable_when_stopped);
 
     nfc->setup = filter_redirector_setup;
     nfc->cleanup = filter_redirector_cleanup;
qapi/qom.json +6 -1
index 6f5c9de0f0..b1fe55944c 100644
@@ -488,13 +488,18 @@
 # @vnet_hdr_support: if true, vnet header support is enabled
 #     (default: false)
 #
+# @enable_when_stopped: if true, activate netdev's read poll when VM
+#     stops to allow filter-redirector to continue receiving data
+#     (default: false)
+#
 # Since: 2.6
 ##
 { 'struct': 'FilterRedirectorProperties',
   'base': 'NetfilterProperties',
   'data': { '*indev': 'str',
             '*outdev': 'str',
-            '*vnet_hdr_support': 'bool' } }
+            '*vnet_hdr_support': 'bool',
+            '*enable_when_stopped': 'bool' } }
 
 ##
 # @FilterRewriterProperties:
tests/qtest/test-filter-redirector.c +106 -0

117 lines not on this page · raw message

Signature · 1 line
2.52.0
#2 lore raw

Re: [PATCH 02/12] net/filter-mirror: add enable_when_stopped option for filter-redirector

Quoted 10 lines · Cindy Lu

From: Jason Wang <[email protected]>

Add a QAPI option 'enable_when_stopped' for filter-redirector that allows it to continue receiving data from netdev when VM is stopped.

When enabled, a VM state change handler activates the netdev's read_poll() when VM stops, allowing the netdev to continue reading data and passing it through filter-redirector to the chardev output.

Quoted 7 lines

This is useful for scenarios where filter-redirector needs to process network traffic even when the VM is paused.

Usage:
-object filter-redirector,id=f0,netdev=net0,queue=tx,\
outdev=chardev0,enable_when_stopped=true

It seems this series is trying to address previous VM migration network related issues that Juraj Marcin mentioned.
Add CC to him.

I've taken a quick look, and this series lacks support for filter-reply and filter-rewriter.
Could there be a reason for this?

Thanks
Chen

.

Quoted 249 lines
---
 net/filter-mirror.c                  |  38 ++++++++++
 qapi/qom.json                        |   7 +-
 tests/qtest/test-filter-redirector.c | 106 +++++++++++++++++++++++++++
 3 files changed, 150 insertions(+), 1 deletion(-)
net/filter-mirror.c +38 -0
index aa2ab452fd..e1a0650abd 100644
@@ -21,6 +21,7 @@
 #include "qemu/iov.h"
 #include "qemu/sockets.h"
 #include "block/aio-wait.h"
+#include "system/runstate.h"
 
 #define TYPE_FILTER_MIRROR "filter-mirror"
 typedef struct MirrorState MirrorState;
@@ -41,6 +42,8 @@ struct MirrorState {
     CharFrontend chr_out;
     SocketReadState rs;
     bool vnet_hdr;
+    bool enable_when_stopped;
+    VMChangeStateEntry *vmsentry;
 };
 
 typedef struct FilterSendCo {
@@ -251,6 +254,7 @@ static void filter_redirector_cleanup(NetFilterState *nf)
 
     qemu_chr_fe_deinit(&s->chr_in, false);
     qemu_chr_fe_deinit(&s->chr_out, false);
+    qemu_del_vm_change_state_handler(s->vmsentry);
 }
 
 static void filter_mirror_setup(NetFilterState *nf, Error **errp)
@@ -282,6 +286,18 @@ static void redirector_rs_finalize(SocketReadState *rs)
     redirector_to_filter(nf, rs->buf, rs->packet_len);
 }
 
+static void filter_redirector_vm_state_change(void *opaque, bool running,
+                                              RunState state)
+{
+    NetFilterState *nf = opaque;
+    MirrorState *s = FILTER_REDIRECTOR(nf);
+    NetClientState *nc = nf->netdev;
+
+    if (!running && s->enable_when_stopped && nc->info->read_poll) {
+        nc->info->read_poll(nc, true);
+    }
+}
+
 static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(nf);
@@ -331,6 +347,9 @@ static void filter_redirector_setup(NetFilterState *nf, Error **errp)
             return;
         }
     }
+
+    s->vmsentry = qemu_add_vm_change_state_handler(
+        filter_redirector_vm_state_change, nf);
 }
 
 static void filter_redirector_status_changed(NetFilterState *nf, Error **errp)
@@ -437,6 +456,22 @@ static void filter_redirector_set_vnet_hdr(Object *obj,
     s->vnet_hdr = value;
 }
 
+static bool filter_redirector_get_enable_when_stopped(Object *obj, Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    return s->enable_when_stopped;
+}
+
+static void filter_redirector_set_enable_when_stopped(Object *obj,
+                                                      bool value,
+                                                      Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    s->enable_when_stopped = value;
+}
+
 static void filter_mirror_class_init(ObjectClass *oc, const void *data)
 {
     NetFilterClass *nfc = NETFILTER_CLASS(oc);
@@ -463,6 +498,9 @@ static void filter_redirector_class_init(ObjectClass *oc, const void *data)
     object_class_property_add_bool(oc, "vnet_hdr_support",
                                    filter_redirector_get_vnet_hdr,
                                    filter_redirector_set_vnet_hdr);
+    object_class_property_add_bool(oc, "enable_when_stopped",
+                                   filter_redirector_get_enable_when_stopped,
+                                   filter_redirector_set_enable_when_stopped);
 
     nfc->setup = filter_redirector_setup;
     nfc->cleanup = filter_redirector_cleanup;
qapi/qom.json +6 -1
index 6f5c9de0f0..b1fe55944c 100644
@@ -488,13 +488,18 @@
 # @vnet_hdr_support: if true, vnet header support is enabled
 #     (default: false)
 #
+# @enable_when_stopped: if true, activate netdev's read poll when VM
+#     stops to allow filter-redirector to continue receiving data
+#     (default: false)
+#
 # Since: 2.6
 ##
 { 'struct': 'FilterRedirectorProperties',
   'base': 'NetfilterProperties',
   'data': { '*indev': 'str',
             '*outdev': 'str',
-            '*vnet_hdr_support': 'bool' } }
+            '*vnet_hdr_support': 'bool',
+            '*enable_when_stopped': 'bool' } }
 
 ##
 # @FilterRewriterProperties:
tests/qtest/test-filter-redirector.c +106 -1
index 5540c232c0..fa958bb0a5 100644
@@ -385,6 +385,110 @@ static void test_redirector_init_status_off(void)
     qtest_quit(qts);
 }
 
+/*
+ * Test filter-redirector works when VM is stopped (TX direction).
+ *
+ * This test verifies that when VM is stopped, the filter-redirector
+ * can still receive data from the netdev because the VM state change
+ * handler activates the netdev's read_poll(). Data flows from netdev
+ * to filter-redirector and out through the chardev.
+ *
+ * Data flow: backend_sock -> netdev (read_poll) -> filter-redirector -> chardev
+ */
+static void test_redirector_with_vm_stop(void)
+{
+    int backend_sock[2], recv_sock;
+    uint32_t ret = 0, len = 0;
+    char send_buf[] = "Hello!!";
+    char sock_path0[] = "filter-redirector0.XXXXXX";
+    char *recv_buf;
+    uint32_t size = sizeof(send_buf);
+    size = htonl(size);
+    QTestState *qts;
+    struct timeval tv;
+    fd_set rfds;
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, backend_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = mkstemp(sock_path0);
+    g_assert_cmpint(ret, !=, -1);
+
+    /*
+     * Setup TX path: netdev -> filter-redirector -> chardev
+     * Data sent to backend_sock[0] will be read by the netdev,
+     * passed through filter-redirector, and output to sock_path0.
+     * Enable enable_when_stopped to activate read_poll when VM stops.
+     */
+    qts = qtest_initf(
+        "-nic socket,id=qtest-bn0,fd=%d "
+        "-chardev socket,id=redirector0,path=%s,server=on,wait=off "
+        "-object filter-redirector,id=qtest-f0,netdev=qtest-bn0,"
+        "queue=tx,outdev=redirector0,enable_when_stopped=true ",
+        backend_sock[1], sock_path0);
+
+    recv_sock = unix_connect(sock_path0, NULL);
+    g_assert_cmpint(recv_sock, !=, -1);
+
+    /* Ensure connection is established */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    struct iovec iov[] = {
+        {
+            .iov_base = &size,
+            .iov_len = sizeof(size),
+        }, {
+            .iov_base = send_buf,
+            .iov_len = sizeof(send_buf),
+        },
+    };
+
+    /*
+     * Stop the VM - this triggers our vm_state_change handler
+     * which should activate the netdev's read_poll()
+     */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'stop'}");
+
+    /* Wait for VM to actually stop */
+    qtest_qmp_eventwait(qts, "STOP");
+
+    /*
+     * Send data to backend socket while VM is stopped.
+     * The netdev should still read the data (because read_poll is
+     * activated by our vm_state_change handler), pass it through
+     * filter-redirector, and output to the chardev.
+     */
+    ret = iov_send(backend_sock[0], iov, 2, 0, sizeof(size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(size));
+
+    /*
+     * Data should arrive at recv_sock even with VM stopped,
+     * because read_poll is activated.
+     */
+    FD_ZERO(&rfds);
+    FD_SET(recv_sock, &rfds);
+    tv.tv_sec = 5;
+    tv.tv_usec = 0;
+    ret = select(recv_sock + 1, &rfds, NULL, NULL, &tv);
+    g_assert_cmpint(ret, ==, 1);  /* Data should arrive */
+
+    ret = recv(recv_sock, &len, sizeof(len), 0);
+    g_assert_cmpint(ret, ==, sizeof(len));
+    len = ntohl(len);
+
+    g_assert_cmpint(len, ==, sizeof(send_buf));
+    recv_buf = g_malloc(len);
+    ret = recv(recv_sock, recv_buf, len, 0);
+    g_assert_cmpint(ret, ==, len);
+    g_assert_cmpstr(recv_buf, ==, send_buf);
+
+    g_free(recv_buf);
+    close(recv_sock);
+    close(backend_sock[0]);
+    unlink(sock_path0);
+    qtest_quit(qts);
+}
+
 static void test_redirector_rx_event_opened(void)
 {
     int backend_sock[2], send_sock;
@@ -489,5 +593,7 @@ int main(int argc, char **argv)
                    test_redirector_init_status_off);
     qtest_add_func("/netfilter/redirector_rx_event_opened",
                    test_redirector_rx_event_opened);
+    qtest_add_func("/netfilter/redirector_with_vm_stop",
+                   test_redirector_with_vm_stop);
     return g_test_run();
 }
--

2.52.0

author
#3 lore raw

Re: [PATCH 02/12] net/filter-mirror: add enable_when_stopped option for filter-redirector

Quoted 24 lines · Zhang Chen
Quoted 10 lines · Cindy Lu

From: Jason Wang <[email protected]>

Add a QAPI option 'enable_when_stopped' for filter-redirector that allows it to continue receiving data from netdev when VM is stopped.

When enabled, a VM state change handler activates the netdev's read_poll() when VM stops, allowing the netdev to continue reading data and passing it through filter-redirector to the chardev output.

Quoted 7 lines

This is useful for scenarios where filter-redirector needs to process network traffic even when the VM is paused.

Usage:
-object filter-redirector,id=f0,netdev=net0,queue=tx,\
outdev=chardev0,enable_when_stopped=true

It seems this series is trying to address previous VM migration network related issues that Juraj Marcin mentioned.
Add CC to him.

Quoted 7 lines

I've taken a quick look, and this series lacks support for filter-reply and filter-rewriter.
Could there be a reason for this?

Thanks
Chen

Hi Chen
For this RFC, filter-reply and filter-rewriter is not need, I will add support for them later.
Thanks
cindy

Quoted 255 lines

.

Quoted 249 lines
---
 net/filter-mirror.c                  |  38 ++++++++++
 qapi/qom.json                        |   7 +-
 tests/qtest/test-filter-redirector.c | 106 +++++++++++++++++++++++++++
 3 files changed, 150 insertions(+), 1 deletion(-)
net/filter-mirror.c +38 -0
index aa2ab452fd..e1a0650abd 100644
@@ -21,6 +21,7 @@
 #include "qemu/iov.h"
 #include "qemu/sockets.h"
 #include "block/aio-wait.h"
+#include "system/runstate.h"
 
 #define TYPE_FILTER_MIRROR "filter-mirror"
 typedef struct MirrorState MirrorState;
@@ -41,6 +42,8 @@ struct MirrorState {
     CharFrontend chr_out;
     SocketReadState rs;
     bool vnet_hdr;
+    bool enable_when_stopped;
+    VMChangeStateEntry *vmsentry;
 };
 
 typedef struct FilterSendCo {
@@ -251,6 +254,7 @@ static void filter_redirector_cleanup(NetFilterState *nf)
 
     qemu_chr_fe_deinit(&s->chr_in, false);
     qemu_chr_fe_deinit(&s->chr_out, false);
+    qemu_del_vm_change_state_handler(s->vmsentry);
 }
 
 static void filter_mirror_setup(NetFilterState *nf, Error **errp)
@@ -282,6 +286,18 @@ static void redirector_rs_finalize(SocketReadState *rs)
     redirector_to_filter(nf, rs->buf, rs->packet_len);
 }
 
+static void filter_redirector_vm_state_change(void *opaque, bool running,
+                                              RunState state)
+{
+    NetFilterState *nf = opaque;
+    MirrorState *s = FILTER_REDIRECTOR(nf);
+    NetClientState *nc = nf->netdev;
+
+    if (!running && s->enable_when_stopped && nc->info->read_poll) {
+        nc->info->read_poll(nc, true);
+    }
+}
+
 static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(nf);
@@ -331,6 +347,9 @@ static void filter_redirector_setup(NetFilterState *nf, Error **errp)
             return;
         }
     }
+
+    s->vmsentry = qemu_add_vm_change_state_handler(
+        filter_redirector_vm_state_change, nf);
 }
 
 static void filter_redirector_status_changed(NetFilterState *nf, Error **errp)
@@ -437,6 +456,22 @@ static void filter_redirector_set_vnet_hdr(Object *obj,
     s->vnet_hdr = value;
 }
 
+static bool filter_redirector_get_enable_when_stopped(Object *obj, Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    return s->enable_when_stopped;
+}
+
+static void filter_redirector_set_enable_when_stopped(Object *obj,
+                                                      bool value,
+                                                      Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    s->enable_when_stopped = value;
+}
+
 static void filter_mirror_class_init(ObjectClass *oc, const void *data)
 {
     NetFilterClass *nfc = NETFILTER_CLASS(oc);
@@ -463,6 +498,9 @@ static void filter_redirector_class_init(ObjectClass *oc, const void *data)
     object_class_property_add_bool(oc, "vnet_hdr_support",
                                    filter_redirector_get_vnet_hdr,
                                    filter_redirector_set_vnet_hdr);
+    object_class_property_add_bool(oc, "enable_when_stopped",
+                                   filter_redirector_get_enable_when_stopped,
+                                   filter_redirector_set_enable_when_stopped);
 
     nfc->setup = filter_redirector_setup;
     nfc->cleanup = filter_redirector_cleanup;
qapi/qom.json +6 -1
index 6f5c9de0f0..b1fe55944c 100644
@@ -488,13 +488,18 @@
 # @vnet_hdr_support: if true, vnet header support is enabled
 #     (default: false)
 #
+# @enable_when_stopped: if true, activate netdev's read poll when VM
+#     stops to allow filter-redirector to continue receiving data
+#     (default: false)
+#
 # Since: 2.6
 ##
 { 'struct': 'FilterRedirectorProperties',
   'base': 'NetfilterProperties',
   'data': { '*indev': 'str',
             '*outdev': 'str',
-            '*vnet_hdr_support': 'bool' } }
+            '*vnet_hdr_support': 'bool',
+            '*enable_when_stopped': 'bool' } }
 
 ##
 # @FilterRewriterProperties:
tests/qtest/test-filter-redirector.c +106 -1
index 5540c232c0..fa958bb0a5 100644
@@ -385,6 +385,110 @@ static void test_redirector_init_status_off(void)
     qtest_quit(qts);
 }
 
+/*
+ * Test filter-redirector works when VM is stopped (TX direction).
+ *
+ * This test verifies that when VM is stopped, the filter-redirector
+ * can still receive data from the netdev because the VM state change
+ * handler activates the netdev's read_poll(). Data flows from netdev
+ * to filter-redirector and out through the chardev.
+ *
+ * Data flow: backend_sock -> netdev (read_poll) -> filter-redirector -> chardev
+ */
+static void test_redirector_with_vm_stop(void)
+{
+    int backend_sock[2], recv_sock;
+    uint32_t ret = 0, len = 0;
+    char send_buf[] = "Hello!!";
+    char sock_path0[] = "filter-redirector0.XXXXXX";
+    char *recv_buf;
+    uint32_t size = sizeof(send_buf);
+    size = htonl(size);
+    QTestState *qts;
+    struct timeval tv;
+    fd_set rfds;
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, backend_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = mkstemp(sock_path0);
+    g_assert_cmpint(ret, !=, -1);
+
+    /*
+     * Setup TX path: netdev -> filter-redirector -> chardev
+     * Data sent to backend_sock[0] will be read by the netdev,
+     * passed through filter-redirector, and output to sock_path0.
+     * Enable enable_when_stopped to activate read_poll when VM stops.
+     */
+    qts = qtest_initf(
+        "-nic socket,id=qtest-bn0,fd=%d "
+        "-chardev socket,id=redirector0,path=%s,server=on,wait=off "
+        "-object filter-redirector,id=qtest-f0,netdev=qtest-bn0,"
+        "queue=tx,outdev=redirector0,enable_when_stopped=true ",
+        backend_sock[1], sock_path0);
+
+    recv_sock = unix_connect(sock_path0, NULL);
+    g_assert_cmpint(recv_sock, !=, -1);
+
+    /* Ensure connection is established */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    struct iovec iov[] = {
+        {
+            .iov_base = &size,
+            .iov_len = sizeof(size),
+        }, {
+            .iov_base = send_buf,
+            .iov_len = sizeof(send_buf),
+        },
+    };
+
+    /*
+     * Stop the VM - this triggers our vm_state_change handler
+     * which should activate the netdev's read_poll()
+     */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'stop'}");
+
+    /* Wait for VM to actually stop */
+    qtest_qmp_eventwait(qts, "STOP");
+
+    /*
+     * Send data to backend socket while VM is stopped.
+     * The netdev should still read the data (because read_poll is
+     * activated by our vm_state_change handler), pass it through
+     * filter-redirector, and output to the chardev.
+     */
+    ret = iov_send(backend_sock[0], iov, 2, 0, sizeof(size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(size));
+
+    /*
+     * Data should arrive at recv_sock even with VM stopped,
+     * because read_poll is activated.
+     */
+    FD_ZERO(&rfds);
+    FD_SET(recv_sock, &rfds);
+    tv.tv_sec = 5;
+    tv.tv_usec = 0;
+    ret = select(recv_sock + 1, &rfds, NULL, NULL, &tv);
+    g_assert_cmpint(ret, ==, 1);  /* Data should arrive */
+
+    ret = recv(recv_sock, &len, sizeof(len), 0);
+    g_assert_cmpint(ret, ==, sizeof(len));
+    len = ntohl(len);
+
+    g_assert_cmpint(len, ==, sizeof(send_buf));
+    recv_buf = g_malloc(len);
+    ret = recv(recv_sock, recv_buf, len, 0);
+    g_assert_cmpint(ret, ==, len);
+    g_assert_cmpstr(recv_buf, ==, send_buf);
+
+    g_free(recv_buf);
+    close(recv_sock);
+    close(backend_sock[0]);
+    unlink(sock_path0);
+    qtest_quit(qts);
+}
+
 static void test_redirector_rx_event_opened(void)
 {
     int backend_sock[2], send_sock;
@@ -489,5 +593,7 @@ int main(int argc, char **argv)
                    test_redirector_init_status_off);
     qtest_add_func("/netfilter/redirector_rx_event_opened",
                    test_redirector_rx_event_opened);
+    qtest_add_func("/netfilter/redirector_with_vm_stop",
+                   test_redirector_with_vm_stop);
     return g_test_run();
 }
--

2.52.0

#4 lore raw

Re: [PATCH 02/12] net/filter-mirror: add enable_when_stopped option for filter-redirector

Quoted 30 lines · Cindy Lu
Quoted 28 lines · Zhang Chen
Quoted 10 lines · Cindy Lu

From: Jason Wang <[email protected]>

Add a QAPI option 'enable_when_stopped' for filter-redirector that allows it to continue receiving data from netdev when VM is stopped.

When enabled, a VM state change handler activates the netdev's read_poll() when VM stops, allowing the netdev to continue reading data and passing it through filter-redirector to the chardev output.

Quoted 7 lines

This is useful for scenarios where filter-redirector needs to process network traffic even when the VM is paused.

Usage:
-object filter-redirector,id=f0,netdev=net0,queue=tx,\
outdev=chardev0,enable_when_stopped=true

It seems this series is trying to address previous VM migration network related issues that Juraj Marcin mentioned.
Add CC to him.

I've taken a quick look, and this series lacks support for filter-reply and filter-rewriter.
Could there be a reason for this?

Quoted 6 lines
Quoted 3 lines

Thanks
Chen

Hi Chen
For this RFC, filter-reply and filter-rewriter is not need, I will add support for them later.

Right, I think the reason is that we don't see a use case for them.

Thanks

Quoted 258 lines

Thanks
cindy

Quoted 255 lines

.

Quoted 249 lines
---
 net/filter-mirror.c                  |  38 ++++++++++
 qapi/qom.json                        |   7 +-
 tests/qtest/test-filter-redirector.c | 106 +++++++++++++++++++++++++++
 3 files changed, 150 insertions(+), 1 deletion(-)
net/filter-mirror.c +38 -0
index aa2ab452fd..e1a0650abd 100644
@@ -21,6 +21,7 @@
 #include "qemu/iov.h"
 #include "qemu/sockets.h"
 #include "block/aio-wait.h"
+#include "system/runstate.h"
 
 #define TYPE_FILTER_MIRROR "filter-mirror"
 typedef struct MirrorState MirrorState;
@@ -41,6 +42,8 @@ struct MirrorState {
     CharFrontend chr_out;
     SocketReadState rs;
     bool vnet_hdr;
+    bool enable_when_stopped;
+    VMChangeStateEntry *vmsentry;
 };
 
 typedef struct FilterSendCo {
@@ -251,6 +254,7 @@ static void filter_redirector_cleanup(NetFilterState *nf)
 
     qemu_chr_fe_deinit(&s->chr_in, false);
     qemu_chr_fe_deinit(&s->chr_out, false);
+    qemu_del_vm_change_state_handler(s->vmsentry);
 }
 
 static void filter_mirror_setup(NetFilterState *nf, Error **errp)
@@ -282,6 +286,18 @@ static void redirector_rs_finalize(SocketReadState *rs)
     redirector_to_filter(nf, rs->buf, rs->packet_len);
 }
 
+static void filter_redirector_vm_state_change(void *opaque, bool running,
+                                              RunState state)
+{
+    NetFilterState *nf = opaque;
+    MirrorState *s = FILTER_REDIRECTOR(nf);
+    NetClientState *nc = nf->netdev;
+
+    if (!running && s->enable_when_stopped && nc->info->read_poll) {
+        nc->info->read_poll(nc, true);
+    }
+}
+
 static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(nf);
@@ -331,6 +347,9 @@ static void filter_redirector_setup(NetFilterState *nf, Error **errp)
             return;
         }
     }
+
+    s->vmsentry = qemu_add_vm_change_state_handler(
+        filter_redirector_vm_state_change, nf);
 }
 
 static void filter_redirector_status_changed(NetFilterState *nf, Error **errp)
@@ -437,6 +456,22 @@ static void filter_redirector_set_vnet_hdr(Object *obj,
     s->vnet_hdr = value;
 }
 
+static bool filter_redirector_get_enable_when_stopped(Object *obj, Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    return s->enable_when_stopped;
+}
+
+static void filter_redirector_set_enable_when_stopped(Object *obj,
+                                                      bool value,
+                                                      Error **errp)
+{
+    MirrorState *s = FILTER_REDIRECTOR(obj);
+
+    s->enable_when_stopped = value;
+}
+
 static void filter_mirror_class_init(ObjectClass *oc, const void *data)
 {
     NetFilterClass *nfc = NETFILTER_CLASS(oc);
@@ -463,6 +498,9 @@ static void filter_redirector_class_init(ObjectClass *oc, const void *data)
     object_class_property_add_bool(oc, "vnet_hdr_support",
                                    filter_redirector_get_vnet_hdr,
                                    filter_redirector_set_vnet_hdr);
+    object_class_property_add_bool(oc, "enable_when_stopped",
+                                   filter_redirector_get_enable_when_stopped,
+                                   filter_redirector_set_enable_when_stopped);
 
     nfc->setup = filter_redirector_setup;
     nfc->cleanup = filter_redirector_cleanup;
qapi/qom.json +6 -1
index 6f5c9de0f0..b1fe55944c 100644
@@ -488,13 +488,18 @@
 # @vnet_hdr_support: if true, vnet header support is enabled
 #     (default: false)
 #
+# @enable_when_stopped: if true, activate netdev's read poll when VM
+#     stops to allow filter-redirector to continue receiving data
+#     (default: false)
+#
 # Since: 2.6
 ##
 { 'struct': 'FilterRedirectorProperties',
   'base': 'NetfilterProperties',
   'data': { '*indev': 'str',
             '*outdev': 'str',
-            '*vnet_hdr_support': 'bool' } }
+            '*vnet_hdr_support': 'bool',
+            '*enable_when_stopped': 'bool' } }
 
 ##
 # @FilterRewriterProperties:
tests/qtest/test-filter-redirector.c +106 -1
index 5540c232c0..fa958bb0a5 100644
@@ -385,6 +385,110 @@ static void test_redirector_init_status_off(void)
     qtest_quit(qts);
 }
 
+/*
+ * Test filter-redirector works when VM is stopped (TX direction).
+ *
+ * This test verifies that when VM is stopped, the filter-redirector
+ * can still receive data from the netdev because the VM state change
+ * handler activates the netdev's read_poll(). Data flows from netdev
+ * to filter-redirector and out through the chardev.
+ *
+ * Data flow: backend_sock -> netdev (read_poll) -> filter-redirector -> chardev
+ */
+static void test_redirector_with_vm_stop(void)
+{
+    int backend_sock[2], recv_sock;
+    uint32_t ret = 0, len = 0;
+    char send_buf[] = "Hello!!";
+    char sock_path0[] = "filter-redirector0.XXXXXX";
+    char *recv_buf;
+    uint32_t size = sizeof(send_buf);
+    size = htonl(size);
+    QTestState *qts;
+    struct timeval tv;
+    fd_set rfds;
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, backend_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = mkstemp(sock_path0);
+    g_assert_cmpint(ret, !=, -1);
+
+    /*
+     * Setup TX path: netdev -> filter-redirector -> chardev
+     * Data sent to backend_sock[0] will be read by the netdev,
+     * passed through filter-redirector, and output to sock_path0.
+     * Enable enable_when_stopped to activate read_poll when VM stops.
+     */
+    qts = qtest_initf(
+        "-nic socket,id=qtest-bn0,fd=%d "
+        "-chardev socket,id=redirector0,path=%s,server=on,wait=off "
+        "-object filter-redirector,id=qtest-f0,netdev=qtest-bn0,"
+        "queue=tx,outdev=redirector0,enable_when_stopped=true ",
+        backend_sock[1], sock_path0);
+
+    recv_sock = unix_connect(sock_path0, NULL);
+    g_assert_cmpint(recv_sock, !=, -1);
+
+    /* Ensure connection is established */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    struct iovec iov[] = {
+        {
+            .iov_base = &size,
+            .iov_len = sizeof(size),
+        }, {
+            .iov_base = send_buf,
+            .iov_len = sizeof(send_buf),
+        },
+    };
+
+    /*
+     * Stop the VM - this triggers our vm_state_change handler
+     * which should activate the netdev's read_poll()
+     */
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'stop'}");
+
+    /* Wait for VM to actually stop */
+    qtest_qmp_eventwait(qts, "STOP");
+
+    /*
+     * Send data to backend socket while VM is stopped.
+     * The netdev should still read the data (because read_poll is
+     * activated by our vm_state_change handler), pass it through
+     * filter-redirector, and output to the chardev.
+     */
+    ret = iov_send(backend_sock[0], iov, 2, 0, sizeof(size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(size));
+
+    /*
+     * Data should arrive at recv_sock even with VM stopped,
+     * because read_poll is activated.
+     */
+    FD_ZERO(&rfds);
+    FD_SET(recv_sock, &rfds);
+    tv.tv_sec = 5;
+    tv.tv_usec = 0;
+    ret = select(recv_sock + 1, &rfds, NULL, NULL, &tv);
+    g_assert_cmpint(ret, ==, 1);  /* Data should arrive */
+
+    ret = recv(recv_sock, &len, sizeof(len), 0);
+    g_assert_cmpint(ret, ==, sizeof(len));
+    len = ntohl(len);
+
+    g_assert_cmpint(len, ==, sizeof(send_buf));
+    recv_buf = g_malloc(len);
+    ret = recv(recv_sock, recv_buf, len, 0);
+    g_assert_cmpint(ret, ==, len);
+    g_assert_cmpstr(recv_buf, ==, send_buf);
+
+    g_free(recv_buf);
+    close(recv_sock);
+    close(backend_sock[0]);
+    unlink(sock_path0);
+    qtest_quit(qts);
+}
+
 static void test_redirector_rx_event_opened(void)
 {
     int backend_sock[2], send_sock;
@@ -489,5 +593,7 @@ int main(int argc, char **argv)
                    test_redirector_init_status_off);
     qtest_add_func("/netfilter/redirector_rx_event_opened",
                    test_redirector_rx_event_opened);
+    qtest_add_func("/netfilter/redirector_with_vm_stop",
+                   test_redirector_with_vm_stop);
     return g_test_run();
 }
--

2.52.0

author
#5 lore raw

PATCH 3/12 net/filter: add statistics counters for netfilters

In reply to Cindy Lu

From: Jason Wang <[email protected]>

Add packet and byte counters to NetFilterState to track traffic passing through netfilters. The counters are updated in qemu_netfilter_receive() for both TX and RX directions.

New QMP command 'query-netfilter-stats' and HMP command 'info netfilter-stats' are added to query the statistics.

The NetFilterStats structure includes:
- name: filter name
- netdev: attached netdev id
- type: filter type (e.g., filter-mirror)
- packets-tx/rx: packet counters
- bytes-tx/rx: byte counters

Example QMP usage:
{"execute": "query-netfilter-stats"}

Example HMP usage:
(qemu) info netfilter-stats

---
 hmp-commands-info.hx  | 13 +++++++++
 include/monitor/hmp.h |  1 +
 include/net/filter.h  |  6 +++++
 net/filter.c          | 16 ++++++++++-
 net/net-hmp-cmds.c    | 28 +++++++++++++++++++
 net/net.c             | 42 +++++++++++++++++++++++++++++
 qapi/net.json         | 63 +++++++++++++++++++++++++++++++++++++++++++
 7 files changed, 168 insertions(+), 1 deletion(-)
hmp-commands-info.hx +13 -0
index 41674dcbe1..d67df3f98a 100644
@@ -44,6 +44,19 @@ SRST
     Show the network state.
 ERST
 
+    {
+        .name       = "netfilter-stats",
+        .args_type  = "",
+        .params     = "",
+        .help       = "show netfilter statistics",
+        .cmd        = hmp_info_netfilter_stats,
+    },
+
+SRST
+  ``info netfilter-stats``
+    Show netfilter statistics (packets and bytes counters).
+ERST
+
     {
         .name       = "chardev",
         .args_type  = "",
include/monitor/hmp.h +1 -0
index 83721b5ffc..7150ca8514 100644
@@ -56,6 +56,7 @@ void hmp_cont(Monitor *mon, const QDict *qdict);
 void hmp_system_wakeup(Monitor *mon, const QDict *qdict);
 void hmp_nmi(Monitor *mon, const QDict *qdict);
 void hmp_info_network(Monitor *mon, const QDict *qdict);
+void hmp_info_netfilter_stats(Monitor *mon, const QDict *qdict);
 void hmp_set_link(Monitor *mon, const QDict *qdict);
 void hmp_balloon(Monitor *mon, const QDict *qdict);
 void hmp_loadvm(Monitor *mon, const QDict *qdict);
include/net/filter.h +6 -0
index f15f7932b2..04786e4e87 100644
@@ -60,6 +60,12 @@ struct NetFilterState {
     char *position;
     bool insert_before_flag;
     QTAILQ_ENTRY(NetFilterState) next;
+
+    /* statistics */
+    uint64_t bytes_tx;
+    uint64_t bytes_rx;
+    uint64_t packets_tx;
+    uint64_t packets_rx;
 };
 
 ssize_t qemu_netfilter_receive(NetFilterState *nf,
net/filter.c +15 -1
index c7cc6615dc..76345c1a9d 100644
@@ -33,13 +33,27 @@ ssize_t qemu_netfilter_receive(NetFilterState *nf,
                                int iovcnt,
                                NetPacketSent *sent_cb)
 {
+    ssize_t ret;
+    size_t size;
+
     if (qemu_can_skip_netfilter(nf)) {
         return 0;
     }
     if (nf->direction == direction ||
         nf->direction == NET_FILTER_DIRECTION_ALL) {
-        return NETFILTER_GET_CLASS(OBJECT(nf))->receive_iov(
+        /* Update statistics */
+        size = iov_size(iov, iovcnt);
+        if (direction == NET_FILTER_DIRECTION_TX) {
+            nf->packets_tx++;
+            nf->bytes_tx += size;
+        } else {
+            nf->packets_rx++;
+            nf->bytes_rx += size;
+        }
+
+        ret = NETFILTER_GET_CLASS(OBJECT(nf))->receive_iov(
                                    nf, sender, flags, iov, iovcnt, sent_cb);
+        return ret;
     }
 
     return 0;
net/net-hmp-cmds.c +28 -0
index e7c55d2787..9bdd6d233f 100644
@@ -168,3 +168,31 @@ void netdev_del_completion(ReadLineState *rs, int nb_args, const char *str)
         }
     }
 }
+
+void hmp_info_netfilter_stats(Monitor *mon, const QDict *qdict)
+{
+    NetFilterStatsList *stats_list, *entry;
+    Error *err = NULL;
+
+    stats_list = qmp_query_netfilter_stats(NULL, &err);
+    if (hmp_handle_error(mon, err)) {
+        return;
+    }
+
+    if (!stats_list) {
+        monitor_printf(mon, "No netfilters found\n");
+        return;
+    }
+
+    for (entry = stats_list; entry; entry = entry->next) {
+        NetFilterStats *stats = entry->value;
+        monitor_printf(mon, "%s: netdev=%s type=%s\n",
+                       stats->name, stats->netdev, stats->type);
+        monitor_printf(mon, "  tx: %" PRIu64 " packets, %" PRIu64 " bytes\n",
+                       stats->packets_tx, stats->bytes_tx);
+        monitor_printf(mon, "  rx: %" PRIu64 " packets, %" PRIu64 " bytes\n",
+                       stats->packets_rx, stats->bytes_rx);
+    }
+
+    qapi_free_NetFilterStatsList(stats_list);
+}
net/net.c +42 -0

48 lines not on this page · raw message

qapi/net.json +63 -0

66 lines not on this page · raw message

Signature · 1 line
2.52.0
author
#6 lore raw

PATCH 4/12 net/filter-mirror: add indev/outdev statistics for filter-redirector

In reply to Cindy Lu

From: Jason Wang <[email protected]>

Add packet and byte counters for filter-redirector's indev and outdev character devices:

- indev_packets/indev_bytes: count packets/bytes received from indev
- outdev_packets/outdev_bytes: count packets/bytes sent to outdev

The indev counters are updated in redirector_rs_finalize() when a complete packet is read from indev. The outdev counters are updated in filter_redirector_receive_iov() when data is successfully sent to outdev.

Design changes:
- Add FilterGetStats callback to NetFilterClass, allowing each filter type to implement its own statistics collection
- Introduce a flexible 'counters' array in NetFilterStats (QAPI) to allow different filter types to expose their own specific counters
- net.c uses the callback instead of directly calling filter-specific functions, improving modularity

The QMP query-netfilter-stats command and HMP info netfilter-stats command now include the optional counters array for filters that implement the get_stats callback.

Example output:
(qemu) info netfilter-stats
rd0: netdev=bn0 type=filter-redirector
tx: 5 packets, 500 bytes
rx: 0 packets, 0 bytes
indev: 3 packets, 300 bytes
outdev: 5 packets, 500 bytes

---
 include/net/filter.h |  8 ++++++++
 net/filter-mirror.c  | 42 ++++++++++++++++++++++++++++++++++++++++--
 net/net-hmp-cmds.c   | 10 ++++++++++
 net/net.c            | 28 ++++++++++++++++++++++++++++
 qapi/net.json        | 25 ++++++++++++++++++++++++-
 5 files changed, 110 insertions(+), 3 deletions(-)
include/net/filter.h +8 -0
index 04786e4e87..f0673c9163 100644
@@ -35,6 +35,13 @@ typedef void (FilterStatusChanged) (NetFilterState *nf, Error **errp);
 
 typedef void (FilterHandleEvent) (NetFilterState *nf, int event, Error **errp);
 
+/*
+ * Get filter-specific statistics counters.
+ * Returns a GList of NetFilterCounter (QAPI type), or NULL if no counters.
+ * The caller is responsible for freeing the returned list and its contents.
+ */
+typedef GList *(FilterGetStats) (NetFilterState *nf);
+
 struct NetFilterClass {
     ObjectClass parent_class;
 
@@ -43,6 +50,7 @@ struct NetFilterClass {
     FilterCleanup *cleanup;
     FilterStatusChanged *status_changed;
     FilterHandleEvent *handle_event;
+    FilterGetStats *get_stats;
     /* mandatory */
     FilterReceiveIOV *receive_iov;
 };
net/filter-mirror.c +40 -2

90 lines not on this page · raw message

net/net-hmp-cmds.c +10 -0
index 9bdd6d233f..df9336be1e 100644
@@ -192,6 +192,16 @@ void hmp_info_netfilter_stats(Monitor *mon, const QDict *qdict)
                        stats->packets_tx, stats->bytes_tx);
         monitor_printf(mon, "  rx: %" PRIu64 " packets, %" PRIu64 " bytes\n",
                        stats->packets_rx, stats->bytes_rx);
+        if (stats->counters) {
+            NetFilterCounterList *counter_entry;
+            for (counter_entry = stats->counters; counter_entry;
+                 counter_entry = counter_entry->next) {
+                NetFilterCounter *counter = counter_entry->value;
+                monitor_printf(mon,
+                               "  %s: %" PRIu64 " packets, %" PRIu64 " bytes\n",
+                               counter->name, counter->packets, counter->bytes);
+            }
+        }
     }
 
     qapi_free_NetFilterStatsList(stats_list);
net/net.c +28 -0
index 40966fbf8a..b15f4db65e 100644
@@ -1631,6 +1631,34 @@ NetFilterStatsList *qmp_query_netfilter_stats(const char *name, Error **errp)
             stats->bytes_tx = nf->bytes_tx;
             stats->bytes_rx = nf->bytes_rx;
 
+            /* Get filter-specific counters via callback */
+            {
+                NetFilterClass *nfc = NETFILTER_GET_CLASS(nf);
+                if (nfc->get_stats) {
+                    GList *filter_counters = nfc->get_stats(nf);
+                    GList *iter;
+
+                    for (iter = filter_counters; iter; iter = iter->next) {
+                        NetFilterCounter *fc = iter->data;
+                        NetFilterCounter *counter;
+
+                        counter = g_new0(NetFilterCounter, 1);
+                        counter->name = g_strdup(fc->name);
+                        counter->packets = fc->packets;
+                        counter->bytes = fc->bytes;
+                        QAPI_LIST_PREPEND(stats->counters, counter);
+
+                        g_free(fc->name);
+                        g_free(fc);
+                    }
+                    g_list_free(filter_counters);
+
+                    if (stats->counters) {
+                        stats->has_counters = true;
+                    }
+                }
+            }
+
             QAPI_LIST_APPEND(tail, stats);
 
             if (name) {
qapi/net.json +24 -1
index 277cdd9e32..c57497d328 100644
@@ -1192,6 +1192,25 @@
 { 'event': 'NETDEV_VHOST_USER_DISCONNECTED',
   'data': { 'netdev-id': 'str' } }
 
+##
+# @NetFilterCounter:
+#
+# A filter-specific counter with packet and byte counts.
+#
+# @name: the name of the counter (e.g., "indev", "outdev")
+#
+# @packets: number of packets
+#
+# @bytes: number of bytes
+#
+# Since: 10.1
+##
+{ 'struct': 'NetFilterCounter',
+  'data': {
+    'name':    'str',
+    'packets': 'uint64',
+    'bytes':   'uint64' } }
+
 ##
 # @NetFilterStats:
 #
@@ -1211,6 +1230,9 @@
 #
 # @bytes-rx: number of received bytes
 #
+# @counters: filter-specific counters (optional, depends on
+#     filter type)
+#
 # Since: 10.1
 ##
 { 'struct': 'NetFilterStats',
@@ -1221,7 +1243,8 @@
     'packets-tx': 'uint64',
     'packets-rx': 'uint64',
     'bytes-tx':   'uint64',
-    'bytes-rx':   'uint64' } }
+    'bytes-rx':   'uint64',
+    '*counters':  ['NetFilterCounter'] } }
 
 ##
 # @query-netfilter-stats:
Signature · 1 line
2.52.0
author
#7 lore raw

PATCH 5/12 tests/qtest: add tests for filter-redirector indev/outdev statistics

In reply to Cindy Lu

From: Jason Wang <[email protected]>

Add test cases to verify the indev/outdev counters for filter-redirector:

test_query_netfilter_stats_rx():
- Extended to verify indev counter in the counters array
- Uses filter-redirector with indev to inject packets
- Verifies indev packets/bytes are updated

test_query_netfilter_stats_redirector_outdev():
- New test for outdev statistics
- Uses filter-redirector with outdev configured
- Verifies initial outdev counters are zero
- Sends packet and verifies outdev packets/bytes are updated

These tests verify the new flexible counters array design where filter-specific statistics are returned via the get_stats callback.

---
 tests/qtest/test-netfilter.c | 371 +++++++++++++++++++++++++++++++++++
 1 file changed, 371 insertions(+)
tests/qtest/test-netfilter.c +371 -0
index 326d4bd85f..20b0373cf7 100644
@@ -9,6 +9,7 @@
  */
 
 #include "qemu/osdep.h"
+#include "qemu/iov.h"
 #include "libqtest-single.h"
 #include "qobject/qdict.h"
 
@@ -124,6 +125,371 @@ static void add_multi_netfilter(void)
     qobject_unref(response);
 }
 
+/*
+ * Test query-netfilter-stats for TX direction using filter-mirror.
+ *
+ * Traffic flow:
+ *   test_sock -> socket backend (bn0) -> filter-mirror (TX stats++) -> chardev
+ */
+static void test_query_netfilter_stats_tx(void)
+{
+    QTestState *qts;
+    QDict *response;
+    QList *stats_list;
+    const QListEntry *entry;
+    int send_sock[2], recv_sock[2];
+    int ret;
+    char send_buf[] = "Hello TX stats!";
+    uint32_t size = sizeof(send_buf);
+    uint32_t net_size;
+    bool found_filter = false;
+
+    net_size = htonl(size);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, send_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, recv_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    qts = qtest_initf(
+        "-nic socket,id=bn0,fd=%d "
+        "-chardev socket,id=mirror0,fd=%d "
+        "-object filter-mirror,id=f0,netdev=bn0,queue=tx,outdev=mirror0",
+        send_sock[1], recv_sock[1]);
+
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    /* Query initial stats */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    g_assert(!qdict_haskey(response, "error"));
+    stats_list = qdict_get_qlist(response, "return");
+    g_assert(stats_list);
+
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "f0") == 0) {
+            found_filter = true;
+            g_assert_cmpint(qdict_get_int(stats, "packets-tx"), ==, 0);
+            g_assert_cmpint(qdict_get_int(stats, "bytes-tx"), ==, 0);
+            g_assert_cmpstr(qdict_get_str(stats, "type"), ==, "filter-mirror");
+        }
+    }
+    g_assert(found_filter);
+    qobject_unref(response);
+
+    /* Send packet - triggers TX direction */
+    struct iovec iov[] = {
+        { .iov_base = &net_size, .iov_len = sizeof(net_size) },
+        { .iov_base = send_buf, .iov_len = sizeof(send_buf) },
+    };
+    ret = iov_send(send_sock[0], iov, 2, 0,
+                   sizeof(net_size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(net_size));
+
+    g_usleep(100000);
+
+    /* Verify TX stats updated */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    stats_list = qdict_get_qlist(response, "return");
+
+    found_filter = false;
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "f0") == 0) {
+            found_filter = true;
+            g_assert_cmpint(qdict_get_int(stats, "packets-tx"), >=, 1);
+            g_assert_cmpint(qdict_get_int(stats, "bytes-tx"), >=,
+                            sizeof(send_buf));
+        }
+    }
+    g_assert(found_filter);
+    qobject_unref(response);
+
+    close(send_sock[0]);
+    close(send_sock[1]);
+    close(recv_sock[0]);
+    close(recv_sock[1]);
+    qtest_quit(qts);
+}
+
+/*
+ * Test query-netfilter-stats for RX direction using filter-redirector.
+ *
+ * Traffic flow:
+ *   indev_sock -> chardev (indev) -> filter-redirector -> netdev (RX path)
+ *
+ * When filter-redirector reads from indev and calls redirector_to_filter(),
+ * it passes the packet to the next filter in the chain via
+ * qemu_netfilter_pass_to_next(). We add a second filter (filter-buffer)
+ * that will receive the packet and update its RX stats.
+ */
+static void test_query_netfilter_stats_rx(void)
+{
+    QTestState *qts;
+    QDict *response;
+    QList *stats_list;
+    const QListEntry *entry;
+    int backend_sock[2], indev_sock[2];
+    int ret;
+    char send_buf[] = "Hello RX stats!";
+    uint32_t size = sizeof(send_buf);
+    uint32_t net_size;
+    bool found_buffer = false;
+
+    net_size = htonl(size);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, backend_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, indev_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    /*
+     * Setup:
+     * - filter-redirector (rd0, queue=rx, indev) at tail - injects data
+     * - filter-buffer (fb0, queue=rx) at head - receives and counts
+     *
+     * RX direction traverses from tail to head, so:
+     * indev -> rd0 (reads, calls pass_to_next) -> fb0 (receive_iov, RX stats++)
+     */
+    qts = qtest_initf(
+        "-nic socket,id=bn0,fd=%d "
+        "-chardev socket,id=indev0,fd=%d "
+        "-object filter-buffer,id=fb0,netdev=bn0,queue=rx,interval=1000000,position=head "
+        "-object filter-redirector,id=rd0,netdev=bn0,queue=rx,indev=indev0,position=tail",
+        backend_sock[1], indev_sock[1]);
+
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    /* Query initial stats - fb0 should have zero RX */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    g_assert(!qdict_haskey(response, "error"));
+    stats_list = qdict_get_qlist(response, "return");
+    g_assert(stats_list);
+
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "fb0") == 0) {
+            found_buffer = true;
+            g_assert_cmpint(qdict_get_int(stats, "packets-rx"), ==, 0);
+            g_assert_cmpint(qdict_get_int(stats, "bytes-rx"), ==, 0);
+            g_assert_cmpstr(qdict_get_str(stats, "type"), ==, "filter-buffer");
+        }
+    }
+    g_assert(found_buffer);
+    qobject_unref(response);
+
+    /* Inject packet via indev - triggers RX direction */
+    struct iovec iov[] = {
+        { .iov_base = &net_size, .iov_len = sizeof(net_size) },
+        { .iov_base = send_buf, .iov_len = sizeof(send_buf) },
+    };
+    ret = iov_send(indev_sock[0], iov, 2, 0,
+                   sizeof(net_size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(net_size));
+
+    g_usleep(100000);
+
+    /* Verify fb0's RX stats and rd0's indev stats updated */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    stats_list = qdict_get_qlist(response, "return");
+
+    found_buffer = false;
+    bool found_redirector = false;
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "fb0") == 0) {
+            found_buffer = true;
+            g_assert_cmpint(qdict_get_int(stats, "packets-rx"), >=, 1);
+            g_assert_cmpint(qdict_get_int(stats, "bytes-rx"), >=,
+                            sizeof(send_buf));
+        }
+        if (g_strcmp0(name, "rd0") == 0) {
+            QList *counters;
+            const QListEntry *centry;
+            bool found_indev = false;
+
+            found_redirector = true;
+            /* Verify indev counter in counters array */
+            g_assert(qdict_haskey(stats, "counters"));
+            counters = qdict_get_qlist(stats, "counters");
+            for (centry = qlist_first(counters); centry;
+                 centry = qlist_next(centry)) {
+                QDict *counter = qobject_to(QDict, qlist_entry_obj(centry));
+                const char *cname = qdict_get_str(counter, "name");
+                if (g_strcmp0(cname, "indev") == 0) {
+                    found_indev = true;
+                    g_assert_cmpint(qdict_get_int(counter, "packets"), >=, 1);
+                    g_assert_cmpint(qdict_get_int(counter, "bytes"),
+                                    >=, sizeof(send_buf));
+                }
+            }
+            g_assert(found_indev);
+        }
+    }
+    g_assert(found_buffer);
+    g_assert(found_redirector);
+    qobject_unref(response);
+
+    /* Test query by name */
+    response = qtest_qmp(qts,
+                         "{'execute': 'query-netfilter-stats',"
+                         " 'arguments': { 'name': 'fb0' }}");
+    g_assert(response);
+    g_assert(!qdict_haskey(response, "error"));
+    stats_list = qdict_get_qlist(response, "return");
+    g_assert_cmpint(qlist_size(stats_list), ==, 1);
+    qobject_unref(response);
+
+    /* Test error for non-existent filter */
+    response = qtest_qmp(qts,
+                         "{'execute': 'query-netfilter-stats',"
+                         " 'arguments': { 'name': 'nonexistent' }}");
+    g_assert(response);
+    g_assert(qdict_haskey(response, "error"));
+    qobject_unref(response);
+
+    close(backend_sock[0]);
+    close(backend_sock[1]);
+    close(indev_sock[0]);
+    close(indev_sock[1]);
+    qtest_quit(qts);
+}
+
+/*
+ * Test filter-redirector outdev statistics.
+ *
+ * Traffic flow:
+ *   test_sock -> socket backend -> filter-redirector (outdev) -> chardev
+ *
+ * When data passes through filter-redirector with outdev configured,
+ * it sends the data to outdev and updates outdev statistics.
+ */
+static void test_query_netfilter_stats_redirector_outdev(void)
+{
+    QTestState *qts;
+    QDict *response;
+    QList *stats_list;
+    const QListEntry *entry;
+    int send_sock[2], recv_sock[2];
+    int ret;
+    char send_buf[] = "Hello outdev stats!";
+    uint32_t size = sizeof(send_buf);
+    uint32_t net_size;
+    bool found_redirector = false;
+
+    net_size = htonl(size);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, send_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, recv_sock);
+    g_assert_cmpint(ret, !=, -1);
+
+    qts = qtest_initf(
+        "-nic socket,id=bn0,fd=%d "
+        "-chardev socket,id=outdev0,fd=%d "
+        "-object filter-redirector,id=rd0,netdev=bn0,queue=tx,outdev=outdev0",
+        send_sock[1], recv_sock[1]);
+
+    qtest_qmp_assert_success(qts, "{ 'execute' : 'query-status'}");
+
+    /* Query initial stats */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    stats_list = qdict_get_qlist(response, "return");
+
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "rd0") == 0) {
+            QList *counters;
+            const QListEntry *centry;
+            bool found_outdev = false;
+
+            found_redirector = true;
+            g_assert(qdict_haskey(stats, "counters"));
+            counters = qdict_get_qlist(stats, "counters");
+            for (centry = qlist_first(counters); centry;
+                 centry = qlist_next(centry)) {
+                QDict *counter = qobject_to(QDict, qlist_entry_obj(centry));
+                const char *cname = qdict_get_str(counter, "name");
+                if (g_strcmp0(cname, "outdev") == 0) {
+                    found_outdev = true;
+                    g_assert_cmpint(qdict_get_int(counter, "packets"), ==, 0);
+                    g_assert_cmpint(qdict_get_int(counter, "bytes"), ==, 0);
+                }
+            }
+            g_assert(found_outdev);
+        }
+    }
+    g_assert(found_redirector);
+    qobject_unref(response);
+
+    /* Send packet - triggers TX direction and outdev */
+    struct iovec iov[] = {
+        { .iov_base = &net_size, .iov_len = sizeof(net_size) },
+        { .iov_base = send_buf, .iov_len = sizeof(send_buf) },
+    };
+    ret = iov_send(send_sock[0], iov, 2, 0,
+                   sizeof(net_size) + sizeof(send_buf));
+    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(net_size));
+
+    g_usleep(100000);
+
+    /* Verify outdev stats updated */
+    response = qtest_qmp(qts, "{'execute': 'query-netfilter-stats'}");
+    g_assert(response);
+    stats_list = qdict_get_qlist(response, "return");
+
+    found_redirector = false;
+    for (entry = qlist_first(stats_list); entry; entry = qlist_next(entry)) {
+        QDict *stats = qobject_to(QDict, qlist_entry_obj(entry));
+        const char *name = qdict_get_str(stats, "name");
+        if (g_strcmp0(name, "rd0") == 0) {
+            QList *counters;
+            const QListEntry *centry;
+            bool found_outdev = false;
+
+            found_redirector = true;
+            /* TX stats should also be updated */
+            g_assert_cmpint(qdict_get_int(stats, "packets-tx"), >=, 1);
+
+            /* Verify outdev counter */
+            counters = qdict_get_qlist(stats, "counters");
+            for (centry = qlist_first(counters); centry;
+                 centry = qlist_next(centry)) {
+                QDict *counter = qobject_to(QDict, qlist_entry_obj(centry));
+                const char *cname = qdict_get_str(counter, "name");
+                if (g_strcmp0(cname, "outdev") == 0) {
+                    found_outdev = true;
+                    g_assert_cmpint(qdict_get_int(counter, "packets"), >=, 1);
+                    g_assert_cmpint(qdict_get_int(counter, "bytes"),
+                                    >=, sizeof(send_buf));
+                }
+            }
+            g_assert(found_outdev);
+        }
+    }
+    g_assert(found_redirector);
+    qobject_unref(response);
+
+    close(send_sock[0]);
+    close(send_sock[1]);
+    close(recv_sock[0]);
+    close(recv_sock[1]);
+    qtest_quit(qts);
+}
+
 /* add multi(2) netfilters to a netdev and then remove the netdev */
 static void remove_netdev_with_multi_netfilter(void)
 {
@@ -187,6 +553,11 @@ int main(int argc, char **argv)
     qtest_add_func("/netfilter/remove_netdev_multi",
                    remove_netdev_with_multi_netfilter);
 
+    qtest_add_func("/netfilter/query_stats_tx", test_query_netfilter_stats_tx);
+    qtest_add_func("/netfilter/query_stats_rx", test_query_netfilter_stats_rx);
+    qtest_add_func("/netfilter/query_stats_redirector_outdev",
+                   test_query_netfilter_stats_redirector_outdev);
+
     args = g_strdup_printf("-nic user,id=qtest-bn0");
     qtest_start(args);
     ret = g_test_run();
Signature · 1 line
2.52.0
author
#8 lore raw

PATCH 6/12 netfilter: filter-redirector: always return iov_size()

In reply to Cindy Lu

From: Jason Wang <[email protected]>

filter-redirector forwards packets to a chardev (outdev). The backend write path may return 0 or a negative error even though the filter has consumed (and should account for) the packet.

Returning 0 propagates back to the sender (e.g. tap backend) as "cannot send" and can cause polling to be disabled, preventing further draining of tap traffic into the netfilter chain.

Always report the packet as consumed by returning iov_size() when outdev is connected. Errors are still reported, but the data path is kept progressing.

---
 net/filter-mirror.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/filter-mirror.c +1 -1
index 21598b97a7..eb703b7dee 100644
@@ -247,7 +247,7 @@ static ssize_t filter_redirector_receive_iov(NetFilterState *nf,
             s->outdev_packets++;
             s->outdev_bytes += ret;
         }
-        return ret;
+        return iov_size(iov, iovcnt);
     } else {
         return 0;
     }
Signature · 1 line
2.52.0
author
#9 lore raw

PATCH 7/12 netfilter: enable read_poll when redirector created while stopped

In reply to Cindy Lu

From: Jason Wang <[email protected]>

filter-redirector uses a vm change state handler to enable netdev read_poll() when enable_when_stopped=true and the VM stops, so that host traffic can be still drained into the netfilter chain while vCPUs are not running.

However, qemu_add_vm_change_state_handler() does not invoke the callback for the current VM state at registration time. If a redirector is created after the VM is already stopped (or if enable_when_stopped is toggled on while stopped), read_poll() may remain disabled and packets will not be drained.

Add a helper that checks the current runstate and proactively enables read_poll() when enable_when_stopped is set and the VM is already stopped. Call it from redirector setup and from the enable_when_stopped property setter.

---
 net/filter-mirror.c | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
net/filter-mirror.c +32 -0
index eb703b7dee..c1b9dabacd 100644
@@ -314,6 +314,27 @@ static void filter_redirector_vm_state_change(void *opaque, bool running,
     }
 }
 
+static void filter_redirector_maybe_enable_read_poll(NetFilterState *nf)
+{
+    MirrorState *s = FILTER_REDIRECTOR(nf);
+    NetClientState *nc = nf->netdev;
+
+    if (!nc || !nc->info || !nc->info->read_poll) {
+        return;
+    }
+
+    /*
+     * When a redirector is created while the VM is already stopped,
+     * qemu_add_vm_change_state_handler() will not immediately invoke the
+     * callback for the current state. If enable_when_stopped is set, we
+     * must proactively enable read_poll so that tap packets can be drained
+     * into the netfilter chain (e.g. redirector+buffer) during stop.
+     */
+    if (!runstate_is_running() && s->enable_when_stopped) {
+        nc->info->read_poll(nc, true);
+    }
+}
+
 static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(nf);
@@ -366,6 +387,8 @@ static void filter_redirector_setup(NetFilterState *nf, Error **errp)
 
     s->vmsentry = qemu_add_vm_change_state_handler(
         filter_redirector_vm_state_change, nf);
+
+    filter_redirector_maybe_enable_read_poll(nf);
 }
 
 static void filter_redirector_status_changed(NetFilterState *nf, Error **errp)
@@ -484,8 +507,17 @@ static void filter_redirector_set_enable_when_stopped(Object *obj,
                                                       Error **errp)
 {
     MirrorState *s = FILTER_REDIRECTOR(obj);
+    NetFilterState *nf = NETFILTER(obj);
 
     s->enable_when_stopped = value;
+
+    /*
+     * If toggled on while the VM is already stopped, ensure we enable read_poll
+     * immediately (vm_state_change callback only runs on transitions).
+     */
+    if (value) {
+        filter_redirector_maybe_enable_read_poll(nf);
+    }
 }
 
 static void filter_mirror_class_init(ObjectClass *oc, const void *data)
Signature · 1 line
2.52.0
author
#10 lore raw

PATCH 8/12 virtio-net: disable backend poll while stopped by default

In reply to Cindy Lu

From: Jason Wang <[email protected]>

When the VM is stopped, reading from the backend (e.g. tap) can pull host traffic into QEMU queues at a point where the core networking code may flush or purge queued packets on vmstop to avoid state changes while not running. This can show up as intermittent packet loss around stop/resume transitions.

Register a virtio-net vm change state handler that disables backend read_poll() while the VM is stopped, and re-enables it when the VM runs again. Use a higher priority so it runs early on vmstop, while allowing netfilter pipelines (e.g. redirector with enable_when_stopped) to re-enable polling explicitly when they are ready to handle traffic.

---
 hw/net/virtio-net.c            | 47 ++++++++++++++++++++++++++++++++++
 include/hw/virtio/virtio-net.h |  2 ++
 2 files changed, 49 insertions(+)
hw/net/virtio-net.c +47 -0
index 17ed0ef919..d6d2188863 100644
@@ -41,6 +41,7 @@
 #include "standard-headers/linux/ethtool.h"
 #include "system/system.h"
 #include "system/replay.h"
+#include "system/runstate.h"
 #include "trace.h"
 #include "monitor/qdev.h"
 #include "monitor/monitor.h"
@@ -1310,6 +1311,38 @@ static void virtio_net_disable_rss(VirtIONet *n)
     virtio_net_commit_rss_config(n);
 }
 
+static void virtio_net_backend_read_poll_set(VirtIONet *n, bool enable)
+{
+    int i;
+
+    if (!n->nic) {
+        return;
+    }
+
+    for (i = 0; i < (int)n->max_ncs; i++) {
+        NetClientState *frontend = qemu_get_subqueue(n->nic, i);
+        NetClientState *backend = frontend ? frontend->peer : NULL;
+
+        if (backend && backend->info && backend->info->read_poll) {
+            backend->info->read_poll(backend, enable);
+        }
+    }
+}
+
+static void virtio_net_vm_state_change_backend_poll(void *opaque, bool running,
+                                                    RunState state)
+{
+    VirtIONet *n = opaque;
+
+    /*
+     * Prevent backend (e.g. tap) from reading packets while the VM is stopped.
+     * This avoids pulling host->guest traffic into QEMU queues that may be
+     * purged on vmstop, and lets netfilter pipelines (e.g. redirector+buffer)
+     * explicitly re-enable polling when they are ready.
+     */
+    virtio_net_backend_read_poll_set(n, running);
+}
+
 static bool virtio_net_load_ebpf_fds(VirtIONet *n, Error **errp)
 {
     int fds[EBPF_RSS_MAX_FDS] = { [0 ... EBPF_RSS_MAX_FDS - 1] = -1};
@@ -4047,6 +4080,15 @@ static void virtio_net_device_realize(DeviceState *dev, Error **errp)
             n->rss_data.specified_hash_types.on_bits |
             n->rss_data.specified_hash_types.auto_bits;
     }
+
+    /*
+     * Default behavior: use a higher priority than netfilter redirector
+     * handlers (default 0) so that on vmstop we disable first, and redirectors
+     * can re-enable read_poll after this if enable_when_stopped is set.
+     */
+    n->backend_poll_vmstate =
+        qemu_add_vm_change_state_handler_prio(
+            virtio_net_vm_state_change_backend_poll, n, 10);
 }
 
 static void virtio_net_device_unrealize(DeviceState *dev)
@@ -4059,6 +4101,11 @@ static void virtio_net_device_unrealize(DeviceState *dev)
         virtio_net_unload_ebpf(n);
     }
 
+    if (n->backend_poll_vmstate) {
+        qemu_del_vm_change_state_handler(n->backend_poll_vmstate);
+        n->backend_poll_vmstate = NULL;
+    }
+
     /* This will stop vhost backend if appropriate. */
     virtio_net_set_status(vdev, 0);
 
include/hw/virtio/virtio-net.h +2 -0
index f708355306..a40a7d7cc6 100644
@@ -218,6 +218,8 @@ struct VirtIONet {
     uint64_t saved_guest_offloads;
     AnnounceTimer announce_timer;
     bool needs_vnet_hdr_swap;
+    /* Keep backend (e.g. tap) from reading while VM is stopped. */
+    VMChangeStateEntry *backend_poll_vmstate;
     bool mtu_bypass_backend;
     /* primary failover device is hidden*/
     bool failover_primary_hidden;
Signature · 1 line
2.52.0
author
#11 lore raw

PATCH 9/12 net/filter-mirror: treat redirector injections as raw frames

In reply to Cindy Lu

Packets injected from the redirector chardev are raw Ethernet frames without a vnet_hdr prefix. Mark them as RAW so downstream filters (e.g. dump) do not skip vnet_hdr_len bytes, and strip the vnet_hdr prefix only when vnet_hdr_support is enabled and a valid prefix is present.

---
 net/filter-mirror.c | 30 +++++++++++++++++++++++++-----
 1 file changed, 25 insertions(+), 5 deletions(-)
net/filter-mirror.c +25 -5
index c1b9dabacd..de32028246 100644
@@ -146,6 +146,7 @@ static int filter_send(MirrorState *s,
 }
 
 static void redirector_to_filter(NetFilterState *nf,
+                                 unsigned flags,
                                  const uint8_t *buf,
                                  int len)
 {
@@ -156,13 +157,13 @@ static void redirector_to_filter(NetFilterState *nf,
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_TX) {
-        qemu_netfilter_pass_to_next(nf->netdev, 0, &iov, 1, nf);
+        qemu_netfilter_pass_to_next(nf->netdev, flags, &iov, 1, nf);
     }
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_RX) {
-        qemu_netfilter_pass_to_next(nf->netdev->peer, 0, &iov, 1, nf);
-     }
+        qemu_netfilter_pass_to_next(nf->netdev->peer, flags, &iov, 1, nf);
+    }
 }
 
 static int redirector_chr_can_read(void *opaque)
@@ -294,12 +295,31 @@ static void redirector_rs_finalize(SocketReadState *rs)
 {
     MirrorState *s = container_of(rs, MirrorState, rs);
     NetFilterState *nf = NETFILTER(s);
+    const uint8_t *buf = rs->buf;
+    int len = rs->packet_len;
 
     /* Update indev statistics */
     s->indev_packets++;
-    s->indev_bytes += rs->packet_len;
+    s->indev_bytes += len;
+
+    /*
+     * If the sender enables vnet_hdr_support, received data includes a
+     * vnet_hdr prefix. Skip vnet_hdr_len bytes and pass the Ethernet frame.
+     */
+    if (s->vnet_hdr) {
+        if (rs->vnet_hdr_len <= 0 || rs->vnet_hdr_len >= len) {
+            return;
+        }
+        buf += rs->vnet_hdr_len;
+        len -= rs->vnet_hdr_len;
+    }
 
-    redirector_to_filter(nf, rs->buf, rs->packet_len);
+    /*
+     * Packets injected from the chardev are raw Ethernet frames without a
+     * vnet_hdr prefix. Mark them as RAW so downstream filters (e.g. dump)
+     * won't try to skip a vnet_hdr_len.
+     */
+    redirector_to_filter(nf, QEMU_NET_PACKET_FLAG_RAW, buf, len);
 }
 
 static void filter_redirector_vm_state_change(void *opaque, bool running,
Signature · 1 line
2.52.0
#12 lore raw

Re: [PATCH 09/12] net/filter-mirror: treat redirector injections as raw frames

Quoted 3 lines · Cindy Lu

Packets injected from the redirector chardev are raw Ethernet frames without a vnet_hdr prefix.

This may not be true as it could be the traffic from a remote redirector that is redirecting virtio-net traffic?

Thanks

Quoted 75 lines

Mark them as RAW so downstream filters (e.g. dump) do not skip vnet_hdr_len bytes, and strip the vnet_hdr prefix only when vnet_hdr_support is enabled and a valid prefix is present.

---
 net/filter-mirror.c | 30 +++++++++++++++++++++++++-----
 1 file changed, 25 insertions(+), 5 deletions(-)
net/filter-mirror.c +25 -6
index c1b9dabacd..de32028246 100644
@@ -146,6 +146,7 @@ static int filter_send(MirrorState *s,
 }
 
 static void redirector_to_filter(NetFilterState *nf,
+                                 unsigned flags,
                                  const uint8_t *buf,
                                  int len)
 {
@@ -156,13 +157,13 @@ static void redirector_to_filter(NetFilterState *nf,
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_TX) {
-        qemu_netfilter_pass_to_next(nf->netdev, 0, &iov, 1, nf);
+        qemu_netfilter_pass_to_next(nf->netdev, flags, &iov, 1, nf);
     }
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_RX) {
-        qemu_netfilter_pass_to_next(nf->netdev->peer, 0, &iov, 1, nf);
-     }
+        qemu_netfilter_pass_to_next(nf->netdev->peer, flags, &iov, 1, nf);
+    }
 }
 
 static int redirector_chr_can_read(void *opaque)
@@ -294,12 +295,31 @@ static void redirector_rs_finalize(SocketReadState *rs)
 {
     MirrorState *s = container_of(rs, MirrorState, rs);
     NetFilterState *nf = NETFILTER(s);
+    const uint8_t *buf = rs->buf;
+    int len = rs->packet_len;
 
     /* Update indev statistics */
     s->indev_packets++;
-    s->indev_bytes += rs->packet_len;
+    s->indev_bytes += len;
+
+    /*
+     * If the sender enables vnet_hdr_support, received data includes a
+     * vnet_hdr prefix. Skip vnet_hdr_len bytes and pass the Ethernet frame.
+     */
+    if (s->vnet_hdr) {
+        if (rs->vnet_hdr_len <= 0 || rs->vnet_hdr_len >= len) {
+            return;
+        }
+        buf += rs->vnet_hdr_len;
+        len -= rs->vnet_hdr_len;
+    }
 
-    redirector_to_filter(nf, rs->buf, rs->packet_len);
+    /*
+     * Packets injected from the chardev are raw Ethernet frames without a
+     * vnet_hdr prefix. Mark them as RAW so downstream filters (e.g. dump)
+     * won't try to skip a vnet_hdr_len.
+     */
+    redirector_to_filter(nf, QEMU_NET_PACKET_FLAG_RAW, buf, len);
 }
 
 static void filter_redirector_vm_state_change(void *opaque, bool running,
--

2.52.0

author
#13 lore raw

Re: [PATCH 09/12] net/filter-mirror: treat redirector injections as raw frames

Quoted 11 lines · Jason Wang
Quoted 3 lines · Cindy Lu

Packets injected from the redirector chardev are raw Ethernet frames without a vnet_hdr prefix.

This may not be true as it could be the traffic from a remote redirector that is redirecting virtio-net traffic?

Thanks

Hi Jason
sorry I should make the commit log more clear, in the code. I use the s->vnet_hdr to check the if they use the vnet_hdr, if yes then remove the head.
I should rewrite this commit log, what I mean is after this redirector process all
the packet would be the marked as RAW
Thanks
cindy

Quoted 76 lines
Quoted 75 lines

Mark them as RAW so downstream filters (e.g. dump) do not skip vnet_hdr_len bytes, and strip the vnet_hdr prefix only when vnet_hdr_support is enabled and a valid prefix is present.

---
 net/filter-mirror.c | 30 +++++++++++++++++++++++++-----
 1 file changed, 25 insertions(+), 5 deletions(-)
net/filter-mirror.c +25 -6
index c1b9dabacd..de32028246 100644
@@ -146,6 +146,7 @@ static int filter_send(MirrorState *s,
 }
 
 static void redirector_to_filter(NetFilterState *nf,
+                                 unsigned flags,
                                  const uint8_t *buf,
                                  int len)
 {
@@ -156,13 +157,13 @@ static void redirector_to_filter(NetFilterState *nf,
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_TX) {
-        qemu_netfilter_pass_to_next(nf->netdev, 0, &iov, 1, nf);
+        qemu_netfilter_pass_to_next(nf->netdev, flags, &iov, 1, nf);
     }
 
     if (nf->direction == NET_FILTER_DIRECTION_ALL ||
         nf->direction == NET_FILTER_DIRECTION_RX) {
-        qemu_netfilter_pass_to_next(nf->netdev->peer, 0, &iov, 1, nf);
-     }
+        qemu_netfilter_pass_to_next(nf->netdev->peer, flags, &iov, 1, nf);
+    }
 }
 
 static int redirector_chr_can_read(void *opaque)
@@ -294,12 +295,31 @@ static void redirector_rs_finalize(SocketReadState *rs)
 {
     MirrorState *s = container_of(rs, MirrorState, rs);
     NetFilterState *nf = NETFILTER(s);
+    const uint8_t *buf = rs->buf;
+    int len = rs->packet_len;
 
     /* Update indev statistics */
     s->indev_packets++;
-    s->indev_bytes += rs->packet_len;
+    s->indev_bytes += len;
+
+    /*
+     * If the sender enables vnet_hdr_support, received data includes a
+     * vnet_hdr prefix. Skip vnet_hdr_len bytes and pass the Ethernet frame.
+     */
+    if (s->vnet_hdr) {
+        if (rs->vnet_hdr_len <= 0 || rs->vnet_hdr_len >= len) {
+            return;
+        }
+        buf += rs->vnet_hdr_len;
+        len -= rs->vnet_hdr_len;
+    }
 
-    redirector_to_filter(nf, rs->buf, rs->packet_len);
+    /*
+     * Packets injected from the chardev are raw Ethernet frames without a
+     * vnet_hdr prefix. Mark them as RAW so downstream filters (e.g. dump)
+     * won't try to skip a vnet_hdr_len.
+     */
+    redirector_to_filter(nf, QEMU_NET_PACKET_FLAG_RAW, buf, len);
 }
 
 static void filter_redirector_vm_state_change(void *opaque, bool running,
--

2.52.0

author
#14 lore raw

PATCH 10/12 net/filter-buffer: store raw frames and synthesize vnet_hdr on release

In reply to Cindy Lu

Buffer only the Ethernet frame so packets can be re-framed using the current netdev vnet_hdr_len at release time (important across migration). Add a custom queue deliver callback to prepend a zeroed vnet_hdr when needed, and fix iov trimming to avoid freeing adjusted pointers or enqueueing empty packets.

---
 net/filter-buffer.c | 82 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 78 insertions(+), 4 deletions(-)
net/filter-buffer.c +78 -4
index 427da24097..f26b212b06 100644
@@ -8,6 +8,7 @@
 
 #include "qemu/osdep.h"
 #include "net/filter.h"
+#include "net/net.h"
 #include "net/queue.h"
 #include "qapi/error.h"
 #include "qemu/timer.h"
@@ -28,6 +29,43 @@ struct FilterBufferState {
     QEMUTimer release_timer;
 };
 
+static ssize_t filter_buffer_pass_to_next(NetClientState *sender,
+                                          unsigned flags,
+                                          const struct iovec *iov,
+                                          int iovcnt,
+                                          void *opaque)
+{
+    NetFilterState *nf = opaque;
+    int vnet_hdr_len = 0;
+
+    /*
+     * filter-buffer stores Ethernet frames without the vnet_hdr prefix.
+     * When releasing packets, synthesize a zeroed vnet_hdr of the current
+     * netdev vnet_hdr_len (if any) so the downstream NIC/backend sees the
+     * expected framing even across migration where vnet_hdr_len can change.
+     */
+    if (nf && nf->netdev) {
+        vnet_hdr_len = qemu_get_vnet_hdr_len(nf->netdev);
+    }
+
+    if (vnet_hdr_len > 0) {
+        uint8_t vnet_hdr[128] = { 0 };
+        g_autofree struct iovec *iov2 = g_new(struct iovec, iovcnt + 1);
+
+        g_assert((size_t)vnet_hdr_len <= sizeof(vnet_hdr));
+        iov2[0].iov_base = vnet_hdr;
+        iov2[0].iov_len = vnet_hdr_len;
+        memcpy(&iov2[1], iov, iovcnt * sizeof(*iov));
+
+        return qemu_netfilter_pass_to_next(sender,
+                                           QEMU_NET_PACKET_FLAG_NONE,
+                                           iov2, iovcnt + 1, opaque);
+    }
+
+    return qemu_netfilter_pass_to_next(sender, QEMU_NET_PACKET_FLAG_RAW,
+                                       iov, iovcnt, opaque);
+}
+
 static void filter_buffer_flush(NetFilterState *nf)
 {
     FilterBufferState *s = FILTER_BUFFER(nf);
@@ -64,6 +102,11 @@ static ssize_t filter_buffer_receive_iov(NetFilterState *nf,
                                          NetPacketSent *sent_cb)
 {
     FilterBufferState *s = FILTER_BUFFER(nf);
+    size_t skip = 0;
+    size_t total;
+    struct iovec *iov_copy;
+    struct iovec *iov_copy_base;
+    unsigned int iovcnt_copy;
 
     /*
      * We return size when buffer a packet, the sender will take it as
@@ -79,9 +122,40 @@ static ssize_t filter_buffer_receive_iov(NetFilterState *nf,
      * the packets without caring about the receiver. This is suboptimal.
      * May need more thoughts (e.g keeping sent_cb).
      */
-    qemu_net_queue_append_iov(s->incoming_queue, sender, flags,
-                              iov, iovcnt, NULL);
-    return iov_size(iov, iovcnt);
+    total = iov_size(iov, iovcnt);
+
+    /*
+     * The backend (e.g. tap) may prepend a vnet_hdr. Buffer only the Ethernet
+     * frame so we can re-synthesize the right vnet_hdr_len at release time.
+     */
+    if (!(flags & QEMU_NET_PACKET_FLAG_RAW) && nf->netdev) {
+        skip = qemu_get_vnet_hdr_len(nf->netdev);
+        if (skip > total) {
+            skip = total;
+        }
+    }
+
+    iov_copy = g_new(struct iovec, iovcnt);
+    iov_copy_base = iov_copy;
+    memcpy(iov_copy, iov, iovcnt * sizeof(*iov_copy));
+    iovcnt_copy = iovcnt;
+    if (skip) {
+        iov_discard_front(&iov_copy, &iovcnt_copy, skip);
+    }
+    if (iovcnt_copy == 0) {
+        g_free(iov_copy_base);
+        return total;
+    }
+
+    /*
+     * Stored packets are raw Ethernet frames (no vnet_hdr prefix).
+     */
+    qemu_net_queue_append_iov(s->incoming_queue, sender,
+                              QEMU_NET_PACKET_FLAG_RAW,
+                              iov_copy, iovcnt_copy, NULL);
+    g_free(iov_copy_base);
+
+    return total;
 }
 
 static void filter_buffer_cleanup(NetFilterState *nf)
@@ -126,7 +200,7 @@ static void filter_buffer_setup(NetFilterState *nf, Error **errp)
         return;
     }
 
-    s->incoming_queue = qemu_new_net_queue(qemu_netfilter_pass_to_next, nf);
+    s->incoming_queue = qemu_new_net_queue(filter_buffer_pass_to_next, nf);
     filter_buffer_setup_timer(nf);
 }
 
Signature · 1 line
2.52.0
author
#15 lore raw

PATCH 11/12 virtio-net: re-apply vnet_hdr state after virtio_load

In reply to Cindy Lu

virtio_load() restores guest_features after vmstate post_load hooks. Re-apply vnet_hdr related state in virtio_net_post_load_virtio() so backend header lengths match the migrated feature set (important for netfilter pipelines).

---
 hw/net/virtio-net.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)
hw/net/virtio-net.c +15 -0
index d6d2188863..125aa0108d 100644
@@ -3282,6 +3282,21 @@ static int virtio_net_post_load_device(void *opaque, int version_id)
 static int virtio_net_post_load_virtio(VirtIODevice *vdev)
 {
     VirtIONet *n = VIRTIO_NET(vdev);
+    bool has_tunnel_hdr = virtio_has_tunnel_hdr(vdev->guest_features_ex);
+
+    /*
+     * virtio_load() restores guest_features after vmstate post_load hooks.
+     * Re-apply vnet_hdr related state here so the backend vnet_hdr_len and
+     * n->host_hdr_len match the migrated feature set (important for receiving
+     * packets from netfilters like redirector/buffer during COLO/migration).
+     */
+    peer_test_vnet_hdr(n);
+    virtio_net_set_mrg_rx_bufs(n, n->mergeable_rx_bufs,
+                               virtio_vdev_has_feature(vdev,
+                                                       VIRTIO_F_VERSION_1),
+                               virtio_vdev_has_feature(vdev,
+                                                      VIRTIO_NET_F_HASH_REPORT),
+                               has_tunnel_hdr);
     /*
      * The actual needed state is now in saved_guest_offloads,
      * see virtio_net_post_load_device for detail.
Signature · 1 line
2.52.0
author
#16 lore raw

PATCH 12/12 net/filter-mirror: keep mirroring while stopped

In reply to Cindy Lu

During migration pre-switchover the VM runstate is stopped, which can cause tap read_poll to be disabled (qemu_send_packet_async() returns 0) and incoming tap frames stop reaching the redirector/mirror filter.

Re-enable tap read_poll when swredir is turned on while stopped, and allow the redirector outdev path to keep draining packets while stopped by adding a per-NetClientState allow_send_when_stopped bit used by qemu_can_send_packet().

---
 include/net/net.h   |  6 ++++++
 net/filter-mirror.c | 49 +++++++++++++++++++++++++++++++++++++--------
 net/net.c           | 10 ++++++++-
 3 files changed, 56 insertions(+), 9 deletions(-)
include/net/net.h +6 -0
index d2b2e6fc44..bde052acbb 100644
@@ -126,6 +126,12 @@ struct NetClientState {
     char *name;
     char info_str[256];
     unsigned receive_disabled : 1;
+    /*
+     * Allow this sender to keep draining packets while VM is stopped.
+     * Used by COLO-style pre-switchover mirroring, where netfilter needs to
+     * see incoming tap frames even when runstate is not running.
+     */
+    unsigned allow_send_when_stopped:1;
     NetClientDestructor *destructor;
     unsigned int queue_index;
     unsigned rxfilter_notify_enabled:1;
net/filter-mirror.c +41 -8

83 lines not on this page · raw message

net/net.c +9 -1
index b15f4db65e..06f54eebb4 100644
@@ -632,7 +632,7 @@ int qemu_can_send_packet(NetClientState *sender)
 {
     int vm_running = runstate_is_running();
 
-    if (!vm_running) {
+    if (!vm_running && !sender->allow_send_when_stopped) {
         return 0;
     }
 
@@ -640,6 +640,14 @@ int qemu_can_send_packet(NetClientState *sender)
         return 1;
     }
 
+    /*
+     * When VM is stopped (e.g. migration pre-switchover), allow draining tap
+     * packets so netfilters (redirector/mirror) can operate.
+     */
+    if (!vm_running && sender->allow_send_when_stopped) {
+        return 1;
+    }
+
     return qemu_can_receive_packet(sender->peer);
 }
 
Signature · 1 line
2.52.0