| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/11/18 10:04 | flow | patch-triage |
13mArgs:null Results: {
"EnableConfigs": [
"VSOCKETS",
"VIRTIO_VSOCKETS",
"VHOST_VSOCK"
],
"FocusSymbols": [
"vsock_nl_dev_netns_set_doit",
"vsock_nl_dev_netns_get_doit",
"vsock_maybe_set_connected",
"vsock_g2h_net_reachable",
"vsock_g2h_reachable_sk",
"vsock_find_cid",
"__vsock_find_cid",
"vhost_vsock_set_cid",
"virtio_transport_recv_connecting",
"virtio_transport_recv_listen"
],
"KMSANReasoning": "The patch series introduces a Generic Netlink control interface (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET) and transport reachability checks to support assigning the guest-to-host vsock device to specific network namespaces.\n\nEvaluating KMSAN vs KASAN applicability:\n- Data sent to userspace: In the netlink dump/get path (vsock_nl_dev_netns_fill), the netns ID is sent via nla_put_s32(), which writes a 4-byte scalar value, with netlink attribute alignment padding zeroed by netlink helpers. The local variable 'id' is guaranteed to be initialized when !equal, and is never evaluated when equal is true. Similarly, IOCTL_VM_SOCKETS_GET_LOCAL_CID writes a u32 CID that is unconditionally initialized before put_user(). There are no uninitialized struct fields, padding, or kernel-to-user info-leak risks.\n- Local variables and control flow: All local variables across the new functions (e.g. vsock_nl_dev_netns_set_doit, vsock_g2h_net_assign, vsock_g2h_reset_unreachable, vhost_vsock_set_cid) are fully initialized prior to evaluation.\n- Primary bug risks: The changes introduce complex locking (ordering between vsock_g2h_assign_mutex, vsock_register_mutex, vsock_table_lock, and socket locks), RCU dereferencing of vsock_g2h_net, network namespace reference tracking (get_net_track/put_net_track), and connected socket cleanup logic. Any potential defects here would manifest as deadlocks, race conditions, use-after-free, or refcount imbalances, all of which are covered by LOCKDEP and standard KASAN builds.\n\nTherefore, there are no uninitialized memory risks that justify running a dedicated KMSAN fuzzing session.",
"NeedsKMSAN": false,
"Reasoning": "The patch series introduces a new Generic Netlink family (\"vsock\") allowing user space (with CAP_NET_ADMIN) to assign the guest-to-host (G2H) vsock device to different network namespaces (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET). It also modifies core AF_VSOCK socket state handling, namespace tracking and reference lifetime, CID resolution under concurrency, and virtio/vhost vsock transport connection lifecycle logic. These changes execute in reachable networking code accessible in standard virtualized environments and should be fuzzed for concurrency, state management, and refcount regressions.",
"WorthFuzzing": true
} |
| 1/1 | 2026/11/18 10:04 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 190eefd6dcf9994800a722359e674bd7ddd1931e\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Wed Nov 18 10:04:32 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/Documentation/admin-guide/sysctl/net.rst b/Documentation/admin-guide/sysctl/net.rst\nindex fe43e85959583e..87bde0fe1ccfc2 100644\n--- a/Documentation/admin-guide/sysctl/net.rst\n+++ b/Documentation/admin-guide/sysctl/net.rst\n@@ -529,6 +529,49 @@ their hosts. The behavior of VSOCK sockets in a network namespace is determined\n by the namespace's mode (``global`` or ``local``), which controls how CIDs\n (Context IDs) are allocated and how sockets interact across namespaces.\n \n+In a guest, the vsock device owned by the guest-to-host (G2H) transport belongs\n+to one network namespace at a time. The ``VSOCK_CMD_DEV_NETNS_SET`` command of\n+the ``vsock`` netlink family, described in\n+Documentation/netlink/specs/vsock.yaml, moves it to a namespace given by fd or\n+PID, or else to the namespace the request was sent from. It requires\n+``CAP_NET_ADMIN`` in the initial user namespace.\n+The namespace's mode decides who may then use the device:\n+\n+- ``global`` - every ``global`` mode namespace may use it.\n+- ``local`` - only that namespace may use it, which reserves the connection to\n+ the host for it alone.\n+\n+The device starts out in init_net, so until the command is issued nothing has\n+moved and no mode has changed.\n+\n+Support is transport dependent. A G2H transport that does not implement the\n+move refuses the command with ``EOPNOTSUPP``. Of the in-tree guest transports,\n+only virtio-vsock implements it.\n+\n+A namespace that cannot reach the device sees the vsock addresses it would see\n+if no G2H transport were loaded: the device's CID is not one of its local CIDs,\n+and with ``vsock_loopback`` loaded, ``VMADDR_CID_HOST`` (2) is served by\n+loopback.\n+\n+Connections established before the move, from a namespace that can no longer\n+reach the device, are closed with ``ECONNRESET``. Nothing is sent to the peer,\n+which is what already happens when the device is removed altogether: the peer\n+finds out on its next send, which no longer matches a socket and so is answered\n+with a reset. A peer that only receives waits for its own timeout. A connection\n+still being set up when the device moves is refused with a reset once the peer\n+answers it.\n+\n+An assignment keeps the namespace alive, the same way an open socket does, so\n+deleting that namespace does not move the device. Assigning the device to\n+another namespace, such as init_net, is the only way to undo an assignment, and\n+releases the reference the assignment held on the previous namespace.\n+\n+The move is refused with ``EADDRINUSE`` if a guest registered in the target\n+namespace already answers to the device's CID, since the CID would otherwise\n+name two different peers there. If a loaded H2G transport cannot check that,\n+the move is refused with ``EOPNOTSUPP``. Of the in-tree host transports, only\n+vhost-vsock can.\n+\n ns_mode\n -------\n \ndiff --git a/Documentation/netlink/specs/vsock.yaml b/Documentation/netlink/specs/vsock.yaml\nnew file mode 100644\nindex 00000000000000..f260ee88b14024\n--- /dev/null\n+++ b/Documentation/netlink/specs/vsock.yaml\n@@ -0,0 +1,89 @@\n+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+#\n+# Copyright (c) 2026 Meta Platforms, Inc. and affiliates\n+#\n+---\n+name: vsock\n+\n+doc: |\n+ Control interface for the vsock (AF_VSOCK) core.\n+\n+protocol: genetlink\n+\n+uapi-header: linux/vsock_netlink.h\n+\n+attribute-sets:\n+ -\n+ name: vsock\n+ attributes:\n+ -\n+ name: netns-id\n+ type: s32\n+ doc: |\n+ Network namespace the guest's vsock device is assigned to, as an\n+ nsid relative to the caller.\n+\n+ Absent when the device is in the caller's own namespace, and\n+ NETNSA_NSID_NOT_ASSIGNED when the g2h transport supports netns\n+ assignment and the caller's namespace cannot reach the device under\n+ the mode rules, or when no nsid could be allocated for it.\n+ -\n+ name: netns-fd\n+ type: u32\n+ doc: |\n+ File descriptor of the network namespace to move the guest's vsock\n+ device to.\n+ -\n+ name: netns-pid\n+ type: u32\n+ doc: |\n+ PID of a process in the network namespace to move the guest's vsock\n+ device to.\n+\n+operations:\n+ list:\n+ -\n+ name: dev-netns-set\n+ doc: |\n+ Set the network namespace of the guest's vsock device.\n+\n+ The device is moved to the namespace given by netns-fd or netns-pid,\n+ or to the namespace the request was sent from if neither is given.\n+ It starts out in init_net, and moving it back there is how an\n+ assignment is undone.\n+\n+ A g2h transport that does not support netns assignment returns\n+ EOPNOTSUPP. If the netns assignment would cause a CID collision, it\n+ is rejected with EADDRINUSE.\n+\n+ The namespace's mode decides who may then use the device: a global\n+ mode namespace shares it with every other global mode namespace,\n+ while a local mode namespace reserves it for itself.\n+\n+ Movement to an unreachable local namespace results in sockets being\n+ closed with ECONNRESET. Peers are not guaranteed to be notified via\n+ an RST.\n+\n+ The assignment holds a reference on the namespace.\n+ attribute-set: vsock\n+ flags: [admin-perm]\n+ do:\n+ request:\n+ attributes:\n+ - netns-fd\n+ - netns-pid\n+ -\n+ name: dev-netns-get\n+ doc: |\n+ Get the network namespace the guest's vsock device is assigned to.\n+\n+ The namespace is reported as an nsid relative to the caller, so the\n+ attribute is absent when the device is already in the caller's own\n+ namespace. If the g2h transport supports netns assignment, a caller\n+ whose namespace cannot reach the device is told\n+ NETNSA_NSID_NOT_ASSIGNED rather than where the device went.\n+ attribute-set: vsock\n+ do:\n+ reply:\n+ attributes:\n+ - netns-id\ndiff --git a/MAINTAINERS b/MAINTAINERS\nindex 7636ab50d44fbe..95c8882669bbbb 100644\n--- a/MAINTAINERS\n+++ b/MAINTAINERS\n@@ -29169,10 +29169,12 @@ M:\tStefano Garzarella \u003csgarzare@redhat.com\u003e\n L:\tvirtualization@lists.linux.dev\n L:\tnetdev@vger.kernel.org\n S:\tMaintained\n+F:\tDocumentation/netlink/specs/vsock.yaml\n F:\tdrivers/net/vsockmon.c\n F:\tinclude/net/af_vsock.h\n F:\tinclude/uapi/linux/vm_sockets.h\n F:\tinclude/uapi/linux/vm_sockets_diag.h\n+F:\tinclude/uapi/linux/vsock_netlink.h\n F:\tinclude/uapi/linux/vsockmon.h\n F:\tnet/vmw_vsock/\n F:\ttools/testing/selftests/vsock/\ndiff --git a/drivers/vhost/vsock.c b/drivers/vhost/vsock.c\nindex abed1fbcf66cc5..1a03cff56c5aa4 100644\n--- a/drivers/vhost/vsock.c\n+++ b/drivers/vhost/vsock.c\n@@ -91,10 +91,8 @@ static struct vhost_vsock *vhost_vsock_get(u32 guest_cid, struct net *net)\n \treturn NULL;\n }\n \n-static bool vhost_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)\n+static bool vhost_transport_has_remote_cid(struct net *net, u32 cid)\n {\n-\tstruct sock *sk = sk_vsock(vsk);\n-\tstruct net *net = sock_net(sk);\n \tbool found;\n \n \trcu_read_lock();\n@@ -817,6 +815,7 @@ static int vhost_vsock_dev_release(struct inode *inode, struct file *file)\n static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)\n {\n \tstruct vhost_vsock *other;\n+\tint ret;\n \n \t/* Refuse reserved CIDs */\n \tif (guest_cid \u003c= VMADDR_CID_HOST ||\n@@ -830,15 +829,20 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)\n \t/* Refuse if CID is assigned to the guest-\u003ehost transport (i.e. nested\n \t * VM), to make the loopback work.\n \t */\n-\tif (vsock_find_cid(guest_cid))\n-\t\treturn -EADDRINUSE;\n+\tvsock_cid_lock();\n+\n+\tif (__vsock_find_cid(vsock-\u003enet, guest_cid)) {\n+\t\tret = -EADDRINUSE;\n+\t\tgoto unlock;\n+\t}\n \n \t/* Refuse if CID is already in use */\n \tmutex_lock(\u0026vhost_vsock_mutex);\n \tother = vhost_vsock_get(guest_cid, vsock-\u003enet);\n \tif (other \u0026\u0026 other != vsock) {\n \t\tmutex_unlock(\u0026vhost_vsock_mutex);\n-\t\treturn -EADDRINUSE;\n+\t\tret = -EADDRINUSE;\n+\t\tgoto unlock;\n \t}\n \n \tif (vsock-\u003eguest_cid)\n@@ -848,7 +852,12 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)\n \thash_add_rcu(vhost_vsock_hash, \u0026vsock-\u003ehash, vsock-\u003eguest_cid);\n \tmutex_unlock(\u0026vhost_vsock_mutex);\n \n-\treturn 0;\n+\tret = 0;\n+\n+unlock:\n+\tvsock_cid_unlock();\n+\n+\treturn ret;\n }\n \n static int vhost_vsock_set_features(struct vhost_vsock *vsock, u64 features)\ndiff --git a/include/net/af_vsock.h b/include/net/af_vsock.h\nindex 5549298c1ec6b3..fa025dd754a1f4 100644\n--- a/include/net/af_vsock.h\n+++ b/include/net/af_vsock.h\n@@ -9,6 +9,7 @@\n #define __AF_VSOCK_H__\n \n #include \u003clinux/kernel.h\u003e\n+#include \u003clinux/mutex.h\u003e\n #include \u003clinux/workqueue.h\u003e\n #include \u003cnet/netns/vsock.h\u003e\n #include \u003cnet/sock.h\u003e\n@@ -183,13 +184,16 @@ struct vsock_transport {\n \t * CIDs via the hypervisor (i.e. supports the fallback overlay). VMCI\n \t * does not implement this as it only serves CIDs 0 and 2.\n \t */\n-\tbool (*has_remote_cid)(struct vsock_sock *vsk, u32 remote_cid);\n+\tbool (*has_remote_cid)(struct net *net, u32 remote_cid);\n \n \t/* Read a single skb */\n \tint (*read_skb)(struct vsock_sock *, skb_read_actor_t);\n \n \t/* Zero-copy. */\n \tbool (*msgzerocopy_allow)(void);\n+\n+\t/* True if the G2H transport honours VSOCK_CMD_DEV_NETNS_SET. */\n+\tbool netns_assign_allow;\n };\n \n /**** CORE ****/\n@@ -233,11 +237,20 @@ bool vsock_check_source(const struct vsock_sock *vsk,\n \t\t\tconst struct vsock_transport *transport,\n \t\t\tconst struct sockaddr_vm *src);\n void vsock_remove_sock(struct vsock_sock *vsk);\n-void vsock_for_each_connected_socket(struct vsock_transport *transport,\n+void vsock_for_each_connected_socket(const struct vsock_transport *transport,\n \t\t\t\t void (*fn)(struct sock *sk));\n int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk);\n-bool vsock_find_cid(unsigned int cid);\n+bool vsock_find_cid(struct net *net, unsigned int cid);\n+void vsock_cid_lock(void);\n+void vsock_cid_unlock(void);\n+/* Caller must hold vsock_cid_lock(). */\n+bool __vsock_find_cid(struct net *net, unsigned int cid);\n void vsock_linger(struct sock *sk);\n+struct net *vsock_g2h_net_get(netns_tracker *tracker);\n+bool vsock_g2h_net_eq(const struct net *net);\n+bool vsock_g2h_net_reachable(struct net *net);\n+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk);\n+bool vsock_maybe_set_connected(struct vsock_sock *vsk);\n \n /**** TAP ****/\n \ndiff --git a/include/uapi/linux/vsock_netlink.h b/include/uapi/linux/vsock_netlink.h\nnew file mode 100644\nindex 00000000000000..c7e23d0da17e19\n--- /dev/null\n+++ b/include/uapi/linux/vsock_netlink.h\n@@ -0,0 +1,30 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit directly, auto-generated from: */\n+/*\tDocumentation/netlink/specs/vsock.yaml */\n+/* YNL-GEN uapi header */\n+/* To regenerate run: tools/net/ynl/ynl-regen.sh */\n+\n+#ifndef _UAPI_LINUX_VSOCK_NETLINK_H\n+#define _UAPI_LINUX_VSOCK_NETLINK_H\n+\n+#define VSOCK_FAMILY_NAME\t\"vsock\"\n+#define VSOCK_FAMILY_VERSION\t1\n+\n+enum {\n+\tVSOCK_A_NETNS_ID = 1,\n+\tVSOCK_A_NETNS_FD,\n+\tVSOCK_A_NETNS_PID,\n+\n+\t__VSOCK_A_MAX,\n+\tVSOCK_A_MAX = (__VSOCK_A_MAX - 1)\n+};\n+\n+enum {\n+\tVSOCK_CMD_DEV_NETNS_SET = 1,\n+\tVSOCK_CMD_DEV_NETNS_GET,\n+\n+\t__VSOCK_CMD_MAX,\n+\tVSOCK_CMD_MAX = (__VSOCK_CMD_MAX - 1)\n+};\n+\n+#endif /* _UAPI_LINUX_VSOCK_NETLINK_H */\ndiff --git a/net/vmw_vsock/Makefile b/net/vmw_vsock/Makefile\nindex 5da74c4a9f1d1b..97e2a559e2bf3d 100644\n--- a/net/vmw_vsock/Makefile\n+++ b/net/vmw_vsock/Makefile\n@@ -7,7 +7,7 @@ obj-$(CONFIG_VIRTIO_VSOCKETS_COMMON) += vmw_vsock_virtio_transport_common.o\n obj-$(CONFIG_HYPERV_VSOCKETS) += hv_sock.o\n obj-$(CONFIG_VSOCKETS_LOOPBACK) += vsock_loopback.o\n \n-vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o\n+vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o vsock_nl_gen.o\n vsock-$(CONFIG_BPF_SYSCALL) += vsock_bpf.o\n \n vsock_diag-y += diag.o\ndiff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c\nindex 483af15a5109eb..3bc9eee8ad9daf 100644\n--- a/net/vmw_vsock/af_vsock.c\n+++ b/net/vmw_vsock/af_vsock.c\n@@ -130,6 +130,27 @@\n * a different transport that *does* support local mode. For\n * example, virtio-vsock may not support local mode, but the socket\n * may still accept a connection from vhost-vsock which does.\n+ *\n+ * - A guest has a single vsock device, owned by the guest-\u003ehost transport.\n+ * The VSOCK_CMD_DEV_NETNS_SET netlink command moves it to a namespace given\n+ * by fd or PID, or else to the one the request was sent from. It starts\n+ * out in init_net. The mode rules then decide who may use it, and which\n+ * namespace packets from the host are delivered to:\n+ *\n+ * - assigned to a global mode namespace - every global mode namespace may\n+ * use it. Until the command is issued nothing has moved and no mode has\n+ * changed, so the default is the behaviour that predates it.\n+ * - assigned to a local mode namespace - only that namespace may use it.\n+ * This is how a nested VM is isolated from the rest of the guest.\n+ *\n+ * Connections made before an assignment, from a namespace that can no\n+ * longer reach the device, are closed with ECONNRESET. Nothing is sent to\n+ * the peer. As with device removal, it finds out on its next send.\n+ *\n+ * The assignment holds a reference on the namespace, the way an open socket\n+ * does, so deleting that namespace does not move the device: its destruction\n+ * is deferred until the device moves to another namespace, on another\n+ * assignment or when the transport unregisters.\n */\n \n #include \u003clinux/compat.h\u003e\n@@ -161,10 +182,14 @@\n #include \u003clinux/workqueue.h\u003e\n #include \u003cnet/sock.h\u003e\n #include \u003cnet/af_vsock.h\u003e\n+#include \u003clinux/net_namespace.h\u003e\n+#include \u003cnet/genetlink.h\u003e\n #include \u003cnet/netns/vsock.h\u003e\n #include \u003cuapi/linux/vm_sockets.h\u003e\n #include \u003cuapi/asm-generic/ioctls.h\u003e\n \n+#include \"vsock_nl_gen.h\"\n+\n #define VSOCK_NET_MODE_STR_GLOBAL \"global\"\n #define VSOCK_NET_MODE_STR_LOCAL \"local\"\n \n@@ -206,8 +231,21 @@ static const struct vsock_transport *transport_g2h;\n static const struct vsock_transport *transport_dgram;\n /* Transport used for local communication */\n static const struct vsock_transport *transport_local;\n+/* Protects transport registration and the g2h device's netns. */\n static DEFINE_MUTEX(vsock_register_mutex);\n \n+/* Network namespace of the g2h device. Protected by\n+ * vsock_register_mutex/RCU.\n+ */\n+static struct net __rcu *vsock_g2h_net = RCU_INITIALIZER(\u0026init_net);\n+static netns_tracker vsock_g2h_net_tracker;\n+\n+/* Held across an assign's swap and reset sweep, so that a later assign cannot\n+ * move the device back before the sweep has closed every socket that lost it.\n+ * Must be taken before vsock_register_mutex.\n+ */\n+static DEFINE_MUTEX(vsock_g2h_assign_mutex);\n+\n /**** UTILS ****/\n \n /* Each bound VSocket is stored in the bind hash table and each connected\n@@ -480,7 +518,7 @@ void vsock_remove_sock(struct vsock_sock *vsk)\n }\n EXPORT_SYMBOL_GPL(vsock_remove_sock);\n \n-void vsock_for_each_connected_socket(struct vsock_transport *transport,\n+void vsock_for_each_connected_socket(const struct vsock_transport *transport,\n \t\t\t\t void (*fn)(struct sock *sk))\n {\n \tint i;\n@@ -502,6 +540,37 @@ void vsock_for_each_connected_socket(struct vsock_transport *transport,\n }\n EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);\n \n+/* Return the next connected socket of @transport that @match accepts, with a\n+ * reference held. The scan starts at bucket *@bucket and leaves it where it\n+ * stopped, so calling again resumes there. Unlike\n+ * vsock_for_each_connected_socket(), the caller acts on the socket after\n+ * vsock_table_lock is dropped, so it can take lock_sock().\n+ */\n+static struct sock *\n+vsock_next_connected_socket(const struct vsock_transport *transport,\n+\t\t\t unsigned int *bucket,\n+\t\t\t bool (*match)(struct vsock_sock *vsk))\n+{\n+\tstruct vsock_sock *vsk;\n+\n+\tspin_lock_bh(\u0026vsock_table_lock);\n+\n+\tfor (; *bucket \u003c ARRAY_SIZE(vsock_connected_table); (*bucket)++) {\n+\t\tlist_for_each_entry(vsk, \u0026vsock_connected_table[*bucket],\n+\t\t\t\t connected_table) {\n+\t\t\tif (vsk-\u003etransport == transport \u0026\u0026 match(vsk)) {\n+\t\t\t\tsock_hold(sk_vsock(vsk));\n+\t\t\t\tspin_unlock_bh(\u0026vsock_table_lock);\n+\t\t\t\treturn sk_vsock(vsk);\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\tspin_unlock_bh(\u0026vsock_table_lock);\n+\n+\treturn NULL;\n+}\n+\n void vsock_add_pending(struct sock *listener, struct sock *pending)\n {\n \tstruct vsock_sock *vlistener;\n@@ -553,7 +622,42 @@ void vsock_enqueue_accept(struct sock *listener, struct sock *connected)\n }\n EXPORT_SYMBOL_GPL(vsock_enqueue_accept);\n \n-static bool vsock_use_local_transport(unsigned int remote_cid)\n+/* Return true if @t honours namespace assignment. One that does not keeps the\n+ * reachability rules it had before VSOCK_CMD_DEV_NETNS_SET existed.\n+ */\n+static bool vsock_net_assignable(const struct vsock_transport *t)\n+{\n+\treturn t \u0026\u0026 t-\u003enetns_assign_allow;\n+}\n+\n+static bool vsock_g2h_unreachable(const struct vsock_transport *t,\n+\t\t\t\t struct net *net)\n+{\n+\treturn t == transport_g2h \u0026\u0026 vsock_net_assignable(t) \u0026\u0026\n+\t !vsock_g2h_net_reachable(net);\n+}\n+\n+/* Return the CID of the transport in @transport, as seen from @net.\n+ *\n+ * Returns VMADDR_CID_ANY if the transport supports net assignment but is not\n+ * reachable from the net.\n+ */\n+static u32\n+__vsock_registered_transport_cid(const struct vsock_transport **transport,\n+\t\t\t\t struct net *net)\n+{\n+\tlockdep_assert_held(\u0026vsock_register_mutex);\n+\n+\tif (!*transport)\n+\t\treturn VMADDR_CID_ANY;\n+\n+\tif (vsock_g2h_unreachable(*transport, net))\n+\t\treturn VMADDR_CID_ANY;\n+\n+\treturn (*transport)-\u003eget_local_cid();\n+}\n+\n+static bool vsock_use_local_transport(struct net *net, unsigned int remote_cid)\n {\n \tlockdep_assert_held(\u0026vsock_register_mutex);\n \n@@ -563,11 +667,10 @@ static bool vsock_use_local_transport(unsigned int remote_cid)\n \tif (remote_cid == VMADDR_CID_LOCAL)\n \t\treturn true;\n \n-\tif (transport_g2h) {\n+\tif (transport_g2h \u0026\u0026 !vsock_g2h_unreachable(transport_g2h, net))\n \t\treturn remote_cid == transport_g2h-\u003eget_local_cid();\n-\t} else {\n-\t\treturn remote_cid == VMADDR_CID_HOST;\n-\t}\n+\n+\treturn remote_cid == VMADDR_CID_HOST;\n }\n \n static void vsock_deassign_transport(struct vsock_sock *vsk)\n@@ -626,18 +729,20 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)\n \t\tbreak;\n \tcase SOCK_STREAM:\n \tcase SOCK_SEQPACKET:\n-\t\tif (vsock_use_local_transport(remote_cid))\n+\t\tif (vsock_use_local_transport(sock_net(sk), remote_cid))\n \t\t\tnew_transport = transport_local;\n \t\telse if (remote_cid \u003c= VMADDR_CID_HOST ||\n \t\t\t (remote_flags \u0026 VMADDR_FLAG_TO_HOST))\n \t\t\tnew_transport = transport_g2h;\n \t\telse if (transport_h2g \u0026\u0026\n \t\t\t (!transport_h2g-\u003ehas_remote_cid ||\n-\t\t\t transport_h2g-\u003ehas_remote_cid(vsk, remote_cid)))\n+\t\t\t transport_h2g-\u003ehas_remote_cid(sock_net(sk),\n+\t\t\t\t\t\t\tremote_cid)))\n \t\t\tnew_transport = transport_h2g;\n \t\telse if (sock_net(sk)-\u003evsock.g2h_fallback \u0026\u0026\n \t\t\t transport_g2h \u0026\u0026 transport_g2h-\u003ehas_remote_cid \u0026\u0026\n-\t\t\t transport_g2h-\u003ehas_remote_cid(vsk, remote_cid)) {\n+\t\t\t transport_g2h-\u003ehas_remote_cid(sock_net(sk),\n+\t\t\t\t\t\t remote_cid)) {\n \t\t\tvsk-\u003eremote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;\n \t\t\tnew_transport = transport_g2h;\n \t\t} else {\n@@ -649,6 +754,11 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)\n \t\tgoto err;\n \t}\n \n+\tif (vsock_g2h_unreachable(new_transport, sock_net(sk))) {\n+\t\tret = -ENETUNREACH;\n+\t\tgoto err;\n+\t}\n+\n \tif (vsk-\u003etransport \u0026\u0026 vsk-\u003etransport == new_transport) {\n \t\tret = 0;\n \t\tgoto err;\n@@ -715,21 +825,39 @@ EXPORT_SYMBOL_GPL(vsock_assign_transport);\n * Provide safe access to static transport_{h2g,g2h,dgram,local} callbacks.\n * Otherwise we may race with module removal. Do not use on `vsk-\u003etransport`.\n */\n-static u32 vsock_registered_transport_cid(const struct vsock_transport **transport)\n+static u32\n+vsock_registered_transport_cid(const struct vsock_transport **transport,\n+\t\t\t struct net *net)\n {\n-\tu32 cid = VMADDR_CID_ANY;\n+\tu32 cid;\n \n \tmutex_lock(\u0026vsock_register_mutex);\n-\tif (*transport)\n-\t\tcid = (*transport)-\u003eget_local_cid();\n+\tcid = __vsock_registered_transport_cid(transport, net);\n \tmutex_unlock(\u0026vsock_register_mutex);\n \n \treturn cid;\n }\n \n-bool vsock_find_cid(unsigned int cid)\n+/* Keep the CIDs checked by __vsock_find_cid() stable: transport registration\n+ * and g2h device netns assignment both wait for vsock_cid_unlock().\n+ */\n+void vsock_cid_lock(void)\n+{\n+\tmutex_lock(\u0026vsock_register_mutex);\n+}\n+EXPORT_SYMBOL_GPL(vsock_cid_lock);\n+\n+void vsock_cid_unlock(void)\n+{\n+\tmutex_unlock(\u0026vsock_register_mutex);\n+}\n+EXPORT_SYMBOL_GPL(vsock_cid_unlock);\n+\n+bool __vsock_find_cid(struct net *net, unsigned int cid)\n {\n-\tif (cid == vsock_registered_transport_cid(\u0026transport_g2h))\n+\tlockdep_assert_held(\u0026vsock_register_mutex);\n+\n+\tif (cid == __vsock_registered_transport_cid(\u0026transport_g2h, net))\n \t\treturn true;\n \n \tif (transport_h2g \u0026\u0026 cid == VMADDR_CID_HOST)\n@@ -740,8 +868,273 @@ bool vsock_find_cid(unsigned int cid)\n \n \treturn false;\n }\n+EXPORT_SYMBOL_GPL(__vsock_find_cid);\n+\n+bool vsock_find_cid(struct net *net, unsigned int cid)\n+{\n+\tbool found;\n+\n+\tmutex_lock(\u0026vsock_register_mutex);\n+\tfound = __vsock_find_cid(net, cid);\n+\tmutex_unlock(\u0026vsock_register_mutex);\n+\n+\treturn found;\n+}\n EXPORT_SYMBOL_GPL(vsock_find_cid);\n \n+/* Return the namespace the g2h device is assigned to, with a reference held.\n+ *\n+ * The assignment itself holds a reference, so the namespace cannot be going\n+ * away here and this never fails.\n+ */\n+struct net *vsock_g2h_net_get(netns_tracker *tracker)\n+{\n+\tstruct net *net;\n+\n+\trcu_read_lock();\n+\tnet = rcu_dereference(vsock_g2h_net);\n+\tget_net_track(net, tracker, GFP_ATOMIC);\n+\trcu_read_unlock();\n+\n+\treturn net;\n+}\n+EXPORT_SYMBOL_GPL(vsock_g2h_net_get);\n+\n+/* True if @net is still the namespace the device is assigned to. Cheap enough\n+ * to call per packet on the RX path.\n+ */\n+bool vsock_g2h_net_eq(const struct net *net)\n+{\n+\treturn rcu_access_pointer(vsock_g2h_net) == net;\n+}\n+EXPORT_SYMBOL_GPL(vsock_g2h_net_eq);\n+\n+bool vsock_g2h_net_reachable(struct net *net)\n+{\n+\tbool reachable;\n+\n+\trcu_read_lock();\n+\treachable = vsock_net_check_mode(net, rcu_dereference(vsock_g2h_net));\n+\trcu_read_unlock();\n+\n+\treturn reachable;\n+}\n+EXPORT_SYMBOL_GPL(vsock_g2h_net_reachable);\n+\n+/* True if @vsk can reach the g2h device, or its transport ignores namespace\n+ * assignment.\n+ */\n+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk)\n+{\n+\tif (!vsock_net_assignable(vsk-\u003etransport))\n+\t\treturn true;\n+\n+\treturn vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));\n+}\n+EXPORT_SYMBOL_GPL(vsock_g2h_reachable_sk);\n+\n+/* Move @vsk to TCP_ESTABLISHED and into the connected table, unless the device\n+ * has moved to a namespace @vsk cannot reach. Returns false without doing\n+ * either in that case.\n+ *\n+ * The reset sweep walks the same table under the same lock, so an assign\n+ * cannot land between the check and the insert: either the sweep finds @vsk\n+ * and closes it, or @vsk is never added.\n+ */\n+bool vsock_maybe_set_connected(struct vsock_sock *vsk)\n+{\n+\tstruct list_head *list;\n+\tbool reachable;\n+\n+\tlist = vsock_connected_sockets(\u0026vsk-\u003eremote_addr, \u0026vsk-\u003elocal_addr);\n+\n+\tspin_lock_bh(\u0026vsock_table_lock);\n+\treachable = vsock_g2h_reachable_sk(vsk);\n+\tif (reachable) {\n+\t\tsk_vsock(vsk)-\u003esk_state = TCP_ESTABLISHED;\n+\t\t__vsock_insert_connected(list, vsk);\n+\t}\n+\tspin_unlock_bh(\u0026vsock_table_lock);\n+\n+\treturn reachable;\n+}\n+EXPORT_SYMBOL_GPL(vsock_maybe_set_connected);\n+\n+static bool vsock_g2h_should_reset(struct vsock_sock *vsk)\n+{\n+\treturn READ_ONCE(sk_vsock(vsk)-\u003esk_state) != TCP_CLOSE \u0026\u0026\n+\t !READ_ONCE(vsk-\u003eclose_work_scheduled) \u0026\u0026\n+\t !vsock_g2h_reachable_sk(vsk);\n+}\n+\n+/* Close every connected socket of @t that can no longer reach the g2h device.\n+ */\n+static void vsock_g2h_reset_unreachable(const struct vsock_transport *t)\n+{\n+\tstruct vsock_sock *vsk;\n+\tunsigned int i = 0;\n+\tstruct sock *sk;\n+\tbool reset;\n+\n+\tlockdep_assert_held(\u0026vsock_g2h_assign_mutex);\n+\tlockdep_assert_not_held(\u0026vsock_register_mutex);\n+\n+\t/* lock_sock() cannot be taken under vsock_table_lock, so pick the\n+\t * sockets one at a time, then recheck each under both locks.\n+\t */\n+\twhile ((sk = vsock_next_connected_socket(t, \u0026i,\n+\t\t\t\t\t\t vsock_g2h_should_reset))) {\n+\t\tvsk = vsock_sk(sk);\n+\n+\t\tlock_sock(sk);\n+\n+\t\treset = false;\n+\t\tspin_lock_bh(\u0026vsock_table_lock);\n+\t\t/* It may have been closed since we dropped the table lock. */\n+\t\tif (__vsock_in_connected_table(vsk) \u0026\u0026 vsk-\u003etransport == t \u0026\u0026\n+\t\t vsock_g2h_should_reset(vsk)) {\n+\t\t\t__vsock_remove_connected(vsk);\n+\t\t\treset = true;\n+\t\t}\n+\t\tspin_unlock_bh(\u0026vsock_table_lock);\n+\n+\t\tif (reset) {\n+\t\t\tsock_set_flag(sk, SOCK_DONE);\n+\t\t\tWRITE_ONCE(vsk-\u003epeer_shutdown, SHUTDOWN_MASK);\n+\t\t\tsk-\u003esk_state = TCP_CLOSING;\n+\t\t\tsk-\u003esk_err = ECONNRESET;\n+\t\t\tsk_error_report(sk);\n+\t\t}\n+\n+\t\trelease_sock(sk);\n+\t\tsock_put(sk);\n+\t}\n+}\n+\n+/* Point the g2h device at @net, taking the reference that keeps @net alive,\n+ * and return the namespace it leaves behind.\n+ */\n+static struct net *vsock_g2h_net_swap(struct net *net, netns_tracker *old)\n+{\n+\tlockdep_assert_held(\u0026vsock_register_mutex);\n+\n+\t*old = vsock_g2h_net_tracker;\n+\tget_net_track(net, \u0026vsock_g2h_net_tracker, GFP_KERNEL);\n+\n+\treturn rcu_replace_pointer(vsock_g2h_net, net,\n+\t\t\t\t lockdep_is_held(\u0026vsock_register_mutex));\n+}\n+\n+/* Drop the namespace the device just left, once the readers that may still\n+ * see it in vsock_g2h_net_get() are gone. Runs without the mutex held.\n+ */\n+static void vsock_g2h_net_release(struct net *old, netns_tracker *tracker)\n+{\n+\tsynchronize_rcu();\n+\tput_net_track(old, tracker);\n+}\n+\n+static int vsock_nl_dev_netns_fill(struct sk_buff *msg, struct genl_info *info)\n+{\n+\tstruct net *net = genl_info_net(info);\n+\tstruct net *g2h;\n+\tbool equal;\n+\tvoid *hdr;\n+\ts32 id;\n+\n+\tg2h = rcu_dereference_protected(vsock_g2h_net,\n+\t\t\t\t\tlockdep_is_held(\u0026vsock_register_mutex));\n+\tequal = net_eq(net, g2h);\n+\tif (!equal) {\n+\t\tif (vsock_net_assignable(transport_g2h) \u0026\u0026\n+\t\t !vsock_net_check_mode(net, g2h))\n+\t\t\tid = NETNSA_NSID_NOT_ASSIGNED;\n+\t\telse\n+\t\t\tid = peernet2id_alloc(net, g2h, GFP_KERNEL);\n+\t}\n+\n+\thdr = genlmsg_iput(msg, info);\n+\tif (!hdr)\n+\t\treturn -EMSGSIZE;\n+\n+\tif (!equal \u0026\u0026 nla_put_s32(msg, VSOCK_A_NETNS_ID, id)) {\n+\t\tgenlmsg_cancel(msg, hdr);\n+\t\treturn -EMSGSIZE;\n+\t}\n+\n+\tgenlmsg_end(msg, hdr);\n+\n+\treturn 0;\n+}\n+\n+/* Move the g2h device to @net, which keeps @net alive until the device leaves\n+ * again. Returns -ENODEV if no g2h transport is loaded, -EOPNOTSUPP if the\n+ * loaded one cannot be moved, and -EADDRINUSE if a guest in @net already uses\n+ * the device's CID.\n+ */\n+static int vsock_g2h_net_assign(struct net *net,\n+\t\t\t\tstruct netlink_ext_ack *extack)\n+{\n+\tconst struct vsock_transport *t;\n+\tnetns_tracker old_tracker;\n+\tstruct net *old;\n+\tint ret;\n+\n+\t/* See vsock_g2h_assign_mutex for the lock ordering. */\n+\tmutex_lock(\u0026vsock_g2h_assign_mutex);\n+\tmutex_lock(\u0026vsock_register_mutex);\n+\n+\tret = -ENODEV;\n+\tif (!transport_g2h) {\n+\t\tNL_SET_ERR_MSG(extack, \"no guest-to-host transport is loaded\");\n+\t\tgoto unlock;\n+\t}\n+\n+\tret = -EOPNOTSUPP;\n+\tif (!vsock_net_assignable(transport_g2h)) {\n+\t\tNL_SET_ERR_MSG(extack,\n+\t\t\t \"the loaded guest-to-host transport does not support namespace assignment\");\n+\t\tgoto unlock;\n+\t}\n+\n+\tif (transport_h2g \u0026\u0026 !transport_h2g-\u003ehas_remote_cid) {\n+\t\tNL_SET_ERR_MSG(extack,\n+\t\t\t \"the loaded host-to-guest transport cannot check the device's CID\");\n+\t\tgoto unlock;\n+\t}\n+\n+\tret = -EADDRINUSE;\n+\tif (transport_h2g \u0026\u0026\n+\t transport_h2g-\u003ehas_remote_cid(net,\n+\t\t\t\t\t transport_g2h-\u003eget_local_cid())) {\n+\t\tNL_SET_ERR_MSG(extack,\n+\t\t\t \"a guest in the target namespace already uses the device's CID\");\n+\t\tgoto unlock;\n+\t}\n+\n+\told = vsock_g2h_net_swap(net, \u0026old_tracker);\n+\tt = transport_g2h;\n+\n+\tmutex_unlock(\u0026vsock_register_mutex);\n+\n+\t/* See vsock_maybe_set_connected() comment about synchronizing with\n+\t * connecting sockets.\n+\t */\n+\tvsock_g2h_reset_unreachable(t);\n+\n+\tmutex_unlock(\u0026vsock_g2h_assign_mutex);\n+\n+\tvsock_g2h_net_release(old, \u0026old_tracker);\n+\n+\treturn 0;\n+\n+unlock:\n+\tmutex_unlock(\u0026vsock_register_mutex);\n+\tmutex_unlock(\u0026vsock_g2h_assign_mutex);\n+\n+\treturn ret;\n+}\n+\n static struct sock *vsock_dequeue_accept(struct sock *listener)\n {\n \tstruct vsock_sock *vlistener;\n@@ -908,7 +1301,8 @@ static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)\n \t * like AF_INET prevents binding to a non-local IP address (in most\n \t * cases), we only allow binding to a local CID.\n \t */\n-\tif (addr-\u003esvm_cid != VMADDR_CID_ANY \u0026\u0026 !vsock_find_cid(addr-\u003esvm_cid))\n+\tif (addr-\u003esvm_cid != VMADDR_CID_ANY \u0026\u0026\n+\t !vsock_find_cid(sock_net(sk_vsock(vsk)), addr-\u003esvm_cid))\n \t\treturn -EADDRNOTAVAIL;\n \n \tswitch (sk-\u003esk_socket-\u003etype) {\n@@ -1703,6 +2097,16 @@ static void vsock_connect_timeout(struct work_struct *work)\n \tsock_put(sk);\n }\n \n+/* Avoid breaking the socket when another thread has changed its sock-\u003estate\n+ * while we were asleep.\n+ */\n+static void vsock_connect_close(struct socket *sock)\n+{\n+\tsock-\u003esk-\u003esk_state = TCP_CLOSE;\n+\tif (sock-\u003estate == SS_CONNECTING)\n+\t\tsock-\u003estate = SS_UNCONNECTED;\n+}\n+\n static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,\n \t\t\t int addr_len, int flags)\n {\n@@ -1861,8 +2265,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,\n \t\t\t * sk_state == TCP_SYN_SENT, which hereby we break.\n \t\t\t * In such case VIRTIO_VSOCK_OP_RST will follow.\n \t\t\t */\n-\t\t\tsk-\u003esk_state = TCP_CLOSE;\n-\t\t\tsock-\u003estate = SS_UNCONNECTED;\n+\t\t\tvsock_connect_close(sock);\n \n \t\t\t/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by\n \t\t\t * transport-\u003econnect().\n@@ -1876,10 +2279,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,\n \t}\n \n \terr = sock_error(sk);\n-\tif (err) {\n-\t\tsk-\u003esk_state = TCP_CLOSE;\n-\t\tsock-\u003estate = SS_UNCONNECTED;\n-\t}\n+\tif (err)\n+\t\tvsock_connect_close(sock);\n \n out_wait:\n \tfinish_wait(sk_sleep(sk), \u0026wait);\n@@ -2795,6 +3196,7 @@ static long vsock_dev_do_ioctl(struct file *filp,\n \t\t\t unsigned int cmd, void __user *ptr)\n {\n \tu32 __user *p = ptr;\n+\tstruct net *net;\n \tint retval = 0;\n \tu32 cid;\n \n@@ -2803,11 +3205,14 @@ static long vsock_dev_do_ioctl(struct file *filp,\n \t\t/* To be compatible with the VMCI behavior, we prioritize the\n \t\t * guest CID instead of well-know host CID (VMADDR_CID_HOST).\n \t\t */\n-\t\tcid = vsock_registered_transport_cid(\u0026transport_g2h);\n+\t\tnet = current-\u003ensproxy-\u003enet_ns;\n+\t\tcid = vsock_registered_transport_cid(\u0026transport_g2h, net);\n \t\tif (cid == VMADDR_CID_ANY)\n-\t\t\tcid = vsock_registered_transport_cid(\u0026transport_h2g);\n+\t\t\tcid = vsock_registered_transport_cid(\u0026transport_h2g,\n+\t\t\t\t\t\t\t net);\n \t\tif (cid == VMADDR_CID_ANY)\n-\t\t\tcid = vsock_registered_transport_cid(\u0026transport_local);\n+\t\t\tcid = vsock_registered_transport_cid(\u0026transport_local,\n+\t\t\t\t\t\t\t net);\n \n \t\tif (put_user(cid, p) != 0)\n \t\t\tretval = -EFAULT;\n@@ -2848,6 +3253,63 @@ static struct miscdevice vsock_device = {\n \t.fops\t\t= \u0026vsock_device_ops,\n };\n \n+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info)\n+{\n+\tstruct sk_buff *msg;\n+\tint err;\n+\n+\tmsg = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);\n+\tif (!msg)\n+\t\treturn -ENOMEM;\n+\n+\tmutex_lock(\u0026vsock_register_mutex);\n+\tif (transport_g2h) {\n+\t\terr = vsock_nl_dev_netns_fill(msg, info);\n+\t} else {\n+\t\tNL_SET_ERR_MSG(info-\u003eextack,\n+\t\t\t \"no guest-to-host transport is loaded\");\n+\t\terr = -ENODEV;\n+\t}\n+\tmutex_unlock(\u0026vsock_register_mutex);\n+\n+\tif (err) {\n+\t\tnlmsg_free(msg);\n+\t\treturn err;\n+\t}\n+\n+\treturn genlmsg_reply(msg, info);\n+}\n+\n+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info)\n+{\n+\tstruct nlattr *pid_attr = info-\u003eattrs[VSOCK_A_NETNS_PID];\n+\tstruct nlattr *fd_attr = info-\u003eattrs[VSOCK_A_NETNS_FD];\n+\tstruct net *net;\n+\tint err;\n+\n+\tif (fd_attr \u0026\u0026 pid_attr) {\n+\t\tNL_SET_ERR_MSG(info-\u003eextack,\n+\t\t\t \"netns-fd and netns-pid are mutually exclusive\");\n+\t\treturn -EINVAL;\n+\t}\n+\n+\tif (fd_attr)\n+\t\tnet = get_net_ns_by_fd(nla_get_u32(fd_attr));\n+\telse if (pid_attr)\n+\t\tnet = get_net_ns_by_pid(nla_get_u32(pid_attr));\n+\telse\n+\t\tnet = get_net(genl_info_net(info));\n+\tif (IS_ERR(net)) {\n+\t\tNL_SET_BAD_ATTR(info-\u003eextack, fd_attr ?: pid_attr);\n+\t\treturn PTR_ERR(net);\n+\t}\n+\n+\terr = vsock_g2h_net_assign(net, info-\u003eextack);\n+\tput_net(net);\n+\n+\treturn err;\n+}\n+\n static int __vsock_net_mode_string(const struct ctl_table *table, int write,\n \t\t\t\t void *buffer, size_t *lenp, loff_t *ppos,\n \t\t\t\t enum vsock_net_mode mode,\n@@ -3037,7 +3499,7 @@ static void vsock_net_init(struct net *net)\n \tnet-\u003evsock.g2h_fallback = 1;\n }\n \n-static __net_init int vsock_sysctl_init_net(struct net *net)\n+static __net_init int vsock_pernet_init(struct net *net)\n {\n \tvsock_net_init(net);\n \n@@ -3047,14 +3509,14 @@ static __net_init int vsock_sysctl_init_net(struct net *net)\n \treturn 0;\n }\n \n-static __net_exit void vsock_sysctl_exit_net(struct net *net)\n+static __net_exit void vsock_pernet_exit(struct net *net)\n {\n \tvsock_sysctl_unregister(net);\n }\n \n-static struct pernet_operations vsock_sysctl_ops = {\n-\t.init = vsock_sysctl_init_net,\n-\t.exit = vsock_sysctl_exit_net,\n+static struct pernet_operations vsock_pernet_ops = {\n+\t.init = vsock_pernet_init,\n+\t.exit = vsock_pernet_exit,\n };\n \n static int __init vsock_init(void)\n@@ -3063,6 +3525,8 @@ static int __init vsock_init(void)\n \n \tvsock_init_tables();\n \n+\tget_net_track(\u0026init_net, \u0026vsock_g2h_net_tracker, GFP_KERNEL);\n+\n \tvsock_proto.owner = THIS_MODULE;\n \tvsock_device.minor = MISC_DYNAMIC_MINOR;\n \terr = misc_register(\u0026vsock_device);\n@@ -3084,15 +3548,23 @@ static int __init vsock_init(void)\n \t\tgoto err_unregister_proto;\n \t}\n \n-\tif (register_pernet_subsys(\u0026vsock_sysctl_ops)) {\n+\tif (register_pernet_subsys(\u0026vsock_pernet_ops)) {\n \t\terr = -ENOMEM;\n \t\tgoto err_unregister_sock;\n \t}\n \n+\terr = genl_register_family(\u0026vsock_nl_family);\n+\tif (err) {\n+\t\tpr_err(\"Cannot register vsock netlink family: %d\\n\", err);\n+\t\tgoto err_unregister_pernet;\n+\t}\n+\n \tvsock_bpf_build_proto();\n \n \treturn 0;\n \n+err_unregister_pernet:\n+\tunregister_pernet_subsys(\u0026vsock_pernet_ops);\n err_unregister_sock:\n \tsock_unregister(AF_VSOCK);\n err_unregister_proto:\n@@ -3100,15 +3572,20 @@ static int __init vsock_init(void)\n err_deregister_misc:\n \tmisc_deregister(\u0026vsock_device);\n err_reset_transport:\n+\tput_net_track(\u0026init_net, \u0026vsock_g2h_net_tracker);\n \treturn err;\n }\n \n static void __exit vsock_exit(void)\n {\n+\tgenl_unregister_family(\u0026vsock_nl_family);\n \tmisc_deregister(\u0026vsock_device);\n \tsock_unregister(AF_VSOCK);\n \tproto_unregister(\u0026vsock_proto);\n-\tunregister_pernet_subsys(\u0026vsock_sysctl_ops);\n+\tunregister_pernet_subsys(\u0026vsock_pernet_ops);\n+\n+\tput_net_track(rcu_dereference_protected(vsock_g2h_net, true),\n+\t\t \u0026vsock_g2h_net_tracker);\n }\n \n const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)\n@@ -3175,13 +3652,18 @@ EXPORT_SYMBOL_GPL(vsock_core_register);\n \n void vsock_core_unregister(const struct vsock_transport *t)\n {\n+\tnetns_tracker old_tracker;\n+\tstruct net *old = NULL;\n+\n \tmutex_lock(\u0026vsock_register_mutex);\n \n \tif (transport_h2g == t)\n \t\ttransport_h2g = NULL;\n \n-\tif (transport_g2h == t)\n+\tif (transport_g2h == t) {\n \t\ttransport_g2h = NULL;\n+\t\told = vsock_g2h_net_swap(\u0026init_net, \u0026old_tracker);\n+\t}\n \n \tif (transport_dgram == t)\n \t\ttransport_dgram = NULL;\n@@ -3190,6 +3672,10 @@ void vsock_core_unregister(const struct vsock_transport *t)\n \t\ttransport_local = NULL;\n \n \tmutex_unlock(\u0026vsock_register_mutex);\n+\n+\t/* The device is gone, so release the namespace it was holding. */\n+\tif (old)\n+\t\tvsock_g2h_net_release(old, \u0026old_tracker);\n }\n EXPORT_SYMBOL_GPL(vsock_core_unregister);\n \ndiff --git a/net/vmw_vsock/virtio_transport.c b/net/vmw_vsock/virtio_transport.c\nindex 4f9aa9c4c3aa59..4123924536dd64 100644\n--- a/net/vmw_vsock/virtio_transport.c\n+++ b/net/vmw_vsock/virtio_transport.c\n@@ -542,13 +542,13 @@ static bool virtio_transport_msgzerocopy_allow(void)\n \n bool virtio_transport_stream_allow(struct vsock_sock *vsk, u32 cid, u32 port)\n {\n-\treturn vsock_net_mode_global(vsk);\n+\treturn vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));\n }\n \n static bool virtio_transport_seqpacket_allow(struct vsock_sock *vsk,\n \t\t\t\t\t u32 remote_cid);\n \n-static bool virtio_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)\n+static bool virtio_transport_has_remote_cid(struct net *net, u32 cid)\n {\n \t/* The CID could be implemented by the host. Always assume it is. */\n \treturn true;\n@@ -587,6 +587,7 @@ static struct virtio_transport virtio_transport = {\n \t\t.seqpacket_has_data = virtio_transport_seqpacket_has_data,\n \n \t\t.msgzerocopy_allow = virtio_transport_msgzerocopy_allow,\n+\t\t.netns_assign_allow = true,\n \n \t\t.notify_poll_in = virtio_transport_notify_poll_in,\n \t\t.notify_poll_out = virtio_transport_notify_poll_out,\n@@ -616,7 +617,7 @@ virtio_transport_seqpacket_allow(struct vsock_sock *vsk, u32 remote_cid)\n \tstruct virtio_vsock *vsock;\n \tbool seqpacket_allow;\n \n-\tif (!vsock_net_mode_global(vsk))\n+\tif (!vsock_g2h_net_reachable(sock_net(sk_vsock(vsk))))\n \t\treturn false;\n \n \tseqpacket_allow = false;\n@@ -633,7 +634,12 @@ static void virtio_transport_rx_work(struct work_struct *work)\n {\n \tstruct virtio_vsock *vsock =\n \t\tcontainer_of(work, struct virtio_vsock, rx_work);\n+\tstruct virtio_transport *t = \u0026virtio_transport;\n+\tnetns_tracker ns_tracker;\n \tstruct virtqueue *vq;\n+\tstruct net *net;\n+\n+\tnet = vsock_g2h_net_get(\u0026ns_tracker);\n \n \tmutex_lock(\u0026vsock-\u003erx_lock);\n \n@@ -682,10 +688,15 @@ static void virtio_transport_rx_work(struct work_struct *work)\n \n \t\t\tvirtio_transport_deliver_tap_pkt(skb);\n \n-\t\t\t/* Force virtio-transport into global mode since it\n-\t\t\t * does not yet support local-mode namespacing.\n+\t\t\t/* Only grab a reference if the net changes underneath\n+\t\t\t * us.\n \t\t\t */\n-\t\t\tvirtio_transport_recv_pkt(\u0026virtio_transport, skb, NULL);\n+\t\t\tif (unlikely(!vsock_g2h_net_eq(net))) {\n+\t\t\t\tput_net_track(net, \u0026ns_tracker);\n+\t\t\t\tnet = vsock_g2h_net_get(\u0026ns_tracker);\n+\t\t\t}\n+\n+\t\t\tvirtio_transport_recv_pkt(t, skb, net);\n \t\t}\n \t} while (!virtqueue_enable_cb(vq));\n \n@@ -694,6 +705,8 @@ static void virtio_transport_rx_work(struct work_struct *work)\n \t\tvirtio_vsock_rx_fill(vsock);\n out_nofill:\n \tmutex_unlock(\u0026vsock-\u003erx_lock);\n+\n+\tput_net_track(net, \u0026ns_tracker);\n }\n \n static int virtio_vsock_vqs_init(struct virtio_vsock *vsock)\ndiff --git a/net/vmw_vsock/virtio_transport_common.c b/net/vmw_vsock/virtio_transport_common.c\nindex 1e762a480df490..c1cbe834e4f59d 100644\n--- a/net/vmw_vsock/virtio_transport_common.c\n+++ b/net/vmw_vsock/virtio_transport_common.c\n@@ -295,6 +295,9 @@ static struct sk_buff *virtio_transport_alloc_skb(struct virtio_vsock_pkt_info *\n * since a socket assigned to a transport is required.\n *\n * Do not use on listener sockets!\n+ *\n+ * This checks that the socket can reach the g2h device, so device-only replies\n+ * such as virtio_transport_reset_no_sock() must keep not using this path.\n */\n static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,\n \t\t\t\t\t struct virtio_vsock_pkt_info *info)\n@@ -317,6 +320,9 @@ static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,\n \tif (unlikely(!t_ops))\n \t\treturn -EFAULT;\n \n+\tif (!vsock_g2h_reachable_sk(vsk))\n+\t\treturn -ENETUNREACH;\n+\n \tsrc_cid = t_ops-\u003etransport.get_local_cid();\n \tsrc_port = vsk-\u003elocal_addr.svm_port;\n \tif (!info-\u003eremote_cid) {\n@@ -1468,8 +1474,8 @@ void virtio_transport_release(struct vsock_sock *vsk)\n EXPORT_SYMBOL_GPL(virtio_transport_release);\n \n static int\n-virtio_transport_recv_connecting(struct sock *sk,\n-\t\t\t\t struct sk_buff *skb)\n+virtio_transport_recv_connecting(struct sock *sk, struct sk_buff *skb,\n+\t\t\t\t struct virtio_transport *t)\n {\n \tstruct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);\n \tstruct vsock_sock *vsk = vsock_sk(sk);\n@@ -1478,9 +1484,18 @@ virtio_transport_recv_connecting(struct sock *sk,\n \n \tswitch (le16_to_cpu(hdr-\u003eop)) {\n \tcase VIRTIO_VSOCK_OP_RESPONSE:\n-\t\tsk-\u003esk_state = TCP_ESTABLISHED;\n+\t\tif (!vsock_maybe_set_connected(vsk)) {\n+\t\t\t/* The net arg is required but unused: only g2h can fail\n+\t\t\t * vsock_maybe_set_connected(), and g2h\n+\t\t\t * virtio_transport_reset_no_sock() ignores the net arg.\n+\t\t\t */\n+\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n+\t\t\tskerr = ECONNRESET;\n+\t\t\terr = -ENETUNREACH;\n+\t\t\tgoto close;\n+\t\t}\n+\n \t\tsk-\u003esk_socket-\u003estate = SS_CONNECTED;\n-\t\tvsock_insert_connected(vsk);\n \t\tsk-\u003esk_state_change(sk);\n \t\tbreak;\n \tcase VIRTIO_VSOCK_OP_INVALID:\n@@ -1498,6 +1513,7 @@ virtio_transport_recv_connecting(struct sock *sk,\n \n destroy:\n \tvirtio_transport_reset(vsk, skb);\n+close:\n \tsk-\u003esk_state = TCP_CLOSE;\n \tsk-\u003esk_err = skerr;\n \tsk_error_report(sk);\n@@ -1736,8 +1752,6 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,\n \n \tlock_sock_nested(child, SINGLE_DEPTH_NESTING);\n \n-\tchild-\u003esk_state = TCP_ESTABLISHED;\n-\n \tvchild = vsock_sk(child);\n \tvsock_addr_init(\u0026vchild-\u003elocal_addr, le64_to_cpu(hdr-\u003edst_cid),\n \t\t\tle32_to_cpu(hdr-\u003edst_port));\n@@ -1758,7 +1772,14 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,\n \tif (virtio_transport_space_update(child, skb))\n \t\tchild-\u003esk_write_space(child);\n \n-\tvsock_insert_connected(vchild);\n+\tif (!vsock_maybe_set_connected(vchild)) {\n+\t\trelease_sock(child);\n+\t\t/* Only reached for g2h, whose send_pkt() ignores the netns. */\n+\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n+\t\tsock_put(child);\n+\t\treturn -ENETUNREACH;\n+\t}\n+\n \tvsock_enqueue_accept(sk, child);\n \tvirtio_transport_send_response(vchild, skb);\n \n@@ -1859,7 +1880,7 @@ void virtio_transport_recv_pkt(struct virtio_transport *t,\n \t\tkfree_skb(skb);\n \t\tbreak;\n \tcase TCP_SYN_SENT:\n-\t\tvirtio_transport_recv_connecting(sk, skb);\n+\t\tvirtio_transport_recv_connecting(sk, skb, t);\n \t\tkfree_skb(skb);\n \t\tbreak;\n \tcase TCP_ESTABLISHED:\ndiff --git a/net/vmw_vsock/vsock_nl_gen.c b/net/vmw_vsock/vsock_nl_gen.c\nnew file mode 100644\nindex 00000000000000..18f3d47e723d4c\n--- /dev/null\n+++ b/net/vmw_vsock/vsock_nl_gen.c\n@@ -0,0 +1,44 @@\n+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)\n+/* Do not edit directly, auto-generated from: */\n+/*\tDocumentation/netlink/specs/vsock.yaml */\n+/* YNL-GEN kernel source */\n+/* To regenerate run: tools/net/ynl/ynl-regen.sh */\n+\n+#include \u003cnet/netlink.h\u003e\n+#include \u003cnet/genetlink.h\u003e\n+\n+#include \"vsock_nl_gen.h\"\n+\n+#include \u003cuapi/linux/vsock_netlink.h\u003e\n+\n+/* VSOCK_CMD_DEV_NETNS_SET - do */\n+static const struct nla_policy vsock_dev_netns_set_nl_policy[VSOCK_A_NETNS_PID + 1] = {\n+\t[VSOCK_A_NETNS_FD] = { .type = NLA_U32, },\n+\t[VSOCK_A_NETNS_PID] = { .type = NLA_U32, },\n+};\n+\n+/* Ops table for vsock */\n+static const struct genl_split_ops vsock_nl_ops[] = {\n+\t{\n+\t\t.cmd\t\t= VSOCK_CMD_DEV_NETNS_SET,\n+\t\t.doit\t\t= vsock_nl_dev_netns_set_doit,\n+\t\t.policy\t\t= vsock_dev_netns_set_nl_policy,\n+\t\t.maxattr\t= VSOCK_A_NETNS_PID,\n+\t\t.flags\t\t= GENL_ADMIN_PERM | GENL_CMD_CAP_DO,\n+\t},\n+\t{\n+\t\t.cmd\t= VSOCK_CMD_DEV_NETNS_GET,\n+\t\t.doit\t= vsock_nl_dev_netns_get_doit,\n+\t\t.flags\t= GENL_CMD_CAP_DO,\n+\t},\n+};\n+\n+struct genl_family vsock_nl_family __ro_after_init = {\n+\t.name\t\t= VSOCK_FAMILY_NAME,\n+\t.version\t= VSOCK_FAMILY_VERSION,\n+\t.netnsok\t= true,\n+\t.parallel_ops\t= true,\n+\t.module\t\t= THIS_MODULE,\n+\t.split_ops\t= vsock_nl_ops,\n+\t.n_split_ops\t= ARRAY_SIZE(vsock_nl_ops),\n+};\ndiff --git a/net/vmw_vsock/vsock_nl_gen.h b/net/vmw_vsock/vsock_nl_gen.h\nnew file mode 100644\nindex 00000000000000..a2fd87344581af\n--- /dev/null\n+++ b/net/vmw_vsock/vsock_nl_gen.h\n@@ -0,0 +1,20 @@\n+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */\n+/* Do not edit directly, auto-generated from: */\n+/*\tDocumentation/netlink/specs/vsock.yaml */\n+/* YNL-GEN kernel header */\n+/* To regenerate run: tools/net/ynl/ynl-regen.sh */\n+\n+#ifndef _LINUX_VSOCK_GEN_H\n+#define _LINUX_VSOCK_GEN_H\n+\n+#include \u003cnet/netlink.h\u003e\n+#include \u003cnet/genetlink.h\u003e\n+\n+#include \u003cuapi/linux/vsock_netlink.h\u003e\n+\n+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info);\n+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info);\n+\n+extern struct genl_family vsock_nl_family;\n+\n+#endif /* _LINUX_VSOCK_GEN_H */\ndiff --git a/tools/net/ynl/Makefile.deps b/tools/net/ynl/Makefile.deps\nindex 3eee34e0efcf9c..cd1450f1cac055 100644\n--- a/tools/net/ynl/Makefile.deps\n+++ b/tools/net/ynl/Makefile.deps\n@@ -62,4 +62,5 @@ CFLAGS_tc:= $(call get_hdr_inc,__LINUX_RTNETLINK_H,rtnetlink.h) \\\n \t$(call get_hdr_inc,_TC_SKBEDIT_H,tc_act/tc_skbedit.h) \\\n \t$(call get_hdr_inc,_TC_TUNNEL_KEY_H,tc_act/tc_tunnel_key.h)\n CFLAGS_tcp_metrics:=$(call get_hdr_inc,_LINUX_TCP_METRICS_H,tcp_metrics.h)\n+CFLAGS_vsock:=$(call get_hdr_inc,_LINUX_VSOCK_NETLINK_H,vsock_netlink.h)\n CFLAGS_wireguard:=$(call get_hdr_inc2,_LINUX_WIREGUARD_H,_WG_UAPI_WIREGUARD_H,wireguard.h)\ndiff --git a/tools/testing/selftests/vsock/Makefile b/tools/testing/selftests/vsock/Makefile\nindex c407c0afd9388e..2b066ba91bcd78 100644\n--- a/tools/testing/selftests/vsock/Makefile\n+++ b/tools/testing/selftests/vsock/Makefile\n@@ -13,5 +13,10 @@ $(VSOCK_TEST_DIR)/vsock_test: $(VSOCK_TEST_SRCS)\n TEST_PROGS += vmtest.sh\n TEST_GEN_FILES := vsock_test\n \n+TEST_FILES := \\\n+\t../../../net/ynl/pyynl/cli.py \\\n+\t../../../net/ynl/pyynl/lib \\\n+\t../../../../Documentation/netlink/specs/vsock.yaml\n+\n include ../lib.mk\n \ndiff --git a/tools/testing/selftests/vsock/config b/tools/testing/selftests/vsock/config\nindex 5f0a4f17dfc96c..4b31085558faae 100644\n--- a/tools/testing/selftests/vsock/config\n+++ b/tools/testing/selftests/vsock/config\n@@ -109,3 +109,4 @@ CONFIG_FS_DAX=y\n CONFIG_MEMORY_HOTPLUG=y\n CONFIG_MEMORY_HOTREMOVE=y\n CONFIG_ZONE_DEVICE=y\n+CONFIG_USER_NS=y\ndiff --git a/tools/testing/selftests/vsock/vmtest.sh b/tools/testing/selftests/vsock/vmtest.sh\nindex 310dfc2a39ad57..9614532a56285f 100755\n--- a/tools/testing/selftests/vsock/vmtest.sh\n+++ b/tools/testing/selftests/vsock/vmtest.sh\n@@ -17,6 +17,20 @@ readonly KERNEL_CHECKOUT=$(realpath \"${SCRIPT_DIR}\"/../../../../)\n source \"${SCRIPT_DIR}\"/../kselftest/ktap_helpers.sh\n \n readonly VSOCK_TEST=\"${SCRIPT_DIR}\"/vsock_test\n+\n+# \"make install\" copies the ynl CLI, its lib package and the spec next to this\n+# script (see TEST_FILES); in a source tree they stay where they are built.\n+if [[ -r \"${SCRIPT_DIR}\"/cli.py ]]; then\n+\treadonly YNL_CLI=\"${SCRIPT_DIR}\"/cli.py\n+\treadonly YNL_LIB=\"${SCRIPT_DIR}\"/lib\n+\treadonly VSOCK_SPEC=\"${SCRIPT_DIR}\"/vsock.yaml\n+else\n+\treadonly YNL_DIR=\"${KERNEL_CHECKOUT}\"/tools/net/ynl/pyynl\n+\treadonly YNL_CLI=\"${YNL_DIR}\"/cli.py\n+\treadonly YNL_LIB=\"${YNL_DIR}\"/lib\n+\treadonly SPEC_DIR=\"${KERNEL_CHECKOUT}\"/Documentation/netlink/specs\n+\treadonly VSOCK_SPEC=\"${SPEC_DIR}\"/vsock.yaml\n+fi\n readonly TEST_GUEST_PORT=51000\n readonly TEST_HOST_PORT=50000\n readonly TEST_HOST_PORT_LISTENER=50001\n@@ -73,6 +87,15 @@ readonly TEST_NAMES=(\n \tns_delete_vm_ok\n \tns_delete_host_ok\n \tns_delete_both_ok\n+\tns_guest_local_connect_to_host_fails\n+\tns_guest_assign_g2h_netns_connect_to_host_ok\n+\tns_guest_assign_g2h_netns_by_pid_ok\n+\tns_guest_assign_g2h_netns_init_ns_connect_fails\n+\tns_guest_assign_g2h_netns_host_connect_ok\n+\tns_guest_assign_g2h_netns_pins_ns_ok\n+\tns_guest_assign_g2h_netns_old_conn_send_fails\n+\tns_guest_assign_g2h_netns_no_cap_net_admin_fails\n+\tns_guest_assign_g2h_netns_unpriv_user_ns_fails\n )\n readonly TEST_DESCS=(\n \t# vm_server_host_client\n@@ -149,12 +172,48 @@ readonly TEST_DESCS=(\n \n \t# ns_delete_both_ok\n \t\"Check that deleting the VM and host's namespaces does not break the socket connection\"\n+\n+\t# ns_guest_local_connect_to_host_fails\n+\t\"Check a guest process in a local ns cannot reach the host without the netns assign.\"\n+\n+\t# ns_guest_assign_g2h_netns_connect_to_host_ok\n+\t\"Check a guest process in a local ns reaches the host once the vsock device is assigned to it.\"\n+\n+\t# ns_guest_assign_g2h_netns_by_pid_ok\n+\t\"Check the vsock device can be assigned to a ns given by PID from outside it.\"\n+\n+\t# ns_guest_assign_g2h_netns_init_ns_connect_fails\n+\t\"Check the guest's initial ns loses vsock once the device is assigned to another ns.\"\n+\n+\t# ns_guest_assign_g2h_netns_host_connect_ok\n+\t\"Check the host reaches a guest listener in the ns the vsock device is assigned to.\"\n+\n+\t# ns_guest_assign_g2h_netns_pins_ns_ok\n+\t\"Check the assignment keeps the ns alive when deleted, and that reassigning releases it.\"\n+\n+\t# ns_guest_assign_g2h_netns_old_conn_send_fails\n+\t\"Check connections made before the assign stop sending once they lose the device.\"\n+\n+\t# ns_guest_assign_g2h_netns_no_cap_net_admin_fails\n+\t\"Check assigning the guest's vsock device to a namespace needs CAP_NET_ADMIN.\"\n+\n+\t# ns_guest_assign_g2h_netns_unpriv_user_ns_fails\n+\t\"Check an unprivileged user cannot claim the guest's vsock device via a user ns.\"\n )\n \n readonly USE_SHARED_VM=(\n \tvm_server_host_client\n \tvm_client_host_server\n \tvm_loopback\n+\tns_guest_local_connect_to_host_fails\n+\tns_guest_assign_g2h_netns_connect_to_host_ok\n+\tns_guest_assign_g2h_netns_by_pid_ok\n+\tns_guest_assign_g2h_netns_init_ns_connect_fails\n+\tns_guest_assign_g2h_netns_host_connect_ok\n+\tns_guest_assign_g2h_netns_pins_ns_ok\n+\tns_guest_assign_g2h_netns_old_conn_send_fails\n+\tns_guest_assign_g2h_netns_no_cap_net_admin_fails\n+\tns_guest_assign_g2h_netns_unpriv_user_ns_fails\n )\n readonly NS_MODES=(\"local\" \"global\")\n \n@@ -316,6 +375,43 @@ check_deps() {\n \tfi\n }\n \n+check_ns_guest_deps() {\n+\tlocal tname=$1\n+\tlocal deps=\"unshare python3\"\n+\tlocal dep\n+\n+\tif [[ ! \"${tname}\" =~ ^ns_guest_ ]]; then\n+\t\treturn 0\n+\tfi\n+\n+\t# test-specific guest dep checks\n+\tcase \"${tname}\" in\n+\tns_guest_assign_g2h_netns_no_cap_net_admin_fails | \\\n+\tns_guest_assign_g2h_netns_unpriv_user_ns_fails)\n+\t\tdeps=\"${deps} setpriv\"\n+\t\t;;\n+\tesac\n+\n+\tfor dep in ${deps}; do\n+\t\tif [[ ! -x $(command -v \"${dep}\") ]]; then\n+\t\t\tlog_host \"no ${dep} for test ${tname}\"\n+\t\t\treturn 1\n+\t\tfi\n+\tdone\n+\n+\tif ! python3 -c \"import yaml\" \u0026\u003e/dev/null; then\n+\t\tlog_host \"no python3 yaml module for test ${tname}\"\n+\t\treturn 1\n+\tfi\n+\n+\tif [[ ! -r \"${YNL_CLI}\" ]] || [[ ! -r \"${VSOCK_SPEC}\" ]]; then\n+\t\tlog_host \"no ynl cli or vsock spec for test ${tname}\"\n+\t\treturn 1\n+\tfi\n+\n+\treturn 0\n+}\n+\n check_netns() {\n \tlocal tname=$1\n \n@@ -401,6 +497,19 @@ setup_home() {\n \tmkdir -p \"$(dirname \"${SSH_KEY_PATH}\")\"\n \tssh-keygen -t ed25519 -f \"${SSH_KEY_PATH}\" -N \"\" -q\n \tcp \"${VSOCK_TEST}\" \"${TEST_HOME}\"/vsock_test\n+\n+\tmkdir -p \"${TEST_HOME}\"/ynl\n+\tif [[ -r \"${YNL_CLI}\" ]]; then\n+\t\tcp \"${YNL_CLI}\" \"${TEST_HOME}\"/ynl/\n+\t\tcp -r \"${YNL_LIB}\" \"${TEST_HOME}\"/ynl/\n+\t\tcp \"${VSOCK_SPEC}\" \"${TEST_HOME}\"/ynl/\n+\tfi\n+\n+\t# One of the tests runs the CLI as an unprivileged user, so the CLI\n+\t# has to be reachable by one.\n+\tchmod -R a+rX \"${TEST_HOME}\"/ynl\n+\n+\tchmod 755 \"${TEST_HOME}\"\n }\n \n create_pidfile() {\n@@ -528,6 +637,82 @@ vm_wait_for_ssh() {\n \tdone\n }\n \n+# Create a local mode namespace in the VM and echo the pid holding it open.\n+vm_ns_start() {\n+\tlocal ns=$1\n+\tlocal initns\n+\tlocal nspid\n+\tlocal newns\n+\tlocal i\n+\n+\tlocal mode=/proc/sys/net/vsock/child_ns_mode\n+\n+\tif ! vm_ssh \"${ns}\" -- \"echo local \u003e ${mode}\" \u0026\u003e/dev/null; then\n+\t\treturn\n+\tfi\n+\n+\tnspid=$(vm_ssh \"${ns}\" -- \"unshare -n sleep infinity\" \\\n+\t\t'\u003e/dev/null 2\u003e\u00261 \u0026 echo $!')\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\treturn\n+\tfi\n+\n+\tinitns=$(vm_ssh \"${ns}\" -- \"readlink /proc/self/ns/net\")\n+\tfor ((i = 0; i \u003c WAIT_PERIOD_MAX; i++)); do\n+\t\tnewns=$(vm_ssh \"${ns}\" -- \"readlink /proc/${nspid}/ns/net\" \\\n+\t\t\t2\u003e/dev/null)\n+\t\tif [[ -n \"${newns}\" ]] \u0026\u0026 [[ \"${newns}\" != \"${initns}\" ]]; then\n+\t\t\techo \"${nspid}\"\n+\t\t\treturn\n+\t\tfi\n+\t\tsleep 1\n+\tdone\n+\n+\tvm_ns_stop \"${ns}\" \"${nspid}\"\n+}\n+\n+# Returns once the holder is gone, so that the namespace is unreferenced and\n+# the kernel can start tearing it down.\n+vm_ns_stop() {\n+\tlocal ns=$1\n+\tlocal nspid=$2\n+\n+\tvm_ssh \"${ns}\" \u003c\u003c-EOF \u0026\u003e/dev/null\n+\t\tkill ${nspid}\n+\t\tfor ((i = 0; i \u003c ${WAIT_PERIOD_MAX}; i++)); do\n+\t\t\tkill -0 ${nspid} 2\u003e/dev/null || break\n+\t\t\tsleep 1\n+\t\tdone\n+\tEOF\n+}\n+\n+# Runs in the guest's initial namespace when \u003cnspid\u003e is empty. The command must\n+# not contain single quotes.\n+vm_ns_exec() {\n+\tlocal ns=$1\n+\tlocal nspid=$2\n+\tlocal cmd=$3\n+\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tvm_ssh \"${ns}\" -- \"${cmd}\"\n+\t\treturn\n+\tfi\n+\n+\tvm_ssh \"${ns}\" -- nsenter -t \"${nspid}\" -n sh -c \"'${cmd}'\"\n+}\n+\n+vm_ns_assign_g2h() {\n+\tlocal ns=$1\n+\tlocal nspid=$2\n+\n+\tvm_ns_exec \"${ns}\" \"${nspid}\" \"python3 /root/ynl/cli.py --no-schema \\\n+\t\t--spec /root/ynl/vsock.yaml --do dev-netns-set\"\n+}\n+\n+vm_reset_g2h() {\n+\tvm_ns_assign_g2h \"init_ns\" \"\" \u0026\u003e/dev/null\n+}\n+\n # derived from selftests/net/net_helper.sh\n wait_for_listener()\n {\n@@ -564,17 +749,33 @@ wait_for_listener()\n \tdone\n }\n \n-vm_wait_for_listener() {\n+# Runs in the guest's initial namespace when \u003cnspid\u003e is empty.\n+vm_ns_wait_for_listener() {\n \tlocal ns=$1\n-\tlocal port=$2\n-\tlocal protocol=$3\n+\tlocal nspid=$2\n+\tlocal port=$3\n+\tlocal protocol=$4\n+\tlocal nsenter=\n+\tlocal args\n+\n+\t[[ -n \"${nspid}\" ]] \u0026\u0026 nsenter=\"nsenter -t ${nspid} -n\"\n+\targs=\"${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}\"\n \n \tvm_ssh \"${ns}\" \u003c\u003cEOF\n $(declare -f wait_for_listener)\n-wait_for_listener ${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}\n+export -f wait_for_listener\n+${nsenter} bash -c \"wait_for_listener ${args}\"\n EOF\n }\n \n+vm_wait_for_listener() {\n+\tlocal ns=$1\n+\tlocal port=$2\n+\tlocal protocol=$3\n+\n+\tvm_ns_wait_for_listener \"${ns}\" \"\" \"${port}\" \"${protocol}\"\n+}\n+\n host_wait_for_listener() {\n \tlocal ns=$1\n \tlocal port=$2\n@@ -1421,6 +1622,392 @@ test_ns_delete_both_ok() {\n \tcheck_ns_delete_doesnt_break_connection \"both\"\n }\n \n+# Send a string from the guest to a host listener and leave what the host\n+# received in \u003coutfile\u003e.\n+guest_send_to_host() {\n+\tlocal ns=$1\n+\tlocal nspid=$2\n+\tlocal port=$3\n+\tlocal outfile=$4\n+\tlocal cmd=\"echo TEST | socat -u STDIN VSOCK-CONNECT:2:${port}\"\n+\tlocal pid\n+\n+\tsocat -u VSOCK-LISTEN:\"${port}\" STDOUT \u003e \"${outfile}\" 2\u003e/dev/null \u0026\n+\tpid=$!\n+\thost_wait_for_listener \"${ns}\" \"${port}\" \"vsock\"\n+\n+\tvm_ns_exec \"${ns}\" \"${nspid}\" \"${cmd}\" 2\u003e/dev/null\n+\n+\ttimeout \"${WAIT_PERIOD}\" \\\n+\t\tbash -c 'while [[ ! -s '\"${outfile}\"' ]]; do sleep 1; done'\n+\n+\t# Wait for the listener to actually go, or the next test binding the\n+\t# same port races it and silently reads nothing.\n+\tterminate_pids \"${pid}\"\n+\twait \"${pid}\" 2\u003e/dev/null\n+}\n+\n+# Send a string from the host to a listener in the guest and leave what the\n+# guest received in \u003coutfile\u003e.\n+host_send_to_guest() {\n+\tlocal ns=$1\n+\tlocal nspid=$2\n+\tlocal port=$3\n+\tlocal outfile=$4\n+\tlocal cmd=\"socat -u VSOCK-LISTEN:${port} STDOUT\"\n+\tlocal dst=\"VSOCK-CONNECT:${VSOCK_CID}:${port}\"\n+\tlocal pid\n+\n+\tvm_ns_exec \"${ns}\" \"${nspid}\" \"${cmd}\" \u003e \"${outfile}\" 2\u003e/dev/null \u0026\n+\tpid=$!\n+\tvm_ns_wait_for_listener \"${ns}\" \"${nspid}\" \"${port}\" \"vsock\"\n+\n+\techo TEST | socat -u STDIN \"${dst}\" 2\u003e/dev/null\n+\n+\ttimeout \"${WAIT_PERIOD}\" \\\n+\t\tbash -c 'while [[ ! -s '\"${outfile}\"' ]]; do sleep 1; done'\n+\n+\tvm_ns_exec \"${ns}\" \"${nspid}\" \\\n+\t\t\"pkill -f VSOCK-LISTEN:${port}\" \u0026\u003e/dev/null\n+\tterminate_pids \"${pid}\"\n+\twait \"${pid}\" 2\u003e/dev/null\n+}\n+\n+ns_old_conn_cleanup() {\n+\tlocal port=$1\n+\tlocal pid=$2\n+\tlocal sender=$3\n+\tlocal outfile=$4\n+\tlocal nspid=$5\n+\n+\tvm_ns_exec \"init_ns\" \"\" \"pkill -f VSOCK-CONNECT:2:${port}\" \u0026\u003e/dev/null\n+\tterminate_pids \"${pid}\" \"${sender}\"\n+\twait \"${pid}\" \"${sender}\" 2\u003e/dev/null\n+\trm -f \"${outfile}\"\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+}\n+\n+test_ns_guest_assign_g2h_netns_old_conn_send_fails() {\n+\tlocal gap=$(( WAIT_PERIOD * 3 ))\n+\tlocal port=12346\n+\tlocal elapsed\n+\tlocal started\n+\tlocal outfile\n+\tlocal result\n+\tlocal sender\n+\tlocal nspid\n+\tlocal pid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\tsocat -u VSOCK-LISTEN:\"${port}\" STDOUT \u003e \"${outfile}\" 2\u003e/dev/null \u0026\n+\tpid=$!\n+\thost_wait_for_listener \"init_ns\" \"${port}\" \"vsock\"\n+\n+\t# Send a message, wait, then send another. While waiting, assign the\n+\t# device to a namespace. Confirm the second message does not arrive.\n+\tstarted=${SECONDS}\n+\tvm_ssh \"init_ns\" -- \\\n+\t\t\"(echo FIRST; sleep ${gap}; echo SECOND) |\" \\\n+\t\t\"socat -u STDIN VSOCK-CONNECT:2:${port}\" \u0026\u003e/dev/null \u0026\n+\tsender=$!\n+\n+\ttimeout \"$(( WAIT_PERIOD * WAIT_PERIOD_MAX ))\" \\\n+\t\tbash -c 'while [[ ! -s '\"${outfile}\"' ]]; do sleep 1; done'\n+\n+\tif ! vm_ns_assign_g2h \"init_ns\" \"${nspid}\"; then\n+\t\tlog_host \"failed to assign the vsock device to the guest ns\"\n+\t\tns_old_conn_cleanup \"${port}\" \"${pid}\" \"${sender}\" \\\n+\t\t\t\"${outfile}\" \"${nspid}\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\telapsed=$(( SECONDS - started ))\n+\n+\tsleep $(( gap + WAIT_PERIOD ))\n+\n+\tresult=$(cat \"${outfile}\")\n+\tns_old_conn_cleanup \"${port}\" \"${pid}\" \"${sender}\" \\\n+\t\t\"${outfile}\" \"${nspid}\"\n+\n+\tif [[ \"${result}\" != *FIRST* ]]; then\n+\t\tlog_host \"no connection before the assign: [${result}]\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif [[ $(( elapsed + 1 )) -ge ${gap} ]]; then\n+\t\tlog_host \"connect and assign took ${elapsed}s of a ${gap}s gap\"\n+\t\treturn \"${KSFT_SKIP}\"\n+\tfi\n+\n+\tif [[ \"${result}\" == *SECOND* ]]; then\n+\t\tlog_host \"old connection still delivered after the assign\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_local_connect_to_host_fails() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\tguest_send_to_host \"init_ns\" \"${nspid}\" \"${port}\" \"${outfile}\"\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" == TEST ]]; then\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_connect_to_host_ok() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif ! vm_ns_assign_g2h \"init_ns\" \"${nspid}\"; then\n+\t\tlog_host \"failed to assign the vsock device to the guest ns\"\n+\t\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\tguest_send_to_host \"init_ns\" \"${nspid}\" \"${port}\" \"${outfile}\"\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" != TEST ]]; then\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_by_pid_ok() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif ! vm_ssh \"init_ns\" -- python3 /root/ynl/cli.py --no-schema \\\n+\t\t--spec /root/ynl/vsock.yaml --do dev-netns-set \\\n+\t\t--json \"'{\\\"netns-pid\\\": ${nspid}}'\"; then\n+\t\tlog_host \"failed to assign the vsock device by PID\"\n+\t\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\tguest_send_to_host \"init_ns\" \"${nspid}\" \"${port}\" \"${outfile}\"\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" != TEST ]]; then\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_init_ns_connect_fails() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif ! vm_ns_assign_g2h \"init_ns\" \"${nspid}\"; then\n+\t\tlog_host \"failed to assign the vsock device to the guest ns\"\n+\t\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\tguest_send_to_host \"init_ns\" \"\" \"${port}\" \"${outfile}\"\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" == TEST ]]; then\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_host_connect_ok() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif ! vm_ns_assign_g2h \"init_ns\" \"${nspid}\"; then\n+\t\tlog_host \"failed to assign the vsock device to the guest ns\"\n+\t\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\toutfile=$(mktemp)\n+\thost_send_to_guest \"init_ns\" \"${nspid}\" \"${port}\" \"${outfile}\"\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tvm_reset_g2h\n+\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" != TEST ]]; then\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_pins_ns_ok() {\n+\tlocal port=12345\n+\tlocal outfile\n+\tlocal result\n+\tlocal nspid\n+\n+\tnspid=$(vm_ns_start \"init_ns\")\n+\tif [[ -z \"${nspid}\" ]]; then\n+\t\tlog_host \"failed to create a namespace inside the guest\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif ! vm_ns_assign_g2h \"init_ns\" \"${nspid}\"; then\n+\t\tlog_host \"failed to assign the vsock device to the guest ns\"\n+\t\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tvm_ns_stop \"init_ns\" \"${nspid}\"\n+\tsleep \"${WAIT_PERIOD}\"\n+\n+\toutfile=$(mktemp)\n+\tguest_send_to_host \"init_ns\" \"\" \"${port}\" \"${outfile}\"\n+\tresult=$(cat \"${outfile}\")\n+\tif [[ \"${result}\" == TEST ]]; then\n+\t\tlog_host \"device returned to the init ns instead of pinning it\"\n+\t\trm -f \"${outfile}\"\n+\t\tvm_reset_g2h\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\t# Assigning it back is what releases the deleted namespace.\n+\tvm_reset_g2h\n+\n+\tguest_send_to_host \"init_ns\" \"\" \"$(( port + 1 ))\" \"${outfile}\"\n+\tresult=$(cat \"${outfile}\")\n+\trm -f \"${outfile}\"\n+\n+\tif [[ \"${result}\" != TEST ]]; then\n+\t\tlog_host \"device did not come back on reassign: [${result}]\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+check_assign_g2h_eperm() {\n+\tlocal wrapper=$1\n+\tlocal out\n+\n+\tif out=$(vm_ssh \"init_ns\" -- \"${wrapper}\" python3 /root/ynl/cli.py \\\n+\t\t--no-schema --spec /root/ynl/vsock.yaml \\\n+\t\t--do dev-netns-set 2\u003e\u00261); then\n+\t\tlog_host \"assign unexpectedly succeeded under '${wrapper}'\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\tif [[ \"${out}\" != *\"Operation not permitted\"* ]]; then\n+\t\tlog_host \"no EPERM under '${wrapper}': [${out}]\"\n+\t\treturn \"${KSFT_FAIL}\"\n+\tfi\n+\n+\treturn \"${KSFT_PASS}\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_no_cap_net_admin_fails() {\n+\tcheck_assign_g2h_eperm \"unshare -n setpriv --bounding-set=-net_admin\"\n+}\n+\n+test_ns_guest_assign_g2h_netns_unpriv_user_ns_fails() {\n+\tlocal unpriv_uid=65534\n+\tlocal unpriv\n+\n+\tunpriv=\"setpriv --reuid=${unpriv_uid} --regid=${unpriv_uid}\"\n+\tunpriv=\"${unpriv} --clear-groups\"\n+\n+\tif ! vm_ssh \"init_ns\" -- \"${unpriv} unshare -Urn true\"; then\n+\t\tlog_host \"unprivileged user namespaces unavailable, skipping\"\n+\t\treturn \"${KSFT_SKIP}\"\n+\tfi\n+\n+\tcheck_assign_g2h_eperm \"${unpriv} unshare -Urn\"\n+}\n+\n shared_vm_test() {\n \tlocal tname\n \n@@ -1453,7 +2040,8 @@ run_shared_vm_tests() {\n \t\t\tcontinue\n \t\tfi\n \n-\t\tif ! check_netns \"${arg}\"; then\n+\t\tif ! check_netns \"${arg}\" ||\n+\t\t ! check_ns_guest_deps \"${arg}\"; then\n \t\t\tcheck_result \"${KSFT_SKIP}\" \"${arg}\"\n \t\t\tcontinue\n \t\tfi\n@@ -1517,7 +2105,8 @@ run_ns_tests() {\n \t\t\tcontinue\n \t\tfi\n \n-\t\tif ! check_netns \"${arg}\"; then\n+\t\tif ! check_netns \"${arg}\" ||\n+\t\t ! check_ns_guest_deps \"${arg}\"; then\n \t\t\tcheck_result \"${KSFT_SKIP}\" \"${arg}\"\n \t\t\tcontinue\n \t\tfi\n"
} |
| 2/1 | 2026/11/18 10:04 | agent | patch-evaluator |
6mModel:core Args: null Results: {
"EnableConfigs": [
"VSOCKETS",
"VIRTIO_VSOCKETS",
"VHOST_VSOCK"
],
"FocusSymbols": [
"vsock_nl_dev_netns_set_doit",
"vsock_nl_dev_netns_get_doit",
"vsock_maybe_set_connected",
"vsock_g2h_net_reachable",
"vsock_g2h_reachable_sk",
"vsock_find_cid",
"__vsock_find_cid",
"vhost_vsock_set_cid",
"virtio_transport_recv_connecting",
"virtio_transport_recv_listen"
],
"Reasoning": "The patch series introduces a new Generic Netlink family (\"vsock\") allowing user space (with CAP_NET_ADMIN) to assign the guest-to-host (G2H) vsock device to different network namespaces (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET). It also modifies core AF_VSOCK socket state handling, namespace tracking and reference lifetime, CID resolution under concurrency, and virtio/vhost vsock transport connection lifecycle logic. These changes execute in reachable networking code accessible in standard virtualized environments and should be fuzzed for concurrency, state management, and refcount regressions.",
"WorthFuzzing": true
}Instruction: You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.
IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.
================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.
- REACHABILITY IS THE PRIMARY GATE:
Fuzzing can only discover bugs in code that can actually execute in standard virtualized
environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
regardless of whether it adds assertions or complex logic.
- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
Patch authors routinely label changes as "cleanups", "refactorings", or state
"No functional change intended". Do NOT take these claims at face value.
Code refactorings that rearrange logic, introduce helper functions, or alter state management
in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
If reachable executable code is modified or refactored, it MUST be fuzzed.
- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
Even if the author believes the invariant always holds, fuzzing is essential to verify whether
an unusual sequence of operations can violate it.
================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:
- Non-kernel and non-executable changes:
* Modifications to Documentation/, comments, or spelling fixes.
* User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
that do not affect the compiled kernel image (vmlinux) or kernel modules.
* Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
that do not alter control flow or data structures.
* Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
* Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
* Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
physical PCI hot-unplug or manual sysfs driver unbinding.
* Code paths exclusive to architectures other than the target architecture.
================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
* Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
* Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
* Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
* Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).
================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:
- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
Do NOT list generic, ubiquitous functions called by almost every program in the corpus
(including, but not limited to: general memory allocators and deallocators, page fault
and trap handlers, or core synchronization primitives; this is not an exhaustive list).
Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
which severely dilutes fuzzing effort away from the actual changes.
- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
List functions that specifically implement the logic being added or altered, or direct API entrypoints
for the subsystem feature under review.
- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).
================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 190eefd6dcf9994800a722359e674bd7ddd1931e
Author: syz-cluster <triage@syzkaller.com>
Date: Wed Nov 18 10:04:32 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/admin-guide/sysctl/net.rst b/Documentation/admin-guide/sysctl/net.rst
index fe43e85959583e..87bde0fe1ccfc2 100644
--- a/Documentation/admin-guide/sysctl/net.rst
+++ b/Documentation/admin-guide/sysctl/net.rst
@@ -529,6 +529,49 @@ their hosts. The behavior of VSOCK sockets in a network namespace is determined
by the namespace's mode (``global`` or ``local``), which controls how CIDs
(Context IDs) are allocated and how sockets interact across namespaces.
+In a guest, the vsock device owned by the guest-to-host (G2H) transport belongs
+to one network namespace at a time. The ``VSOCK_CMD_DEV_NETNS_SET`` command of
+the ``vsock`` netlink family, described in
+Documentation/netlink/specs/vsock.yaml, moves it to a namespace given by fd or
+PID, or else to the namespace the request was sent from. It requires
+``CAP_NET_ADMIN`` in the initial user namespace.
+The namespace's mode decides who may then use the device:
+
+- ``global`` - every ``global`` mode namespace may use it.
+- ``local`` - only that namespace may use it, which reserves the connection to
+ the host for it alone.
+
+The device starts out in init_net, so until the command is issued nothing has
+moved and no mode has changed.
+
+Support is transport dependent. A G2H transport that does not implement the
+move refuses the command with ``EOPNOTSUPP``. Of the in-tree guest transports,
+only virtio-vsock implements it.
+
+A namespace that cannot reach the device sees the vsock addresses it would see
+if no G2H transport were loaded: the device's CID is not one of its local CIDs,
+and with ``vsock_loopback`` loaded, ``VMADDR_CID_HOST`` (2) is served by
+loopback.
+
+Connections established before the move, from a namespace that can no longer
+reach the device, are closed with ``ECONNRESET``. Nothing is sent to the peer,
+which is what already happens when the device is removed altogether: the peer
+finds out on its next send, which no longer matches a socket and so is answered
+with a reset. A peer that only receives waits for its own timeout. A connection
+still being set up when the device moves is refused with a reset once the peer
+answers it.
+
+An assignment keeps the namespace alive, the same way an open socket does, so
+deleting that namespace does not move the device. Assigning the device to
+another namespace, such as init_net, is the only way to undo an assignment, and
+releases the reference the assignment held on the previous namespace.
+
+The move is refused with ``EADDRINUSE`` if a guest registered in the target
+namespace already answers to the device's CID, since the CID would otherwise
+name two different peers there. If a loaded H2G transport cannot check that,
+the move is refused with ``EOPNOTSUPP``. Of the in-tree host transports, only
+vhost-vsock can.
+
ns_mode
-------
diff --git a/Documentation/netlink/specs/vsock.yaml b/Documentation/netlink/specs/vsock.yaml
new file mode 100644
index 00000000000000..f260ee88b14024
--- /dev/null
+++ b/Documentation/netlink/specs/vsock.yaml
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+#
+# Copyright (c) 2026 Meta Platforms, Inc. and affiliates
+#
+---
+name: vsock
+
+doc: |
+ Control interface for the vsock (AF_VSOCK) core.
+
+protocol: genetlink
+
+uapi-header: linux/vsock_netlink.h
+
+attribute-sets:
+ -
+ name: vsock
+ attributes:
+ -
+ name: netns-id
+ type: s32
+ doc: |
+ Network namespace the guest's vsock device is assigned to, as an
+ nsid relative to the caller.
+
+ Absent when the device is in the caller's own namespace, and
+ NETNSA_NSID_NOT_ASSIGNED when the g2h transport supports netns
+ assignment and the caller's namespace cannot reach the device under
+ the mode rules, or when no nsid could be allocated for it.
+ -
+ name: netns-fd
+ type: u32
+ doc: |
+ File descriptor of the network namespace to move the guest's vsock
+ device to.
+ -
+ name: netns-pid
+ type: u32
+ doc: |
+ PID of a process in the network namespace to move the guest's vsock
+ device to.
+
+operations:
+ list:
+ -
+ name: dev-netns-set
+ doc: |
+ Set the network namespace of the guest's vsock device.
+
+ The device is moved to the namespace given by netns-fd or netns-pid,
+ or to the namespace the request was sent from if neither is given.
+ It starts out in init_net, and moving it back there is how an
+ assignment is undone.
+
+ A g2h transport that does not support netns assignment returns
+ EOPNOTSUPP. If the netns assignment would cause a CID collision, it
+ is rejected with EADDRINUSE.
+
+ The namespace's mode decides who may then use the device: a global
+ mode namespace shares it with every other global mode namespace,
+ while a local mode namespace reserves it for itself.
+
+ Movement to an unreachable local namespace results in sockets being
+ closed with ECONNRESET. Peers are not guaranteed to be notified via
+ an RST.
+
+ The assignment holds a reference on the namespace.
+ attribute-set: vsock
+ flags: [admin-perm]
+ do:
+ request:
+ attributes:
+ - netns-fd
+ - netns-pid
+ -
+ name: dev-netns-get
+ doc: |
+ Get the network namespace the guest's vsock device is assigned to.
+
+ The namespace is reported as an nsid relative to the caller, so the
+ attribute is absent when the device is already in the caller's own
+ namespace. If the g2h transport supports netns assignment, a caller
+ whose namespace cannot reach the device is told
+ NETNSA_NSID_NOT_ASSIGNED rather than where the device went.
+ attribute-set: vsock
+ do:
+ reply:
+ attributes:
+ - netns-id
diff --git a/MAINTAINERS b/MAINTAINERS
index 7636ab50d44fbe..95c8882669bbbb 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -29169,10 +29169,12 @@ M: Stefano Garzarella <sgarzare@redhat.com>
L: virtualization@lists.linux.dev
L: netdev@vger.kernel.org
S: Maintained
+F: Documentation/netlink/specs/vsock.yaml
F: drivers/net/vsockmon.c
F: include/net/af_vsock.h
F: include/uapi/linux/vm_sockets.h
F: include/uapi/linux/vm_sockets_diag.h
+F: include/uapi/linux/vsock_netlink.h
F: include/uapi/linux/vsockmon.h
F: net/vmw_vsock/
F: tools/testing/selftests/vsock/
diff --git a/drivers/vhost/vsock.c b/drivers/vhost/vsock.c
index abed1fbcf66cc5..1a03cff56c5aa4 100644
--- a/drivers/vhost/vsock.c
+++ b/drivers/vhost/vsock.c
@@ -91,10 +91,8 @@ static struct vhost_vsock *vhost_vsock_get(u32 guest_cid, struct net *net)
return NULL;
}
-static bool vhost_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)
+static bool vhost_transport_has_remote_cid(struct net *net, u32 cid)
{
- struct sock *sk = sk_vsock(vsk);
- struct net *net = sock_net(sk);
bool found;
rcu_read_lock();
@@ -817,6 +815,7 @@ static int vhost_vsock_dev_release(struct inode *inode, struct file *file)
static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
{
struct vhost_vsock *other;
+ int ret;
/* Refuse reserved CIDs */
if (guest_cid <= VMADDR_CID_HOST ||
@@ -830,15 +829,20 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
/* Refuse if CID is assigned to the guest->host transport (i.e. nested
* VM), to make the loopback work.
*/
- if (vsock_find_cid(guest_cid))
- return -EADDRINUSE;
+ vsock_cid_lock();
+
+ if (__vsock_find_cid(vsock->net, guest_cid)) {
+ ret = -EADDRINUSE;
+ goto unlock;
+ }
/* Refuse if CID is already in use */
mutex_lock(&vhost_vsock_mutex);
other = vhost_vsock_get(guest_cid, vsock->net);
if (other && other != vsock) {
mutex_unlock(&vhost_vsock_mutex);
- return -EADDRINUSE;
+ ret = -EADDRINUSE;
+ goto unlock;
}
if (vsock->guest_cid)
@@ -848,7 +852,12 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
hash_add_rcu(vhost_vsock_hash, &vsock->hash, vsock->guest_cid);
mutex_unlock(&vhost_vsock_mutex);
- return 0;
+ ret = 0;
+
+unlock:
+ vsock_cid_unlock();
+
+ return ret;
}
static int vhost_vsock_set_features(struct vhost_vsock *vsock, u64 features)
diff --git a/include/net/af_vsock.h b/include/net/af_vsock.h
index 5549298c1ec6b3..fa025dd754a1f4 100644
--- a/include/net/af_vsock.h
+++ b/include/net/af_vsock.h
@@ -9,6 +9,7 @@
#define __AF_VSOCK_H__
#include <linux/kernel.h>
+#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <net/netns/vsock.h>
#include <net/sock.h>
@@ -183,13 +184,16 @@ struct vsock_transport {
* CIDs via the hypervisor (i.e. supports the fallback overlay). VMCI
* does not implement this as it only serves CIDs 0 and 2.
*/
- bool (*has_remote_cid)(struct vsock_sock *vsk, u32 remote_cid);
+ bool (*has_remote_cid)(struct net *net, u32 remote_cid);
/* Read a single skb */
int (*read_skb)(struct vsock_sock *, skb_read_actor_t);
/* Zero-copy. */
bool (*msgzerocopy_allow)(void);
+
+ /* True if the G2H transport honours VSOCK_CMD_DEV_NETNS_SET. */
+ bool netns_assign_allow;
};
/**** CORE ****/
@@ -233,11 +237,20 @@ bool vsock_check_source(const struct vsock_sock *vsk,
const struct vsock_transport *transport,
const struct sockaddr_vm *src);
void vsock_remove_sock(struct vsock_sock *vsk);
-void vsock_for_each_connected_socket(struct vsock_transport *transport,
+void vsock_for_each_connected_socket(const struct vsock_transport *transport,
void (*fn)(struct sock *sk));
int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk);
-bool vsock_find_cid(unsigned int cid);
+bool vsock_find_cid(struct net *net, unsigned int cid);
+void vsock_cid_lock(void);
+void vsock_cid_unlock(void);
+/* Caller must hold vsock_cid_lock(). */
+bool __vsock_find_cid(struct net *net, unsigned int cid);
void vsock_linger(struct sock *sk);
+struct net *vsock_g2h_net_get(netns_tracker *tracker);
+bool vsock_g2h_net_eq(const struct net *net);
+bool vsock_g2h_net_reachable(struct net *net);
+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk);
+bool vsock_maybe_set_connected(struct vsock_sock *vsk);
/**** TAP ****/
diff --git a/include/uapi/linux/vsock_netlink.h b/include/uapi/linux/vsock_netlink.h
new file mode 100644
index 00000000000000..c7e23d0da17e19
--- /dev/null
+++ b/include/uapi/linux/vsock_netlink.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN uapi header */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#ifndef _UAPI_LINUX_VSOCK_NETLINK_H
+#define _UAPI_LINUX_VSOCK_NETLINK_H
+
+#define VSOCK_FAMILY_NAME "vsock"
+#define VSOCK_FAMILY_VERSION 1
+
+enum {
+ VSOCK_A_NETNS_ID = 1,
+ VSOCK_A_NETNS_FD,
+ VSOCK_A_NETNS_PID,
+
+ __VSOCK_A_MAX,
+ VSOCK_A_MAX = (__VSOCK_A_MAX - 1)
+};
+
+enum {
+ VSOCK_CMD_DEV_NETNS_SET = 1,
+ VSOCK_CMD_DEV_NETNS_GET,
+
+ __VSOCK_CMD_MAX,
+ VSOCK_CMD_MAX = (__VSOCK_CMD_MAX - 1)
+};
+
+#endif /* _UAPI_LINUX_VSOCK_NETLINK_H */
diff --git a/net/vmw_vsock/Makefile b/net/vmw_vsock/Makefile
index 5da74c4a9f1d1b..97e2a559e2bf3d 100644
--- a/net/vmw_vsock/Makefile
+++ b/net/vmw_vsock/Makefile
@@ -7,7 +7,7 @@ obj-$(CONFIG_VIRTIO_VSOCKETS_COMMON) += vmw_vsock_virtio_transport_common.o
obj-$(CONFIG_HYPERV_VSOCKETS) += hv_sock.o
obj-$(CONFIG_VSOCKETS_LOOPBACK) += vsock_loopback.o
-vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o
+vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o vsock_nl_gen.o
vsock-$(CONFIG_BPF_SYSCALL) += vsock_bpf.o
vsock_diag-y += diag.o
diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c
index 483af15a5109eb..3bc9eee8ad9daf 100644
--- a/net/vmw_vsock/af_vsock.c
+++ b/net/vmw_vsock/af_vsock.c
@@ -130,6 +130,27 @@
* a different transport that *does* support local mode. For
* example, virtio-vsock may not support local mode, but the socket
* may still accept a connection from vhost-vsock which does.
+ *
+ * - A guest has a single vsock device, owned by the guest->host transport.
+ * The VSOCK_CMD_DEV_NETNS_SET netlink command moves it to a namespace given
+ * by fd or PID, or else to the one the request was sent from. It starts
+ * out in init_net. The mode rules then decide who may use it, and which
+ * namespace packets from the host are delivered to:
+ *
+ * - assigned to a global mode namespace - every global mode namespace may
+ * use it. Until the command is issued nothing has moved and no mode has
+ * changed, so the default is the behaviour that predates it.
+ * - assigned to a local mode namespace - only that namespace may use it.
+ * This is how a nested VM is isolated from the rest of the guest.
+ *
+ * Connections made before an assignment, from a namespace that can no
+ * longer reach the device, are closed with ECONNRESET. Nothing is sent to
+ * the peer. As with device removal, it finds out on its next send.
+ *
+ * The assignment holds a reference on the namespace, the way an open socket
+ * does, so deleting that namespace does not move the device: its destruction
+ * is deferred until the device moves to another namespace, on another
+ * assignment or when the transport unregisters.
*/
#include <linux/compat.h>
@@ -161,10 +182,14 @@
#include <linux/workqueue.h>
#include <net/sock.h>
#include <net/af_vsock.h>
+#include <linux/net_namespace.h>
+#include <net/genetlink.h>
#include <net/netns/vsock.h>
#include <uapi/linux/vm_sockets.h>
#include <uapi/asm-generic/ioctls.h>
+#include "vsock_nl_gen.h"
+
#define VSOCK_NET_MODE_STR_GLOBAL "global"
#define VSOCK_NET_MODE_STR_LOCAL "local"
@@ -206,8 +231,21 @@ static const struct vsock_transport *transport_g2h;
static const struct vsock_transport *transport_dgram;
/* Transport used for local communication */
static const struct vsock_transport *transport_local;
+/* Protects transport registration and the g2h device's netns. */
static DEFINE_MUTEX(vsock_register_mutex);
+/* Network namespace of the g2h device. Protected by
+ * vsock_register_mutex/RCU.
+ */
+static struct net __rcu *vsock_g2h_net = RCU_INITIALIZER(&init_net);
+static netns_tracker vsock_g2h_net_tracker;
+
+/* Held across an assign's swap and reset sweep, so that a later assign cannot
+ * move the device back before the sweep has closed every socket that lost it.
+ * Must be taken before vsock_register_mutex.
+ */
+static DEFINE_MUTEX(vsock_g2h_assign_mutex);
+
/**** UTILS ****/
/* Each bound VSocket is stored in the bind hash table and each connected
@@ -480,7 +518,7 @@ void vsock_remove_sock(struct vsock_sock *vsk)
}
EXPORT_SYMBOL_GPL(vsock_remove_sock);
-void vsock_for_each_connected_socket(struct vsock_transport *transport,
+void vsock_for_each_connected_socket(const struct vsock_transport *transport,
void (*fn)(struct sock *sk))
{
int i;
@@ -502,6 +540,37 @@ void vsock_for_each_connected_socket(struct vsock_transport *transport,
}
EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
+/* Return the next connected socket of @transport that @match accepts, with a
+ * reference held. The scan starts at bucket *@bucket and leaves it where it
+ * stopped, so calling again resumes there. Unlike
+ * vsock_for_each_connected_socket(), the caller acts on the socket after
+ * vsock_table_lock is dropped, so it can take lock_sock().
+ */
+static struct sock *
+vsock_next_connected_socket(const struct vsock_transport *transport,
+ unsigned int *bucket,
+ bool (*match)(struct vsock_sock *vsk))
+{
+ struct vsock_sock *vsk;
+
+ spin_lock_bh(&vsock_table_lock);
+
+ for (; *bucket < ARRAY_SIZE(vsock_connected_table); (*bucket)++) {
+ list_for_each_entry(vsk, &vsock_connected_table[*bucket],
+ connected_table) {
+ if (vsk->transport == transport && match(vsk)) {
+ sock_hold(sk_vsock(vsk));
+ spin_unlock_bh(&vsock_table_lock);
+ return sk_vsock(vsk);
+ }
+ }
+ }
+
+ spin_unlock_bh(&vsock_table_lock);
+
+ return NULL;
+}
+
void vsock_add_pending(struct sock *listener, struct sock *pending)
{
struct vsock_sock *vlistener;
@@ -553,7 +622,42 @@ void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
}
EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
-static bool vsock_use_local_transport(unsigned int remote_cid)
+/* Return true if @t honours namespace assignment. One that does not keeps the
+ * reachability rules it had before VSOCK_CMD_DEV_NETNS_SET existed.
+ */
+static bool vsock_net_assignable(const struct vsock_transport *t)
+{
+ return t && t->netns_assign_allow;
+}
+
+static bool vsock_g2h_unreachable(const struct vsock_transport *t,
+ struct net *net)
+{
+ return t == transport_g2h && vsock_net_assignable(t) &&
+ !vsock_g2h_net_reachable(net);
+}
+
+/* Return the CID of the transport in @transport, as seen from @net.
+ *
+ * Returns VMADDR_CID_ANY if the transport supports net assignment but is not
+ * reachable from the net.
+ */
+static u32
+__vsock_registered_transport_cid(const struct vsock_transport **transport,
+ struct net *net)
+{
+ lockdep_assert_held(&vsock_register_mutex);
+
+ if (!*transport)
+ return VMADDR_CID_ANY;
+
+ if (vsock_g2h_unreachable(*transport, net))
+ return VMADDR_CID_ANY;
+
+ return (*transport)->get_local_cid();
+}
+
+static bool vsock_use_local_transport(struct net *net, unsigned int remote_cid)
{
lockdep_assert_held(&vsock_register_mutex);
@@ -563,11 +667,10 @@ static bool vsock_use_local_transport(unsigned int remote_cid)
if (remote_cid == VMADDR_CID_LOCAL)
return true;
- if (transport_g2h) {
+ if (transport_g2h && !vsock_g2h_unreachable(transport_g2h, net))
return remote_cid == transport_g2h->get_local_cid();
- } else {
- return remote_cid == VMADDR_CID_HOST;
- }
+
+ return remote_cid == VMADDR_CID_HOST;
}
static void vsock_deassign_transport(struct vsock_sock *vsk)
@@ -626,18 +729,20 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
break;
case SOCK_STREAM:
case SOCK_SEQPACKET:
- if (vsock_use_local_transport(remote_cid))
+ if (vsock_use_local_transport(sock_net(sk), remote_cid))
new_transport = transport_local;
else if (remote_cid <= VMADDR_CID_HOST ||
(remote_flags & VMADDR_FLAG_TO_HOST))
new_transport = transport_g2h;
else if (transport_h2g &&
(!transport_h2g->has_remote_cid ||
- transport_h2g->has_remote_cid(vsk, remote_cid)))
+ transport_h2g->has_remote_cid(sock_net(sk),
+ remote_cid)))
new_transport = transport_h2g;
else if (sock_net(sk)->vsock.g2h_fallback &&
transport_g2h && transport_g2h->has_remote_cid &&
- transport_g2h->has_remote_cid(vsk, remote_cid)) {
+ transport_g2h->has_remote_cid(sock_net(sk),
+ remote_cid)) {
vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
new_transport = transport_g2h;
} else {
@@ -649,6 +754,11 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
goto err;
}
+ if (vsock_g2h_unreachable(new_transport, sock_net(sk))) {
+ ret = -ENETUNREACH;
+ goto err;
+ }
+
if (vsk->transport && vsk->transport == new_transport) {
ret = 0;
goto err;
@@ -715,21 +825,39 @@ EXPORT_SYMBOL_GPL(vsock_assign_transport);
* Provide safe access to static transport_{h2g,g2h,dgram,local} callbacks.
* Otherwise we may race with module removal. Do not use on `vsk->transport`.
*/
-static u32 vsock_registered_transport_cid(const struct vsock_transport **transport)
+static u32
+vsock_registered_transport_cid(const struct vsock_transport **transport,
+ struct net *net)
{
- u32 cid = VMADDR_CID_ANY;
+ u32 cid;
mutex_lock(&vsock_register_mutex);
- if (*transport)
- cid = (*transport)->get_local_cid();
+ cid = __vsock_registered_transport_cid(transport, net);
mutex_unlock(&vsock_register_mutex);
return cid;
}
-bool vsock_find_cid(unsigned int cid)
+/* Keep the CIDs checked by __vsock_find_cid() stable: transport registration
+ * and g2h device netns assignment both wait for vsock_cid_unlock().
+ */
+void vsock_cid_lock(void)
+{
+ mutex_lock(&vsock_register_mutex);
+}
+EXPORT_SYMBOL_GPL(vsock_cid_lock);
+
+void vsock_cid_unlock(void)
+{
+ mutex_unlock(&vsock_register_mutex);
+}
+EXPORT_SYMBOL_GPL(vsock_cid_unlock);
+
+bool __vsock_find_cid(struct net *net, unsigned int cid)
{
- if (cid == vsock_registered_transport_cid(&transport_g2h))
+ lockdep_assert_held(&vsock_register_mutex);
+
+ if (cid == __vsock_registered_transport_cid(&transport_g2h, net))
return true;
if (transport_h2g && cid == VMADDR_CID_HOST)
@@ -740,8 +868,273 @@ bool vsock_find_cid(unsigned int cid)
return false;
}
+EXPORT_SYMBOL_GPL(__vsock_find_cid);
+
+bool vsock_find_cid(struct net *net, unsigned int cid)
+{
+ bool found;
+
+ mutex_lock(&vsock_register_mutex);
+ found = __vsock_find_cid(net, cid);
+ mutex_unlock(&vsock_register_mutex);
+
+ return found;
+}
EXPORT_SYMBOL_GPL(vsock_find_cid);
+/* Return the namespace the g2h device is assigned to, with a reference held.
+ *
+ * The assignment itself holds a reference, so the namespace cannot be going
+ * away here and this never fails.
+ */
+struct net *vsock_g2h_net_get(netns_tracker *tracker)
+{
+ struct net *net;
+
+ rcu_read_lock();
+ net = rcu_dereference(vsock_g2h_net);
+ get_net_track(net, tracker, GFP_ATOMIC);
+ rcu_read_unlock();
+
+ return net;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_get);
+
+/* True if @net is still the namespace the device is assigned to. Cheap enough
+ * to call per packet on the RX path.
+ */
+bool vsock_g2h_net_eq(const struct net *net)
+{
+ return rcu_access_pointer(vsock_g2h_net) == net;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_eq);
+
+bool vsock_g2h_net_reachable(struct net *net)
+{
+ bool reachable;
+
+ rcu_read_lock();
+ reachable = vsock_net_check_mode(net, rcu_dereference(vsock_g2h_net));
+ rcu_read_unlock();
+
+ return reachable;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_reachable);
+
+/* True if @vsk can reach the g2h device, or its transport ignores namespace
+ * assignment.
+ */
+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk)
+{
+ if (!vsock_net_assignable(vsk->transport))
+ return true;
+
+ return vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_reachable_sk);
+
+/* Move @vsk to TCP_ESTABLISHED and into the connected table, unless the device
+ * has moved to a namespace @vsk cannot reach. Returns false without doing
+ * either in that case.
+ *
+ * The reset sweep walks the same table under the same lock, so an assign
+ * cannot land between the check and the insert: either the sweep finds @vsk
+ * and closes it, or @vsk is never added.
+ */
+bool vsock_maybe_set_connected(struct vsock_sock *vsk)
+{
+ struct list_head *list;
+ bool reachable;
+
+ list = vsock_connected_sockets(&vsk->remote_addr, &vsk->local_addr);
+
+ spin_lock_bh(&vsock_table_lock);
+ reachable = vsock_g2h_reachable_sk(vsk);
+ if (reachable) {
+ sk_vsock(vsk)->sk_state = TCP_ESTABLISHED;
+ __vsock_insert_connected(list, vsk);
+ }
+ spin_unlock_bh(&vsock_table_lock);
+
+ return reachable;
+}
+EXPORT_SYMBOL_GPL(vsock_maybe_set_connected);
+
+static bool vsock_g2h_should_reset(struct vsock_sock *vsk)
+{
+ return READ_ONCE(sk_vsock(vsk)->sk_state) != TCP_CLOSE &&
+ !READ_ONCE(vsk->close_work_scheduled) &&
+ !vsock_g2h_reachable_sk(vsk);
+}
+
+/* Close every connected socket of @t that can no longer reach the g2h device.
+ */
+static void vsock_g2h_reset_unreachable(const struct vsock_transport *t)
+{
+ struct vsock_sock *vsk;
+ unsigned int i = 0;
+ struct sock *sk;
+ bool reset;
+
+ lockdep_assert_held(&vsock_g2h_assign_mutex);
+ lockdep_assert_not_held(&vsock_register_mutex);
+
+ /* lock_sock() cannot be taken under vsock_table_lock, so pick the
+ * sockets one at a time, then recheck each under both locks.
+ */
+ while ((sk = vsock_next_connected_socket(t, &i,
+ vsock_g2h_should_reset))) {
+ vsk = vsock_sk(sk);
+
+ lock_sock(sk);
+
+ reset = false;
+ spin_lock_bh(&vsock_table_lock);
+ /* It may have been closed since we dropped the table lock. */
+ if (__vsock_in_connected_table(vsk) && vsk->transport == t &&
+ vsock_g2h_should_reset(vsk)) {
+ __vsock_remove_connected(vsk);
+ reset = true;
+ }
+ spin_unlock_bh(&vsock_table_lock);
+
+ if (reset) {
+ sock_set_flag(sk, SOCK_DONE);
+ WRITE_ONCE(vsk->peer_shutdown, SHUTDOWN_MASK);
+ sk->sk_state = TCP_CLOSING;
+ sk->sk_err = ECONNRESET;
+ sk_error_report(sk);
+ }
+
+ release_sock(sk);
+ sock_put(sk);
+ }
+}
+
+/* Point the g2h device at @net, taking the reference that keeps @net alive,
+ * and return the namespace it leaves behind.
+ */
+static struct net *vsock_g2h_net_swap(struct net *net, netns_tracker *old)
+{
+ lockdep_assert_held(&vsock_register_mutex);
+
+ *old = vsock_g2h_net_tracker;
+ get_net_track(net, &vsock_g2h_net_tracker, GFP_KERNEL);
+
+ return rcu_replace_pointer(vsock_g2h_net, net,
+ lockdep_is_held(&vsock_register_mutex));
+}
+
+/* Drop the namespace the device just left, once the readers that may still
+ * see it in vsock_g2h_net_get() are gone. Runs without the mutex held.
+ */
+static void vsock_g2h_net_release(struct net *old, netns_tracker *tracker)
+{
+ synchronize_rcu();
+ put_net_track(old, tracker);
+}
+
+static int vsock_nl_dev_netns_fill(struct sk_buff *msg, struct genl_info *info)
+{
+ struct net *net = genl_info_net(info);
+ struct net *g2h;
+ bool equal;
+ void *hdr;
+ s32 id;
+
+ g2h = rcu_dereference_protected(vsock_g2h_net,
+ lockdep_is_held(&vsock_register_mutex));
+ equal = net_eq(net, g2h);
+ if (!equal) {
+ if (vsock_net_assignable(transport_g2h) &&
+ !vsock_net_check_mode(net, g2h))
+ id = NETNSA_NSID_NOT_ASSIGNED;
+ else
+ id = peernet2id_alloc(net, g2h, GFP_KERNEL);
+ }
+
+ hdr = genlmsg_iput(msg, info);
+ if (!hdr)
+ return -EMSGSIZE;
+
+ if (!equal && nla_put_s32(msg, VSOCK_A_NETNS_ID, id)) {
+ genlmsg_cancel(msg, hdr);
+ return -EMSGSIZE;
+ }
+
+ genlmsg_end(msg, hdr);
+
+ return 0;
+}
+
+/* Move the g2h device to @net, which keeps @net alive until the device leaves
+ * again. Returns -ENODEV if no g2h transport is loaded, -EOPNOTSUPP if the
+ * loaded one cannot be moved, and -EADDRINUSE if a guest in @net already uses
+ * the device's CID.
+ */
+static int vsock_g2h_net_assign(struct net *net,
+ struct netlink_ext_ack *extack)
+{
+ const struct vsock_transport *t;
+ netns_tracker old_tracker;
+ struct net *old;
+ int ret;
+
+ /* See vsock_g2h_assign_mutex for the lock ordering. */
+ mutex_lock(&vsock_g2h_assign_mutex);
+ mutex_lock(&vsock_register_mutex);
+
+ ret = -ENODEV;
+ if (!transport_g2h) {
+ NL_SET_ERR_MSG(extack, "no guest-to-host transport is loaded");
+ goto unlock;
+ }
+
+ ret = -EOPNOTSUPP;
+ if (!vsock_net_assignable(transport_g2h)) {
+ NL_SET_ERR_MSG(extack,
+ "the loaded guest-to-host transport does not support namespace assignment");
+ goto unlock;
+ }
+
+ if (transport_h2g && !transport_h2g->has_remote_cid) {
+ NL_SET_ERR_MSG(extack,
+ "the loaded host-to-guest transport cannot check the device's CID");
+ goto unlock;
+ }
+
+ ret = -EADDRINUSE;
+ if (transport_h2g &&
+ transport_h2g->has_remote_cid(net,
+ transport_g2h->get_local_cid())) {
+ NL_SET_ERR_MSG(extack,
+ "a guest in the target namespace already uses the device's CID");
+ goto unlock;
+ }
+
+ old = vsock_g2h_net_swap(net, &old_tracker);
+ t = transport_g2h;
+
+ mutex_unlock(&vsock_register_mutex);
+
+ /* See vsock_maybe_set_connected() comment about synchronizing with
+ * connecting sockets.
+ */
+ vsock_g2h_reset_unreachable(t);
+
+ mutex_unlock(&vsock_g2h_assign_mutex);
+
+ vsock_g2h_net_release(old, &old_tracker);
+
+ return 0;
+
+unlock:
+ mutex_unlock(&vsock_register_mutex);
+ mutex_unlock(&vsock_g2h_assign_mutex);
+
+ return ret;
+}
+
static struct sock *vsock_dequeue_accept(struct sock *listener)
{
struct vsock_sock *vlistener;
@@ -908,7 +1301,8 @@ static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
* like AF_INET prevents binding to a non-local IP address (in most
* cases), we only allow binding to a local CID.
*/
- if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
+ if (addr->svm_cid != VMADDR_CID_ANY &&
+ !vsock_find_cid(sock_net(sk_vsock(vsk)), addr->svm_cid))
return -EADDRNOTAVAIL;
switch (sk->sk_socket->type) {
@@ -1703,6 +2097,16 @@ static void vsock_connect_timeout(struct work_struct *work)
sock_put(sk);
}
+/* Avoid breaking the socket when another thread has changed its sock->state
+ * while we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+ sock->sk->sk_state = TCP_CLOSE;
+ if (sock->state == SS_CONNECTING)
+ sock->state = SS_UNCONNECTED;
+}
+
static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
int addr_len, int flags)
{
@@ -1861,8 +2265,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
* sk_state == TCP_SYN_SENT, which hereby we break.
* In such case VIRTIO_VSOCK_OP_RST will follow.
*/
- sk->sk_state = TCP_CLOSE;
- sock->state = SS_UNCONNECTED;
+ vsock_connect_close(sock);
/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
* transport->connect().
@@ -1876,10 +2279,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
}
err = sock_error(sk);
- if (err) {
- sk->sk_state = TCP_CLOSE;
- sock->state = SS_UNCONNECTED;
- }
+ if (err)
+ vsock_connect_close(sock);
out_wait:
finish_wait(sk_sleep(sk), &wait);
@@ -2795,6 +3196,7 @@ static long vsock_dev_do_ioctl(struct file *filp,
unsigned int cmd, void __user *ptr)
{
u32 __user *p = ptr;
+ struct net *net;
int retval = 0;
u32 cid;
@@ -2803,11 +3205,14 @@ static long vsock_dev_do_ioctl(struct file *filp,
/* To be compatible with the VMCI behavior, we prioritize the
* guest CID instead of well-know host CID (VMADDR_CID_HOST).
*/
- cid = vsock_registered_transport_cid(&transport_g2h);
+ net = current->nsproxy->net_ns;
+ cid = vsock_registered_transport_cid(&transport_g2h, net);
if (cid == VMADDR_CID_ANY)
- cid = vsock_registered_transport_cid(&transport_h2g);
+ cid = vsock_registered_transport_cid(&transport_h2g,
+ net);
if (cid == VMADDR_CID_ANY)
- cid = vsock_registered_transport_cid(&transport_local);
+ cid = vsock_registered_transport_cid(&transport_local,
+ net);
if (put_user(cid, p) != 0)
retval = -EFAULT;
@@ -2848,6 +3253,63 @@ static struct miscdevice vsock_device = {
.fops = &vsock_device_ops,
};
+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info)
+{
+ struct sk_buff *msg;
+ int err;
+
+ msg = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
+ if (!msg)
+ return -ENOMEM;
+
+ mutex_lock(&vsock_register_mutex);
+ if (transport_g2h) {
+ err = vsock_nl_dev_netns_fill(msg, info);
+ } else {
+ NL_SET_ERR_MSG(info->extack,
+ "no guest-to-host transport is loaded");
+ err = -ENODEV;
+ }
+ mutex_unlock(&vsock_register_mutex);
+
+ if (err) {
+ nlmsg_free(msg);
+ return err;
+ }
+
+ return genlmsg_reply(msg, info);
+}
+
+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info)
+{
+ struct nlattr *pid_attr = info->attrs[VSOCK_A_NETNS_PID];
+ struct nlattr *fd_attr = info->attrs[VSOCK_A_NETNS_FD];
+ struct net *net;
+ int err;
+
+ if (fd_attr && pid_attr) {
+ NL_SET_ERR_MSG(info->extack,
+ "netns-fd and netns-pid are mutually exclusive");
+ return -EINVAL;
+ }
+
+ if (fd_attr)
+ net = get_net_ns_by_fd(nla_get_u32(fd_attr));
+ else if (pid_attr)
+ net = get_net_ns_by_pid(nla_get_u32(pid_attr));
+ else
+ net = get_net(genl_info_net(info));
+ if (IS_ERR(net)) {
+ NL_SET_BAD_ATTR(info->extack, fd_attr ?: pid_attr);
+ return PTR_ERR(net);
+ }
+
+ err = vsock_g2h_net_assign(net, info->extack);
+ put_net(net);
+
+ return err;
+}
+
static int __vsock_net_mode_string(const struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos,
enum vsock_net_mode mode,
@@ -3037,7 +3499,7 @@ static void vsock_net_init(struct net *net)
net->vsock.g2h_fallback = 1;
}
-static __net_init int vsock_sysctl_init_net(struct net *net)
+static __net_init int vsock_pernet_init(struct net *net)
{
vsock_net_init(net);
@@ -3047,14 +3509,14 @@ static __net_init int vsock_sysctl_init_net(struct net *net)
return 0;
}
-static __net_exit void vsock_sysctl_exit_net(struct net *net)
+static __net_exit void vsock_pernet_exit(struct net *net)
{
vsock_sysctl_unregister(net);
}
-static struct pernet_operations vsock_sysctl_ops = {
- .init = vsock_sysctl_init_net,
- .exit = vsock_sysctl_exit_net,
+static struct pernet_operations vsock_pernet_ops = {
+ .init = vsock_pernet_init,
+ .exit = vsock_pernet_exit,
};
static int __init vsock_init(void)
@@ -3063,6 +3525,8 @@ static int __init vsock_init(void)
vsock_init_tables();
+ get_net_track(&init_net, &vsock_g2h_net_tracker, GFP_KERNEL);
+
vsock_proto.owner = THIS_MODULE;
vsock_device.minor = MISC_DYNAMIC_MINOR;
err = misc_register(&vsock_device);
@@ -3084,15 +3548,23 @@ static int __init vsock_init(void)
goto err_unregister_proto;
}
- if (register_pernet_subsys(&vsock_sysctl_ops)) {
+ if (register_pernet_subsys(&vsock_pernet_ops)) {
err = -ENOMEM;
goto err_unregister_sock;
}
+ err = genl_register_family(&vsock_nl_family);
+ if (err) {
+ pr_err("Cannot register vsock netlink family: %d\n", err);
+ goto err_unregister_pernet;
+ }
+
vsock_bpf_build_proto();
return 0;
+err_unregister_pernet:
+ unregister_pernet_subsys(&vsock_pernet_ops);
err_unregister_sock:
sock_unregister(AF_VSOCK);
err_unregister_proto:
@@ -3100,15 +3572,20 @@ static int __init vsock_init(void)
err_deregister_misc:
misc_deregister(&vsock_device);
err_reset_transport:
+ put_net_track(&init_net, &vsock_g2h_net_tracker);
return err;
}
static void __exit vsock_exit(void)
{
+ genl_unregister_family(&vsock_nl_family);
misc_deregister(&vsock_device);
sock_unregister(AF_VSOCK);
proto_unregister(&vsock_proto);
- unregister_pernet_subsys(&vsock_sysctl_ops);
+ unregister_pernet_subsys(&vsock_pernet_ops);
+
+ put_net_track(rcu_dereference_protected(vsock_g2h_net, true),
+ &vsock_g2h_net_tracker);
}
const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
@@ -3175,13 +3652,18 @@ EXPORT_SYMBOL_GPL(vsock_core_register);
void vsock_core_unregister(const struct vsock_transport *t)
{
+ netns_tracker old_tracker;
+ struct net *old = NULL;
+
mutex_lock(&vsock_register_mutex);
if (transport_h2g == t)
transport_h2g = NULL;
- if (transport_g2h == t)
+ if (transport_g2h == t) {
transport_g2h = NULL;
+ old = vsock_g2h_net_swap(&init_net, &old_tracker);
+ }
if (transport_dgram == t)
transport_dgram = NULL;
@@ -3190,6 +3672,10 @@ void vsock_core_unregister(const struct vsock_transport *t)
transport_local = NULL;
mutex_unlock(&vsock_register_mutex);
+
+ /* The device is gone, so release the namespace it was holding. */
+ if (old)
+ vsock_g2h_net_release(old, &old_tracker);
}
EXPORT_SYMBOL_GPL(vsock_core_unregister);
diff --git a/net/vmw_vsock/virtio_transport.c b/net/vmw_vsock/virtio_transport.c
index 4f9aa9c4c3aa59..4123924536dd64 100644
--- a/net/vmw_vsock/virtio_transport.c
+++ b/net/vmw_vsock/virtio_transport.c
@@ -542,13 +542,13 @@ static bool virtio_transport_msgzerocopy_allow(void)
bool virtio_transport_stream_allow(struct vsock_sock *vsk, u32 cid, u32 port)
{
- return vsock_net_mode_global(vsk);
+ return vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));
}
static bool virtio_transport_seqpacket_allow(struct vsock_sock *vsk,
u32 remote_cid);
-static bool virtio_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)
+static bool virtio_transport_has_remote_cid(struct net *net, u32 cid)
{
/* The CID could be implemented by the host. Always assume it is. */
return true;
@@ -587,6 +587,7 @@ static struct virtio_transport virtio_transport = {
.seqpacket_has_data = virtio_transport_seqpacket_has_data,
.msgzerocopy_allow = virtio_transport_msgzerocopy_allow,
+ .netns_assign_allow = true,
.notify_poll_in = virtio_transport_notify_poll_in,
.notify_poll_out = virtio_transport_notify_poll_out,
@@ -616,7 +617,7 @@ virtio_transport_seqpacket_allow(struct vsock_sock *vsk, u32 remote_cid)
struct virtio_vsock *vsock;
bool seqpacket_allow;
- if (!vsock_net_mode_global(vsk))
+ if (!vsock_g2h_net_reachable(sock_net(sk_vsock(vsk))))
return false;
seqpacket_allow = false;
@@ -633,7 +634,12 @@ static void virtio_transport_rx_work(struct work_struct *work)
{
struct virtio_vsock *vsock =
container_of(work, struct virtio_vsock, rx_work);
+ struct virtio_transport *t = &virtio_transport;
+ netns_tracker ns_tracker;
struct virtqueue *vq;
+ struct net *net;
+
+ net = vsock_g2h_net_get(&ns_tracker);
mutex_lock(&vsock->rx_lock);
@@ -682,10 +688,15 @@ static void virtio_transport_rx_work(struct work_struct *work)
virtio_transport_deliver_tap_pkt(skb);
- /* Force virtio-transport into global mode since it
- * does not yet support local-mode namespacing.
+ /* Only grab a reference if the net changes underneath
+ * us.
*/
- virtio_transport_recv_pkt(&virtio_transport, skb, NULL);
+ if (unlikely(!vsock_g2h_net_eq(net))) {
+ put_net_track(net, &ns_tracker);
+ net = vsock_g2h_net_get(&ns_tracker);
+ }
+
+ virtio_transport_recv_pkt(t, skb, net);
}
} while (!virtqueue_enable_cb(vq));
@@ -694,6 +705,8 @@ static void virtio_transport_rx_work(struct work_struct *work)
virtio_vsock_rx_fill(vsock);
out_nofill:
mutex_unlock(&vsock->rx_lock);
+
+ put_net_track(net, &ns_tracker);
}
static int virtio_vsock_vqs_init(struct virtio_vsock *vsock)
diff --git a/net/vmw_vsock/virtio_transport_common.c b/net/vmw_vsock/virtio_transport_common.c
index 1e762a480df490..c1cbe834e4f59d 100644
--- a/net/vmw_vsock/virtio_transport_common.c
+++ b/net/vmw_vsock/virtio_transport_common.c
@@ -295,6 +295,9 @@ static struct sk_buff *virtio_transport_alloc_skb(struct virtio_vsock_pkt_info *
* since a socket assigned to a transport is required.
*
* Do not use on listener sockets!
+ *
+ * This checks that the socket can reach the g2h device, so device-only replies
+ * such as virtio_transport_reset_no_sock() must keep not using this path.
*/
static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,
struct virtio_vsock_pkt_info *info)
@@ -317,6 +320,9 @@ static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,
if (unlikely(!t_ops))
return -EFAULT;
+ if (!vsock_g2h_reachable_sk(vsk))
+ return -ENETUNREACH;
+
src_cid = t_ops->transport.get_local_cid();
src_port = vsk->local_addr.svm_port;
if (!info->remote_cid) {
@@ -1468,8 +1474,8 @@ void virtio_transport_release(struct vsock_sock *vsk)
EXPORT_SYMBOL_GPL(virtio_transport_release);
static int
-virtio_transport_recv_connecting(struct sock *sk,
- struct sk_buff *skb)
+virtio_transport_recv_connecting(struct sock *sk, struct sk_buff *skb,
+ struct virtio_transport *t)
{
struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
struct vsock_sock *vsk = vsock_sk(sk);
@@ -1478,9 +1484,18 @@ virtio_transport_recv_connecting(struct sock *sk,
switch (le16_to_cpu(hdr->op)) {
case VIRTIO_VSOCK_OP_RESPONSE:
- sk->sk_state = TCP_ESTABLISHED;
+ if (!vsock_maybe_set_connected(vsk)) {
+ /* The net arg is required but unused: only g2h can fail
+ * vsock_maybe_set_connected(), and g2h
+ * virtio_transport_reset_no_sock() ignores the net arg.
+ */
+ virtio_transport_reset_no_sock(t, skb, sock_net(sk));
+ skerr = ECONNRESET;
+ err = -ENETUNREACH;
+ goto close;
+ }
+
sk->sk_socket->state = SS_CONNECTED;
- vsock_insert_connected(vsk);
sk->sk_state_change(sk);
break;
case VIRTIO_VSOCK_OP_INVALID:
@@ -1498,6 +1513,7 @@ virtio_transport_recv_connecting(struct sock *sk,
destroy:
virtio_transport_reset(vsk, skb);
+close:
sk->sk_state = TCP_CLOSE;
sk->sk_err = skerr;
sk_error_report(sk);
@@ -1736,8 +1752,6 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,
lock_sock_nested(child, SINGLE_DEPTH_NESTING);
- child->sk_state = TCP_ESTABLISHED;
-
vchild = vsock_sk(child);
vsock_addr_init(&vchild->local_addr, le64_to_cpu(hdr->dst_cid),
le32_to_cpu(hdr->dst_port));
@@ -1758,7 +1772,14 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,
if (virtio_transport_space_update(child, skb))
child->sk_write_space(child);
- vsock_insert_connected(vchild);
+ if (!vsock_maybe_set_connected(vchild)) {
+ release_sock(child);
+ /* Only reached for g2h, whose send_pkt() ignores the netns. */
+ virtio_transport_reset_no_sock(t, skb, sock_net(sk));
+ sock_put(child);
+ return -ENETUNREACH;
+ }
+
vsock_enqueue_accept(sk, child);
virtio_transport_send_response(vchild, skb);
@@ -1859,7 +1880,7 @@ void virtio_transport_recv_pkt(struct virtio_transport *t,
kfree_skb(skb);
break;
case TCP_SYN_SENT:
- virtio_transport_recv_connecting(sk, skb);
+ virtio_transport_recv_connecting(sk, skb, t);
kfree_skb(skb);
break;
case TCP_ESTABLISHED:
diff --git a/net/vmw_vsock/vsock_nl_gen.c b/net/vmw_vsock/vsock_nl_gen.c
new file mode 100644
index 00000000000000..18f3d47e723d4c
--- /dev/null
+++ b/net/vmw_vsock/vsock_nl_gen.c
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN kernel source */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#include <net/netlink.h>
+#include <net/genetlink.h>
+
+#include "vsock_nl_gen.h"
+
+#include <uapi/linux/vsock_netlink.h>
+
+/* VSOCK_CMD_DEV_NETNS_SET - do */
+static const struct nla_policy vsock_dev_netns_set_nl_policy[VSOCK_A_NETNS_PID + 1] = {
+ [VSOCK_A_NETNS_FD] = { .type = NLA_U32, },
+ [VSOCK_A_NETNS_PID] = { .type = NLA_U32, },
+};
+
+/* Ops table for vsock */
+static const struct genl_split_ops vsock_nl_ops[] = {
+ {
+ .cmd = VSOCK_CMD_DEV_NETNS_SET,
+ .doit = vsock_nl_dev_netns_set_doit,
+ .policy = vsock_dev_netns_set_nl_policy,
+ .maxattr = VSOCK_A_NETNS_PID,
+ .flags = GENL_ADMIN_PERM | GENL_CMD_CAP_DO,
+ },
+ {
+ .cmd = VSOCK_CMD_DEV_NETNS_GET,
+ .doit = vsock_nl_dev_netns_get_doit,
+ .flags = GENL_CMD_CAP_DO,
+ },
+};
+
+struct genl_family vsock_nl_family __ro_after_init = {
+ .name = VSOCK_FAMILY_NAME,
+ .version = VSOCK_FAMILY_VERSION,
+ .netnsok = true,
+ .parallel_ops = true,
+ .module = THIS_MODULE,
+ .split_ops = vsock_nl_ops,
+ .n_split_ops = ARRAY_SIZE(vsock_nl_ops),
+};
diff --git a/net/vmw_vsock/vsock_nl_gen.h b/net/vmw_vsock/vsock_nl_gen.h
new file mode 100644
index 00000000000000..a2fd87344581af
--- /dev/null
+++ b/net/vmw_vsock/vsock_nl_gen.h
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN kernel header */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#ifndef _LINUX_VSOCK_GEN_H
+#define _LINUX_VSOCK_GEN_H
+
+#include <net/netlink.h>
+#include <net/genetlink.h>
+
+#include <uapi/linux/vsock_netlink.h>
+
+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info);
+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info);
+
+extern struct genl_family vsock_nl_family;
+
+#endif /* _LINUX_VSOCK_GEN_H */
diff --git a/tools/net/ynl/Makefile.deps b/tools/net/ynl/Makefile.deps
index 3eee34e0efcf9c..cd1450f1cac055 100644
--- a/tools/net/ynl/Makefile.deps
+++ b/tools/net/ynl/Makefile.deps
@@ -62,4 +62,5 @@ CFLAGS_tc:= $(call get_hdr_inc,__LINUX_RTNETLINK_H,rtnetlink.h) \
$(call get_hdr_inc,_TC_SKBEDIT_H,tc_act/tc_skbedit.h) \
$(call get_hdr_inc,_TC_TUNNEL_KEY_H,tc_act/tc_tunnel_key.h)
CFLAGS_tcp_metrics:=$(call get_hdr_inc,_LINUX_TCP_METRICS_H,tcp_metrics.h)
+CFLAGS_vsock:=$(call get_hdr_inc,_LINUX_VSOCK_NETLINK_H,vsock_netlink.h)
CFLAGS_wireguard:=$(call get_hdr_inc2,_LINUX_WIREGUARD_H,_WG_UAPI_WIREGUARD_H,wireguard.h)
diff --git a/tools/testing/selftests/vsock/Makefile b/tools/testing/selftests/vsock/Makefile
index c407c0afd9388e..2b066ba91bcd78 100644
--- a/tools/testing/selftests/vsock/Makefile
+++ b/tools/testing/selftests/vsock/Makefile
@@ -13,5 +13,10 @@ $(VSOCK_TEST_DIR)/vsock_test: $(VSOCK_TEST_SRCS)
TEST_PROGS += vmtest.sh
TEST_GEN_FILES := vsock_test
+TEST_FILES := \
+ ../../../net/ynl/pyynl/cli.py \
+ ../../../net/ynl/pyynl/lib \
+ ../../../../Documentation/netlink/specs/vsock.yaml
+
include ../lib.mk
diff --git a/tools/testing/selftests/vsock/config b/tools/testing/selftests/vsock/config
index 5f0a4f17dfc96c..4b31085558faae 100644
--- a/tools/testing/selftests/vsock/config
+++ b/tools/testing/selftests/vsock/config
@@ -109,3 +109,4 @@ CONFIG_FS_DAX=y
CONFIG_MEMORY_HOTPLUG=y
CONFIG_MEMORY_HOTREMOVE=y
CONFIG_ZONE_DEVICE=y
+CONFIG_USER_NS=y
diff --git a/tools/testing/selftests/vsock/vmtest.sh b/tools/testing/selftests/vsock/vmtest.sh
index 310dfc2a39ad57..9614532a56285f 100755
--- a/tools/testing/selftests/vsock/vmtest.sh
+++ b/tools/testing/selftests/vsock/vmtest.sh
@@ -17,6 +17,20 @@ readonly KERNEL_CHECKOUT=$(realpath "${SCRIPT_DIR}"/../../../../)
source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
readonly VSOCK_TEST="${SCRIPT_DIR}"/vsock_test
+
+# "make install" copies the ynl CLI, its lib package and the spec next to this
+# script (see TEST_FILES); in a source tree they stay where they are built.
+if [[ -r "${SCRIPT_DIR}"/cli.py ]]; then
+ readonly YNL_CLI="${SCRIPT_DIR}"/cli.py
+ readonly YNL_LIB="${SCRIPT_DIR}"/lib
+ readonly VSOCK_SPEC="${SCRIPT_DIR}"/vsock.yaml
+else
+ readonly YNL_DIR="${KERNEL_CHECKOUT}"/tools/net/ynl/pyynl
+ readonly YNL_CLI="${YNL_DIR}"/cli.py
+ readonly YNL_LIB="${YNL_DIR}"/lib
+ readonly SPEC_DIR="${KERNEL_CHECKOUT}"/Documentation/netlink/specs
+ readonly VSOCK_SPEC="${SPEC_DIR}"/vsock.yaml
+fi
readonly TEST_GUEST_PORT=51000
readonly TEST_HOST_PORT=50000
readonly TEST_HOST_PORT_LISTENER=50001
@@ -73,6 +87,15 @@ readonly TEST_NAMES=(
ns_delete_vm_ok
ns_delete_host_ok
ns_delete_both_ok
+ ns_guest_local_connect_to_host_fails
+ ns_guest_assign_g2h_netns_connect_to_host_ok
+ ns_guest_assign_g2h_netns_by_pid_ok
+ ns_guest_assign_g2h_netns_init_ns_connect_fails
+ ns_guest_assign_g2h_netns_host_connect_ok
+ ns_guest_assign_g2h_netns_pins_ns_ok
+ ns_guest_assign_g2h_netns_old_conn_send_fails
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails
)
readonly TEST_DESCS=(
# vm_server_host_client
@@ -149,12 +172,48 @@ readonly TEST_DESCS=(
# ns_delete_both_ok
"Check that deleting the VM and host's namespaces does not break the socket connection"
+
+ # ns_guest_local_connect_to_host_fails
+ "Check a guest process in a local ns cannot reach the host without the netns assign."
+
+ # ns_guest_assign_g2h_netns_connect_to_host_ok
+ "Check a guest process in a local ns reaches the host once the vsock device is assigned to it."
+
+ # ns_guest_assign_g2h_netns_by_pid_ok
+ "Check the vsock device can be assigned to a ns given by PID from outside it."
+
+ # ns_guest_assign_g2h_netns_init_ns_connect_fails
+ "Check the guest's initial ns loses vsock once the device is assigned to another ns."
+
+ # ns_guest_assign_g2h_netns_host_connect_ok
+ "Check the host reaches a guest listener in the ns the vsock device is assigned to."
+
+ # ns_guest_assign_g2h_netns_pins_ns_ok
+ "Check the assignment keeps the ns alive when deleted, and that reassigning releases it."
+
+ # ns_guest_assign_g2h_netns_old_conn_send_fails
+ "Check connections made before the assign stop sending once they lose the device."
+
+ # ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ "Check assigning the guest's vsock device to a namespace needs CAP_NET_ADMIN."
+
+ # ns_guest_assign_g2h_netns_unpriv_user_ns_fails
+ "Check an unprivileged user cannot claim the guest's vsock device via a user ns."
)
readonly USE_SHARED_VM=(
vm_server_host_client
vm_client_host_server
vm_loopback
+ ns_guest_local_connect_to_host_fails
+ ns_guest_assign_g2h_netns_connect_to_host_ok
+ ns_guest_assign_g2h_netns_by_pid_ok
+ ns_guest_assign_g2h_netns_init_ns_connect_fails
+ ns_guest_assign_g2h_netns_host_connect_ok
+ ns_guest_assign_g2h_netns_pins_ns_ok
+ ns_guest_assign_g2h_netns_old_conn_send_fails
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails
)
readonly NS_MODES=("local" "global")
@@ -316,6 +375,43 @@ check_deps() {
fi
}
+check_ns_guest_deps() {
+ local tname=$1
+ local deps="unshare python3"
+ local dep
+
+ if [[ ! "${tname}" =~ ^ns_guest_ ]]; then
+ return 0
+ fi
+
+ # test-specific guest dep checks
+ case "${tname}" in
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails | \
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails)
+ deps="${deps} setpriv"
+ ;;
+ esac
+
+ for dep in ${deps}; do
+ if [[ ! -x $(command -v "${dep}") ]]; then
+ log_host "no ${dep} for test ${tname}"
+ return 1
+ fi
+ done
+
+ if ! python3 -c "import yaml" &>/dev/null; then
+ log_host "no python3 yaml module for test ${tname}"
+ return 1
+ fi
+
+ if [[ ! -r "${YNL_CLI}" ]] || [[ ! -r "${VSOCK_SPEC}" ]]; then
+ log_host "no ynl cli or vsock spec for test ${tname}"
+ return 1
+ fi
+
+ return 0
+}
+
check_netns() {
local tname=$1
@@ -401,6 +497,19 @@ setup_home() {
mkdir -p "$(dirname "${SSH_KEY_PATH}")"
ssh-keygen -t ed25519 -f "${SSH_KEY_PATH}" -N "" -q
cp "${VSOCK_TEST}" "${TEST_HOME}"/vsock_test
+
+ mkdir -p "${TEST_HOME}"/ynl
+ if [[ -r "${YNL_CLI}" ]]; then
+ cp "${YNL_CLI}" "${TEST_HOME}"/ynl/
+ cp -r "${YNL_LIB}" "${TEST_HOME}"/ynl/
+ cp "${VSOCK_SPEC}" "${TEST_HOME}"/ynl/
+ fi
+
+ # One of the tests runs the CLI as an unprivileged user, so the CLI
+ # has to be reachable by one.
+ chmod -R a+rX "${TEST_HOME}"/ynl
+
+ chmod 755 "${TEST_HOME}"
}
create_pidfile() {
@@ -528,6 +637,82 @@ vm_wait_for_ssh() {
done
}
+# Create a local mode namespace in the VM and echo the pid holding it open.
+vm_ns_start() {
+ local ns=$1
+ local initns
+ local nspid
+ local newns
+ local i
+
+ local mode=/proc/sys/net/vsock/child_ns_mode
+
+ if ! vm_ssh "${ns}" -- "echo local > ${mode}" &>/dev/null; then
+ return
+ fi
+
+ nspid=$(vm_ssh "${ns}" -- "unshare -n sleep infinity" \
+ '>/dev/null 2>&1 & echo $!')
+ if [[ -z "${nspid}" ]]; then
+ return
+ fi
+
+ initns=$(vm_ssh "${ns}" -- "readlink /proc/self/ns/net")
+ for ((i = 0; i < WAIT_PERIOD_MAX; i++)); do
+ newns=$(vm_ssh "${ns}" -- "readlink /proc/${nspid}/ns/net" \
+ 2>/dev/null)
+ if [[ -n "${newns}" ]] && [[ "${newns}" != "${initns}" ]]; then
+ echo "${nspid}"
+ return
+ fi
+ sleep 1
+ done
+
+ vm_ns_stop "${ns}" "${nspid}"
+}
+
+# Returns once the holder is gone, so that the namespace is unreferenced and
+# the kernel can start tearing it down.
+vm_ns_stop() {
+ local ns=$1
+ local nspid=$2
+
+ vm_ssh "${ns}" <<-EOF &>/dev/null
+ kill ${nspid}
+ for ((i = 0; i < ${WAIT_PERIOD_MAX}; i++)); do
+ kill -0 ${nspid} 2>/dev/null || break
+ sleep 1
+ done
+ EOF
+}
+
+# Runs in the guest's initial namespace when <nspid> is empty. The command must
+# not contain single quotes.
+vm_ns_exec() {
+ local ns=$1
+ local nspid=$2
+ local cmd=$3
+
+ if [[ -z "${nspid}" ]]; then
+ vm_ssh "${ns}" -- "${cmd}"
+ return
+ fi
+
+ vm_ssh "${ns}" -- nsenter -t "${nspid}" -n sh -c "'${cmd}'"
+}
+
+vm_ns_assign_g2h() {
+ local ns=$1
+ local nspid=$2
+
+ vm_ns_exec "${ns}" "${nspid}" "python3 /root/ynl/cli.py --no-schema \
+ --spec /root/ynl/vsock.yaml --do dev-netns-set"
+}
+
+vm_reset_g2h() {
+ vm_ns_assign_g2h "init_ns" "" &>/dev/null
+}
+
# derived from selftests/net/net_helper.sh
wait_for_listener()
{
@@ -564,17 +749,33 @@ wait_for_listener()
done
}
-vm_wait_for_listener() {
+# Runs in the guest's initial namespace when <nspid> is empty.
+vm_ns_wait_for_listener() {
local ns=$1
- local port=$2
- local protocol=$3
+ local nspid=$2
+ local port=$3
+ local protocol=$4
+ local nsenter=
+ local args
+
+ [[ -n "${nspid}" ]] && nsenter="nsenter -t ${nspid} -n"
+ args="${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}"
vm_ssh "${ns}" <<EOF
$(declare -f wait_for_listener)
-wait_for_listener ${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}
+export -f wait_for_listener
+${nsenter} bash -c "wait_for_listener ${args}"
EOF
}
+vm_wait_for_listener() {
+ local ns=$1
+ local port=$2
+ local protocol=$3
+
+ vm_ns_wait_for_listener "${ns}" "" "${port}" "${protocol}"
+}
+
host_wait_for_listener() {
local ns=$1
local port=$2
@@ -1421,6 +1622,392 @@ test_ns_delete_both_ok() {
check_ns_delete_doesnt_break_connection "both"
}
+# Send a string from the guest to a host listener and leave what the host
+# received in <outfile>.
+guest_send_to_host() {
+ local ns=$1
+ local nspid=$2
+ local port=$3
+ local outfile=$4
+ local cmd="echo TEST | socat -u STDIN VSOCK-CONNECT:2:${port}"
+ local pid
+
+ socat -u VSOCK-LISTEN:"${port}" STDOUT > "${outfile}" 2>/dev/null &
+ pid=$!
+ host_wait_for_listener "${ns}" "${port}" "vsock"
+
+ vm_ns_exec "${ns}" "${nspid}" "${cmd}" 2>/dev/null
+
+ timeout "${WAIT_PERIOD}" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ # Wait for the listener to actually go, or the next test binding the
+ # same port races it and silently reads nothing.
+ terminate_pids "${pid}"
+ wait "${pid}" 2>/dev/null
+}
+
+# Send a string from the host to a listener in the guest and leave what the
+# guest received in <outfile>.
+host_send_to_guest() {
+ local ns=$1
+ local nspid=$2
+ local port=$3
+ local outfile=$4
+ local cmd="socat -u VSOCK-LISTEN:${port} STDOUT"
+ local dst="VSOCK-CONNECT:${VSOCK_CID}:${port}"
+ local pid
+
+ vm_ns_exec "${ns}" "${nspid}" "${cmd}" > "${outfile}" 2>/dev/null &
+ pid=$!
+ vm_ns_wait_for_listener "${ns}" "${nspid}" "${port}" "vsock"
+
+ echo TEST | socat -u STDIN "${dst}" 2>/dev/null
+
+ timeout "${WAIT_PERIOD}" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ vm_ns_exec "${ns}" "${nspid}" \
+ "pkill -f VSOCK-LISTEN:${port}" &>/dev/null
+ terminate_pids "${pid}"
+ wait "${pid}" 2>/dev/null
+}
+
+ns_old_conn_cleanup() {
+ local port=$1
+ local pid=$2
+ local sender=$3
+ local outfile=$4
+ local nspid=$5
+
+ vm_ns_exec "init_ns" "" "pkill -f VSOCK-CONNECT:2:${port}" &>/dev/null
+ terminate_pids "${pid}" "${sender}"
+ wait "${pid}" "${sender}" 2>/dev/null
+ rm -f "${outfile}"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+}
+
+test_ns_guest_assign_g2h_netns_old_conn_send_fails() {
+ local gap=$(( WAIT_PERIOD * 3 ))
+ local port=12346
+ local elapsed
+ local started
+ local outfile
+ local result
+ local sender
+ local nspid
+ local pid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ socat -u VSOCK-LISTEN:"${port}" STDOUT > "${outfile}" 2>/dev/null &
+ pid=$!
+ host_wait_for_listener "init_ns" "${port}" "vsock"
+
+ # Send a message, wait, then send another. While waiting, assign the
+ # device to a namespace. Confirm the second message does not arrive.
+ started=${SECONDS}
+ vm_ssh "init_ns" -- \
+ "(echo FIRST; sleep ${gap}; echo SECOND) |" \
+ "socat -u STDIN VSOCK-CONNECT:2:${port}" &>/dev/null &
+ sender=$!
+
+ timeout "$(( WAIT_PERIOD * WAIT_PERIOD_MAX ))" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ ns_old_conn_cleanup "${port}" "${pid}" "${sender}" \
+ "${outfile}" "${nspid}"
+ return "${KSFT_FAIL}"
+ fi
+ elapsed=$(( SECONDS - started ))
+
+ sleep $(( gap + WAIT_PERIOD ))
+
+ result=$(cat "${outfile}")
+ ns_old_conn_cleanup "${port}" "${pid}" "${sender}" \
+ "${outfile}" "${nspid}"
+
+ if [[ "${result}" != *FIRST* ]]; then
+ log_host "no connection before the assign: [${result}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ if [[ $(( elapsed + 1 )) -ge ${gap} ]]; then
+ log_host "connect and assign took ${elapsed}s of a ${gap}s gap"
+ return "${KSFT_SKIP}"
+ fi
+
+ if [[ "${result}" == *SECOND* ]]; then
+ log_host "old connection still delivered after the assign"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_local_connect_to_host_fails() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" == TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_connect_to_host_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_by_pid_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ssh "init_ns" -- python3 /root/ynl/cli.py --no-schema \
+ --spec /root/ynl/vsock.yaml --do dev-netns-set \
+ --json "'{\"netns-pid\": ${nspid}}'"; then
+ log_host "failed to assign the vsock device by PID"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_init_ns_connect_fails() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" == TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_host_connect_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ host_send_to_guest "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_pins_ns_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ vm_ns_stop "init_ns" "${nspid}"
+ sleep "${WAIT_PERIOD}"
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "" "${port}" "${outfile}"
+ result=$(cat "${outfile}")
+ if [[ "${result}" == TEST ]]; then
+ log_host "device returned to the init ns instead of pinning it"
+ rm -f "${outfile}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ # Assigning it back is what releases the deleted namespace.
+ vm_reset_g2h
+
+ guest_send_to_host "init_ns" "" "$(( port + 1 ))" "${outfile}"
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ log_host "device did not come back on reassign: [${result}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+check_assign_g2h_eperm() {
+ local wrapper=$1
+ local out
+
+ if out=$(vm_ssh "init_ns" -- "${wrapper}" python3 /root/ynl/cli.py \
+ --no-schema --spec /root/ynl/vsock.yaml \
+ --do dev-netns-set 2>&1); then
+ log_host "assign unexpectedly succeeded under '${wrapper}'"
+ return "${KSFT_FAIL}"
+ fi
+
+ if [[ "${out}" != *"Operation not permitted"* ]]; then
+ log_host "no EPERM under '${wrapper}': [${out}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_no_cap_net_admin_fails() {
+ check_assign_g2h_eperm "unshare -n setpriv --bounding-set=-net_admin"
+}
+
+test_ns_guest_assign_g2h_netns_unpriv_user_ns_fails() {
+ local unpriv_uid=65534
+ local unpriv
+
+ unpriv="setpriv --reuid=${unpriv_uid} --regid=${unpriv_uid}"
+ unpriv="${unpriv} --clear-groups"
+
+ if ! vm_ssh "init_ns" -- "${unpriv} unshare -Urn true"; then
+ log_host "unprivileged user namespaces unavailable, skipping"
+ return "${KSFT_SKIP}"
+ fi
+
+ check_assign_g2h_eperm "${unpriv} unshare -Urn"
+}
+
shared_vm_test() {
local tname
@@ -1453,7 +2040,8 @@ run_shared_vm_tests() {
continue
fi
- if ! check_netns "${arg}"; then
+ if ! check_netns "${arg}" ||
+ ! check_ns_guest_deps "${arg}"; then
check_result "${KSFT_SKIP}" "${arg}"
continue
fi
@@ -1517,7 +2105,8 @@ run_ns_tests() {
continue
fi
- if ! check_netns "${arg}"; then
+ if ! check_netns "${arg}" ||
+ ! check_ns_guest_deps "${arg}"; then
check_result "${KSFT_SKIP}" "${arg}"
continue
fi
|
| 3/2 | 2026/11/18 10:04 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 28037 output: 64 thoughts: 625 Thoughts: **Analyzing the vsock Netlink Patch** Okay, let's dive into this patch. My initial thought is to break down what's being modified. It looks like we're dealing with quite a few files: documentation, MAINTAINERS, and a significant portion of the `net/vmw_vsock` and `drivers/vhost` directories. Specifically, the patch touches `net.rst`, `vsock.yaml`, `vsock.c`, `.h` files, `Makefile`s and various `.c` files within the `net/vmw_vsock` directory. This suggests a potentially substantial change to the vsock subsystem. From what I can gather, the core of the change revolves around introducing a new Generic Netlink family, "vsock." This new family provides commands, `VSOCK_CMD_DEV_NETNS_SET` and `VSOCK_CMD_DEV_NETNS_GET`, to move a guest-to-host (G2H) vsock device to a different network namespace. This, along with modifications to af_vsock, virtio_transport, and vhost/vsock, is the crux of the change. It's fully reachable in a standard QEMU virtualized environment. This is good to know, and the implication is that any existing fuzzing infrastructure, particularly Syzkaller, should be readily applicable. The implementation details involve netlink commands (`vsock_nl_dev_netns_set_doit`, `vsock_nl_dev_netns_get_doit`), mutex locking (`vsock_g2h_assign_mutex`, `vsock_cid_lock`), socket state transitions, and connection reset logic (`vsock_g2h_reset_unreachable`), as well as netns tracking (`vsock_g2h_net_swap`, `vsock_g2h_net_release`). These are all typical elements of a networking subsystem change. So, the next question is obvious: Is this worth fuzzing? Based on the reachability and scope of the changes, the answer is an unequivocal YES. There are netlink aspects and vsock sockets that are ripe targets for fuzzing. Now, let's confirm the details. First, is this actually reachable? It looks like the "vsock" genetlink family can be called from userspace, requiring `CAP_NET_ADMIN` (or unprivileged user namespaces), which should be achievable through standard mechanisms. Additionally, vsock sockets themselves are accessible, meaning we have multiple avenues for fuzzing. Syzkaller's existing support for netlink and vsock is critical here. Finally, what are the configuration options required? I'll need to check the Kconfig files for `net/vmw_vsock` and `drivers/vhost` to ensure the relevant components are enabled. This is standard procedure to determine the build configuration implications. |
| 4/2 | 2026/11/18 10:06 | tool | grepper |
0mArgs:{
"Expression": "CONFIG_VSOCKETS|CONFIG_VIRTIO_VSOCKETS|CONFIG_VHOST_VSOCK",
"PathPrefixes": [
"net/vmw_vsock/Kconfig",
"drivers/vhost/Kconfig"
]
}Results: {
"Output": "no matches"
} |
| 5/2 | 2026/11/18 10:06 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 29355 output: 36 thoughts: 35 Thoughts: Okay, here's my take on those thoughts, framed as an expert's internal monologue: **Investigating Kconfig Dependencies** Alright, before I dive too deep into this integration, it's best to take a direct approach. I need to understand the configuration dependencies at the source. Instead of relying on vague documentation or memory, I'm going to pull the relevant Kconfig files. Specifically, I'll examine `net/vmw_vsock/Kconfig` and `drivers/vhost/Kconfig`. Using something like `read-file` in the kernel build system or a quick grepper search should give me the explicit dependencies and configuration options involved. This should clearly identify how these modules are intended to be used and any relationships between them that I need to be aware of before proceeding. That will give me the raw, unfiltered truth about the configurations. |
| 6/2 | 2026/11/18 10:07 | tool | read-file |
0mArgs:{
"File": "net/vmw_vsock/Kconfig",
"FirstLine": 1,
"LineCount": 80
}Results: {
"Contents": " 1:\t# SPDX-License-Identifier: GPL-2.0-only\n 2:\t#\n 3:\t# Vsock protocol\n 4:\t#\n 5:\t\n 6:\tconfig VSOCKETS\n 7:\t\ttristate \"Virtual Socket protocol\"\n 8:\t\thelp\n 9:\t\t Virtual Socket Protocol is a socket protocol similar to TCP/IP\n 10:\t\t allowing communication between Virtual Machines and hypervisor\n 11:\t\t or host.\n 12:\t\n 13:\t\t You should also select one or more hypervisor-specific transports\n 14:\t\t below.\n 15:\t\n 16:\t\t To compile this driver as a module, choose M here: the module\n 17:\t\t will be called vsock. If unsure, say N.\n 18:\t\n 19:\tconfig VSOCKETS_DIAG\n 20:\t\ttristate \"Virtual Sockets monitoring interface\"\n 21:\t\tdepends on VSOCKETS\n 22:\t\tdefault y\n 23:\t\thelp\n 24:\t\t Support for PF_VSOCK sockets monitoring interface used by the ss tool.\n 25:\t\t If unsure, say Y.\n 26:\t\n 27:\t\t Enable this module so userspace applications can query open sockets.\n 28:\t\n 29:\tconfig VSOCKETS_LOOPBACK\n 30:\t\ttristate \"Virtual Sockets loopback transport\"\n 31:\t\tdepends on VSOCKETS\n 32:\t\tdefault y\n 33:\t\tselect VIRTIO_VSOCKETS_COMMON\n 34:\t\thelp\n 35:\t\t This module implements a loopback transport for Virtual Sockets,\n 36:\t\t using vmw_vsock_virtio_transport_common.\n 37:\t\n 38:\t\t To compile this driver as a module, choose M here: the module\n 39:\t\t will be called vsock_loopback. If unsure, say N.\n 40:\t\n 41:\tconfig VMWARE_VMCI_VSOCKETS\n 42:\t\ttristate \"VMware VMCI transport for Virtual Sockets\"\n 43:\t\tdepends on VSOCKETS \u0026\u0026 VMWARE_VMCI\n 44:\t\thelp\n 45:\t\t This module implements a VMCI transport for Virtual Sockets.\n 46:\t\n 47:\t\t Enable this transport if your Virtual Machine runs on a VMware\n 48:\t\t hypervisor.\n 49:\t\n 50:\t\t To compile this driver as a module, choose M here: the module\n 51:\t\t will be called vmw_vsock_vmci_transport. If unsure, say N.\n 52:\t\n 53:\tconfig VIRTIO_VSOCKETS\n 54:\t\ttristate \"virtio transport for Virtual Sockets\"\n 55:\t\tdepends on VSOCKETS \u0026\u0026 VIRTIO\n 56:\t\tselect VIRTIO_VSOCKETS_COMMON\n 57:\t\thelp\n 58:\t\t This module implements a virtio transport for Virtual Sockets.\n 59:\t\n 60:\t\t Enable this transport if your Virtual Machine host supports Virtual\n 61:\t\t Sockets over virtio.\n 62:\t\n 63:\t\t To compile this driver as a module, choose M here: the module will be\n 64:\t\t called vmw_vsock_virtio_transport. If unsure, say N.\n 65:\t\n 66:\tconfig VIRTIO_VSOCKETS_COMMON\n 67:\t\ttristate\n 68:\t\thelp\n 69:\t\t This option is selected by any driver which needs to access\n 70:\t\t the virtio_vsock. The module will be called\n 71:\t\t vmw_vsock_virtio_transport_common.\n 72:\t\n 73:\tconfig HYPERV_VSOCKETS\n 74:\t\ttristate \"Hyper-V transport for Virtual Sockets\"\n 75:\t\tdepends on VSOCKETS \u0026\u0026 HYPERV_VMBUS\n 76:\t\thelp\n 77:\t\t This module implements a Hyper-V transport for Virtual Sockets.\n 78:\t\n 79:\t\t Enable this transport if your Virtual Machine host supports Virtual\n 80:\t\t Sockets over Hyper-V VMBus.\n"
} |
| 7/2 | 2026/11/18 10:07 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 30681 output: 32 thoughts: 14 Thoughts: Okay, here's my take on those thoughts, tailored for an expert audience: **Investigating a Configuration Context** Alright, I'm digging into this; whatever the issue is, I'm not stopping at just one place. My initial thought process suggests there's a problem, and I need to explore every potential lead. Since it concerns *vhost*, I'm not just going to assume I've found the issue quickly; it's prudent to widen the scope of my investigation. Considering the configuration aspect often relates to build-time decisions, the logical next step is to examine `drivers/vhost/Kconfig` as well. The Kconfig files define the configuration options used during the build process, so any potential misconfiguration will most likely originate there. I'm operating on the assumption that a configuration error is likely responsible, and this is where I'll look. |
| 8/2 | 2026/11/18 10:08 | tool | grepper |
0mArgs:{
"Expression": "config VHOST_VSOCK",
"PathPrefixes": [
"drivers/vhost/"
]
}Results: {
"Output": "drivers/vhost/Kconfig=46=config VHOST_SCSI\n--\ndrivers/vhost/Kconfig-55-\ndrivers/vhost/Kconfig:56:config VHOST_VSOCK\ndrivers/vhost/Kconfig-57-\ttristate \"vhost virtio-vsock driver\"\n"
} |
| 9/2 | 2026/11/18 10:08 | llm | patch-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31001 output: 34 thoughts: 17 Thoughts: Here's a summary of my thought process, as requested: **Navigating the Kconfig Labyrinth** Okay, so I'm diving into this `drivers/vhost/Kconfig` file. Specifically, I'm interested in what's happening around line 56. My mental map probably already includes a general understanding of Kconfig files in the Linux kernel build system. I know they're used for configuration options, dependencies, and dependencies. Line 56 is just a reference point for me to start poking around. I'm going to quickly scan the context around that line. My focus will be on understanding what configuration option is defined there, what it depends on, and how it might impact the build process for vhost drivers. I'll be looking for clues about the scope of the option, whether it enables or disables a feature, and potentially any default values or help text that might provide further insight into its purpose. I'll likely mentally trace how this option relates to the larger vhost subsystem and any associated dependencies, looking for hints on if this is related to a specific hardware configuration, a specific kernel feature, or maybe even related to a security-related decision. My mind will likely be quickly associating these lines with other Kconfig files, too, checking for relationships and any conflicting options. |
| 10/2 | 2026/11/18 10:09 | tool | read-file |
0mArgs:{
"File": "drivers/vhost/Kconfig",
"FirstLine": 54,
"LineCount": 20
}Results: {
"Contents": " 54:\t\tfor use with virtio-scsi guests\n 55:\t\n 56:\tconfig VHOST_VSOCK\n 57:\t\ttristate \"vhost virtio-vsock driver\"\n 58:\t\tdepends on VSOCKETS \u0026\u0026 EVENTFD\n 59:\t\tselect VHOST\n 60:\t\tselect VIRTIO_VSOCKETS_COMMON\n 61:\t\tdefault n\n 62:\t\thelp\n 63:\t\tThis kernel module can be loaded in the host kernel to provide AF_VSOCK\n 64:\t\tsockets for communicating with guests. The guests must have the\n 65:\t\tvirtio_transport.ko driver loaded to use the virtio-vsock device.\n 66:\t\n 67:\t\tTo compile this driver as a module, choose M here: the module will be called\n 68:\t\tvhost_vsock.\n 69:\t\n 70:\tconfig VHOST_VDPA\n 71:\t\ttristate \"Vhost driver for vDPA-based backend\"\n 72:\t\tdepends on EVENTFD\n 73:\t\tselect VHOST\n"
} |
| 11/2 | 2026/11/18 10:09 | llm | patch-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 31606 output: 313 thoughts: 2793 Thoughts: **Analysis of VSOCK NetNS Support for Fuzzing** Alright, let's break this down. My goal here is to identify key entrypoints and configurations for fuzzing the VSOCK (Virtual Socket) code within the Linux kernel, specifically focusing on the new netns (network namespace) functionality. First, I need to understand the basic build requirements. From the `Makefile`, `vsock` is core, enabled by `CONFIG_VSOCKETS`. `VIRTIO_VSOCKETS` and `VHOST_VSOCK` are separate configurations for the virtio and vhost transports, respectively, each with their own dependencies. `NETLINK` and `GENERIC_NETLINK` are standard networking components, and I can assume they're available. `VSOCKETS`, `VIRTIO_VSOCKETS`, and `VHOST_VSOCK` are the key configs here. Now, let's look at the code changes. I'm focusing on non-ubiquitous functions, i.e., those directly related to the netns feature. I've identified the following files as most relevant: `af_vsock.c`, `virtio_transport.c`, `virtio_transport_common.c`, `vhost/vsock.c`, and `vsock_nl_gen.c`. Specifically, in `vsock_nl_gen.c` and `af_vsock.c`, `vsock_nl_dev_netns_set_doit` and `vsock_nl_dev_netns_get_doit` are critical; these are the Netlink entrypoints. Looking at `af_vsock.c`, `vsock_g2h_net_assign`, `vsock_maybe_set_connected`, `vsock_g2h_net_reachable`, `vsock_g2h_reachable_sk`, `vsock_find_cid`, `__vsock_find_cid`, and modified functions `vsock_assign_transport`, `vsock_connect`, `__vsock_bind`, and `vsock_dev_do_ioctl` stand out, along with CID locking functions. From `virtio_transport_common.c`, the modified receive handlers `virtio_transport_recv_connecting` and `virtio_transport_recv_listen` are important. In `virtio_transport.c` modifications to allow functionality are key. And finally, `vhost_vsock_set_cid` is relevant in `drivers/vhost/vsock.c`. Based on the fuzzing guidelines, I need to extract feature-specific entrypoints and core modified functions, avoiding ubiquitous functions like memory allocators. My "FocusSymbols" list should therefore include: `vsock_nl_dev_netns_set_doit`, `vsock_nl_dev_netns_get_doit`, `vsock_maybe_set_connected`, `vsock_g2h_net_reachable`, `vsock_g2h_reachable_sk`, `vsock_find_cid`, `__vsock_find_cid`, `vhost_vsock_set_cid`, `virtio_transport_recv_connecting`, and `virtio_transport_recv_listen`. I'll also consider the static functions called by the Netlink entrypoints, like `vsock_g2h_net_assign`, as potentially important if the fuzzer can't directly target the caller. Also, `vsock_dev_do_ioctl` handles IOCTL calls on `/dev/vsock` and is modified to pass netns, so it's also relevant. Now, let's verify reachability. The netlink family, AF_VSOCK sockets, and /dev/vsock ioctls provide different user-space access points, and virtio/vhost-vsock are common virtualization scenarios, so the code is completely reachable. The key changes involve adding a new netlink family, allowing VSOCK devices to be moved across network namespaces. This introduces significant state transitions, concurrency, reference tracking and IPC interfaces: The `netns_tracker`, RCU pointers, and mutex synchronization across threads (`vsock_g2h_assign_mutex`, `vsock_register_mutex`, `vsock_table_lock`). It also requires socket reset logic and updates in transport connection and packet receive handlers. Overall this warrants fuzzing. `WorthFuzzing` is `true`. I've determined the required configurations: `VSOCKETS`, `VIRTIO_VSOCKETS`, and `VHOST_VSOCK`. I will pass the results and `FocusSymbols` to the fuzzing framework now. |
| 12/2 | 2026/11/18 10:11 | tool | set-results |
0mArgs:{
"EnableConfigs": [
"VSOCKETS",
"VIRTIO_VSOCKETS",
"VHOST_VSOCK"
],
"FocusSymbols": [
"vsock_nl_dev_netns_set_doit",
"vsock_nl_dev_netns_get_doit",
"vsock_maybe_set_connected",
"vsock_g2h_net_reachable",
"vsock_g2h_reachable_sk",
"vsock_find_cid",
"__vsock_find_cid",
"vhost_vsock_set_cid",
"virtio_transport_recv_connecting",
"virtio_transport_recv_listen"
],
"Reasoning": "The patch series introduces a new Generic Netlink family (\"vsock\") allowing user space (with CAP_NET_ADMIN) to assign the guest-to-host (G2H) vsock device to different network namespaces (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET). It also modifies core AF_VSOCK socket state handling, namespace tracking and reference lifetime, CID resolution under concurrency, and virtio/vhost vsock transport connection lifecycle logic. These changes execute in reachable networking code accessible in standard virtualized environments and should be fuzzed for concurrency, state management, and refcount regressions.",
"WorthFuzzing": true
}Results: {
"EnableConfigs": [
"VSOCKETS",
"VIRTIO_VSOCKETS",
"VHOST_VSOCK"
],
"FocusSymbols": [
"vsock_nl_dev_netns_set_doit",
"vsock_nl_dev_netns_get_doit",
"vsock_maybe_set_connected",
"vsock_g2h_net_reachable",
"vsock_g2h_reachable_sk",
"vsock_find_cid",
"__vsock_find_cid",
"vhost_vsock_set_cid",
"virtio_transport_recv_connecting",
"virtio_transport_recv_listen"
],
"Reasoning": "The patch series introduces a new Generic Netlink family (\"vsock\") allowing user space (with CAP_NET_ADMIN) to assign the guest-to-host (G2H) vsock device to different network namespaces (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET). It also modifies core AF_VSOCK socket state handling, namespace tracking and reference lifetime, CID resolution under concurrency, and virtio/vhost vsock transport connection lifecycle logic. These changes execute in reachable networking code accessible in standard virtualized environments and should be fuzzed for concurrency, state management, and refcount regressions.",
"WorthFuzzing": true
} |
| 13/1 | 2026/11/18 10:11 | action | If |
6mArgs:{
"WorthFuzzing": true
}Results: null |
| 14/2 | 2026/11/18 10:11 | agent | kmsan-evaluator |
6mModel:core Args: null Results: {
"KMSANReasoning": "The patch series introduces a Generic Netlink control interface (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET) and transport reachability checks to support assigning the guest-to-host vsock device to specific network namespaces.\n\nEvaluating KMSAN vs KASAN applicability:\n- Data sent to userspace: In the netlink dump/get path (vsock_nl_dev_netns_fill), the netns ID is sent via nla_put_s32(), which writes a 4-byte scalar value, with netlink attribute alignment padding zeroed by netlink helpers. The local variable 'id' is guaranteed to be initialized when !equal, and is never evaluated when equal is true. Similarly, IOCTL_VM_SOCKETS_GET_LOCAL_CID writes a u32 CID that is unconditionally initialized before put_user(). There are no uninitialized struct fields, padding, or kernel-to-user info-leak risks.\n- Local variables and control flow: All local variables across the new functions (e.g. vsock_nl_dev_netns_set_doit, vsock_g2h_net_assign, vsock_g2h_reset_unreachable, vhost_vsock_set_cid) are fully initialized prior to evaluation.\n- Primary bug risks: The changes introduce complex locking (ordering between vsock_g2h_assign_mutex, vsock_register_mutex, vsock_table_lock, and socket locks), RCU dereferencing of vsock_g2h_net, network namespace reference tracking (get_net_track/put_net_track), and connected socket cleanup logic. Any potential defects here would manifest as deadlocks, race conditions, use-after-free, or refcount imbalances, all of which are covered by LOCKDEP and standard KASAN builds.\n\nTherefore, there are no uninitialized memory risks that justify running a dedicated KMSAN fuzzing session.",
"NeedsKMSAN": false
}Instruction: You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.
CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
a comprehensive suite of debugging tools and sanitizers, including KASAN
(out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
(locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
or page allocations) and kernel-to-user memory info-leaks.
Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.
Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.
Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
attributes, ioctl output arguments, socket options, or BPF buffers) where fields
or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
uninitialized bytes of existing buffers.
Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
dereferences, locking deadlocks, or use-after-free bugs (these are already caught
by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.
Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
Prefer calling several tools at the same time to save round-trips.
Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.
Prompt: Target architecture: amd64
For your convenience, here is the diff of the changes:
commit 190eefd6dcf9994800a722359e674bd7ddd1931e
Author: syz-cluster <triage@syzkaller.com>
Date: Wed Nov 18 10:04:32 2026 +0000
syz-cluster: applied patch under review
diff --git a/Documentation/admin-guide/sysctl/net.rst b/Documentation/admin-guide/sysctl/net.rst
index fe43e85959583e..87bde0fe1ccfc2 100644
--- a/Documentation/admin-guide/sysctl/net.rst
+++ b/Documentation/admin-guide/sysctl/net.rst
@@ -529,6 +529,49 @@ their hosts. The behavior of VSOCK sockets in a network namespace is determined
by the namespace's mode (``global`` or ``local``), which controls how CIDs
(Context IDs) are allocated and how sockets interact across namespaces.
+In a guest, the vsock device owned by the guest-to-host (G2H) transport belongs
+to one network namespace at a time. The ``VSOCK_CMD_DEV_NETNS_SET`` command of
+the ``vsock`` netlink family, described in
+Documentation/netlink/specs/vsock.yaml, moves it to a namespace given by fd or
+PID, or else to the namespace the request was sent from. It requires
+``CAP_NET_ADMIN`` in the initial user namespace.
+The namespace's mode decides who may then use the device:
+
+- ``global`` - every ``global`` mode namespace may use it.
+- ``local`` - only that namespace may use it, which reserves the connection to
+ the host for it alone.
+
+The device starts out in init_net, so until the command is issued nothing has
+moved and no mode has changed.
+
+Support is transport dependent. A G2H transport that does not implement the
+move refuses the command with ``EOPNOTSUPP``. Of the in-tree guest transports,
+only virtio-vsock implements it.
+
+A namespace that cannot reach the device sees the vsock addresses it would see
+if no G2H transport were loaded: the device's CID is not one of its local CIDs,
+and with ``vsock_loopback`` loaded, ``VMADDR_CID_HOST`` (2) is served by
+loopback.
+
+Connections established before the move, from a namespace that can no longer
+reach the device, are closed with ``ECONNRESET``. Nothing is sent to the peer,
+which is what already happens when the device is removed altogether: the peer
+finds out on its next send, which no longer matches a socket and so is answered
+with a reset. A peer that only receives waits for its own timeout. A connection
+still being set up when the device moves is refused with a reset once the peer
+answers it.
+
+An assignment keeps the namespace alive, the same way an open socket does, so
+deleting that namespace does not move the device. Assigning the device to
+another namespace, such as init_net, is the only way to undo an assignment, and
+releases the reference the assignment held on the previous namespace.
+
+The move is refused with ``EADDRINUSE`` if a guest registered in the target
+namespace already answers to the device's CID, since the CID would otherwise
+name two different peers there. If a loaded H2G transport cannot check that,
+the move is refused with ``EOPNOTSUPP``. Of the in-tree host transports, only
+vhost-vsock can.
+
ns_mode
-------
diff --git a/Documentation/netlink/specs/vsock.yaml b/Documentation/netlink/specs/vsock.yaml
new file mode 100644
index 00000000000000..f260ee88b14024
--- /dev/null
+++ b/Documentation/netlink/specs/vsock.yaml
@@ -0,0 +1,89 @@
+# SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+#
+# Copyright (c) 2026 Meta Platforms, Inc. and affiliates
+#
+---
+name: vsock
+
+doc: |
+ Control interface for the vsock (AF_VSOCK) core.
+
+protocol: genetlink
+
+uapi-header: linux/vsock_netlink.h
+
+attribute-sets:
+ -
+ name: vsock
+ attributes:
+ -
+ name: netns-id
+ type: s32
+ doc: |
+ Network namespace the guest's vsock device is assigned to, as an
+ nsid relative to the caller.
+
+ Absent when the device is in the caller's own namespace, and
+ NETNSA_NSID_NOT_ASSIGNED when the g2h transport supports netns
+ assignment and the caller's namespace cannot reach the device under
+ the mode rules, or when no nsid could be allocated for it.
+ -
+ name: netns-fd
+ type: u32
+ doc: |
+ File descriptor of the network namespace to move the guest's vsock
+ device to.
+ -
+ name: netns-pid
+ type: u32
+ doc: |
+ PID of a process in the network namespace to move the guest's vsock
+ device to.
+
+operations:
+ list:
+ -
+ name: dev-netns-set
+ doc: |
+ Set the network namespace of the guest's vsock device.
+
+ The device is moved to the namespace given by netns-fd or netns-pid,
+ or to the namespace the request was sent from if neither is given.
+ It starts out in init_net, and moving it back there is how an
+ assignment is undone.
+
+ A g2h transport that does not support netns assignment returns
+ EOPNOTSUPP. If the netns assignment would cause a CID collision, it
+ is rejected with EADDRINUSE.
+
+ The namespace's mode decides who may then use the device: a global
+ mode namespace shares it with every other global mode namespace,
+ while a local mode namespace reserves it for itself.
+
+ Movement to an unreachable local namespace results in sockets being
+ closed with ECONNRESET. Peers are not guaranteed to be notified via
+ an RST.
+
+ The assignment holds a reference on the namespace.
+ attribute-set: vsock
+ flags: [admin-perm]
+ do:
+ request:
+ attributes:
+ - netns-fd
+ - netns-pid
+ -
+ name: dev-netns-get
+ doc: |
+ Get the network namespace the guest's vsock device is assigned to.
+
+ The namespace is reported as an nsid relative to the caller, so the
+ attribute is absent when the device is already in the caller's own
+ namespace. If the g2h transport supports netns assignment, a caller
+ whose namespace cannot reach the device is told
+ NETNSA_NSID_NOT_ASSIGNED rather than where the device went.
+ attribute-set: vsock
+ do:
+ reply:
+ attributes:
+ - netns-id
diff --git a/MAINTAINERS b/MAINTAINERS
index 7636ab50d44fbe..95c8882669bbbb 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -29169,10 +29169,12 @@ M: Stefano Garzarella <sgarzare@redhat.com>
L: virtualization@lists.linux.dev
L: netdev@vger.kernel.org
S: Maintained
+F: Documentation/netlink/specs/vsock.yaml
F: drivers/net/vsockmon.c
F: include/net/af_vsock.h
F: include/uapi/linux/vm_sockets.h
F: include/uapi/linux/vm_sockets_diag.h
+F: include/uapi/linux/vsock_netlink.h
F: include/uapi/linux/vsockmon.h
F: net/vmw_vsock/
F: tools/testing/selftests/vsock/
diff --git a/drivers/vhost/vsock.c b/drivers/vhost/vsock.c
index abed1fbcf66cc5..1a03cff56c5aa4 100644
--- a/drivers/vhost/vsock.c
+++ b/drivers/vhost/vsock.c
@@ -91,10 +91,8 @@ static struct vhost_vsock *vhost_vsock_get(u32 guest_cid, struct net *net)
return NULL;
}
-static bool vhost_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)
+static bool vhost_transport_has_remote_cid(struct net *net, u32 cid)
{
- struct sock *sk = sk_vsock(vsk);
- struct net *net = sock_net(sk);
bool found;
rcu_read_lock();
@@ -817,6 +815,7 @@ static int vhost_vsock_dev_release(struct inode *inode, struct file *file)
static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
{
struct vhost_vsock *other;
+ int ret;
/* Refuse reserved CIDs */
if (guest_cid <= VMADDR_CID_HOST ||
@@ -830,15 +829,20 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
/* Refuse if CID is assigned to the guest->host transport (i.e. nested
* VM), to make the loopback work.
*/
- if (vsock_find_cid(guest_cid))
- return -EADDRINUSE;
+ vsock_cid_lock();
+
+ if (__vsock_find_cid(vsock->net, guest_cid)) {
+ ret = -EADDRINUSE;
+ goto unlock;
+ }
/* Refuse if CID is already in use */
mutex_lock(&vhost_vsock_mutex);
other = vhost_vsock_get(guest_cid, vsock->net);
if (other && other != vsock) {
mutex_unlock(&vhost_vsock_mutex);
- return -EADDRINUSE;
+ ret = -EADDRINUSE;
+ goto unlock;
}
if (vsock->guest_cid)
@@ -848,7 +852,12 @@ static int vhost_vsock_set_cid(struct vhost_vsock *vsock, u64 guest_cid)
hash_add_rcu(vhost_vsock_hash, &vsock->hash, vsock->guest_cid);
mutex_unlock(&vhost_vsock_mutex);
- return 0;
+ ret = 0;
+
+unlock:
+ vsock_cid_unlock();
+
+ return ret;
}
static int vhost_vsock_set_features(struct vhost_vsock *vsock, u64 features)
diff --git a/include/net/af_vsock.h b/include/net/af_vsock.h
index 5549298c1ec6b3..fa025dd754a1f4 100644
--- a/include/net/af_vsock.h
+++ b/include/net/af_vsock.h
@@ -9,6 +9,7 @@
#define __AF_VSOCK_H__
#include <linux/kernel.h>
+#include <linux/mutex.h>
#include <linux/workqueue.h>
#include <net/netns/vsock.h>
#include <net/sock.h>
@@ -183,13 +184,16 @@ struct vsock_transport {
* CIDs via the hypervisor (i.e. supports the fallback overlay). VMCI
* does not implement this as it only serves CIDs 0 and 2.
*/
- bool (*has_remote_cid)(struct vsock_sock *vsk, u32 remote_cid);
+ bool (*has_remote_cid)(struct net *net, u32 remote_cid);
/* Read a single skb */
int (*read_skb)(struct vsock_sock *, skb_read_actor_t);
/* Zero-copy. */
bool (*msgzerocopy_allow)(void);
+
+ /* True if the G2H transport honours VSOCK_CMD_DEV_NETNS_SET. */
+ bool netns_assign_allow;
};
/**** CORE ****/
@@ -233,11 +237,20 @@ bool vsock_check_source(const struct vsock_sock *vsk,
const struct vsock_transport *transport,
const struct sockaddr_vm *src);
void vsock_remove_sock(struct vsock_sock *vsk);
-void vsock_for_each_connected_socket(struct vsock_transport *transport,
+void vsock_for_each_connected_socket(const struct vsock_transport *transport,
void (*fn)(struct sock *sk));
int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk);
-bool vsock_find_cid(unsigned int cid);
+bool vsock_find_cid(struct net *net, unsigned int cid);
+void vsock_cid_lock(void);
+void vsock_cid_unlock(void);
+/* Caller must hold vsock_cid_lock(). */
+bool __vsock_find_cid(struct net *net, unsigned int cid);
void vsock_linger(struct sock *sk);
+struct net *vsock_g2h_net_get(netns_tracker *tracker);
+bool vsock_g2h_net_eq(const struct net *net);
+bool vsock_g2h_net_reachable(struct net *net);
+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk);
+bool vsock_maybe_set_connected(struct vsock_sock *vsk);
/**** TAP ****/
diff --git a/include/uapi/linux/vsock_netlink.h b/include/uapi/linux/vsock_netlink.h
new file mode 100644
index 00000000000000..c7e23d0da17e19
--- /dev/null
+++ b/include/uapi/linux/vsock_netlink.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN uapi header */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#ifndef _UAPI_LINUX_VSOCK_NETLINK_H
+#define _UAPI_LINUX_VSOCK_NETLINK_H
+
+#define VSOCK_FAMILY_NAME "vsock"
+#define VSOCK_FAMILY_VERSION 1
+
+enum {
+ VSOCK_A_NETNS_ID = 1,
+ VSOCK_A_NETNS_FD,
+ VSOCK_A_NETNS_PID,
+
+ __VSOCK_A_MAX,
+ VSOCK_A_MAX = (__VSOCK_A_MAX - 1)
+};
+
+enum {
+ VSOCK_CMD_DEV_NETNS_SET = 1,
+ VSOCK_CMD_DEV_NETNS_GET,
+
+ __VSOCK_CMD_MAX,
+ VSOCK_CMD_MAX = (__VSOCK_CMD_MAX - 1)
+};
+
+#endif /* _UAPI_LINUX_VSOCK_NETLINK_H */
diff --git a/net/vmw_vsock/Makefile b/net/vmw_vsock/Makefile
index 5da74c4a9f1d1b..97e2a559e2bf3d 100644
--- a/net/vmw_vsock/Makefile
+++ b/net/vmw_vsock/Makefile
@@ -7,7 +7,7 @@ obj-$(CONFIG_VIRTIO_VSOCKETS_COMMON) += vmw_vsock_virtio_transport_common.o
obj-$(CONFIG_HYPERV_VSOCKETS) += hv_sock.o
obj-$(CONFIG_VSOCKETS_LOOPBACK) += vsock_loopback.o
-vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o
+vsock-y += af_vsock.o af_vsock_tap.o vsock_addr.o vsock_nl_gen.o
vsock-$(CONFIG_BPF_SYSCALL) += vsock_bpf.o
vsock_diag-y += diag.o
diff --git a/net/vmw_vsock/af_vsock.c b/net/vmw_vsock/af_vsock.c
index 483af15a5109eb..3bc9eee8ad9daf 100644
--- a/net/vmw_vsock/af_vsock.c
+++ b/net/vmw_vsock/af_vsock.c
@@ -130,6 +130,27 @@
* a different transport that *does* support local mode. For
* example, virtio-vsock may not support local mode, but the socket
* may still accept a connection from vhost-vsock which does.
+ *
+ * - A guest has a single vsock device, owned by the guest->host transport.
+ * The VSOCK_CMD_DEV_NETNS_SET netlink command moves it to a namespace given
+ * by fd or PID, or else to the one the request was sent from. It starts
+ * out in init_net. The mode rules then decide who may use it, and which
+ * namespace packets from the host are delivered to:
+ *
+ * - assigned to a global mode namespace - every global mode namespace may
+ * use it. Until the command is issued nothing has moved and no mode has
+ * changed, so the default is the behaviour that predates it.
+ * - assigned to a local mode namespace - only that namespace may use it.
+ * This is how a nested VM is isolated from the rest of the guest.
+ *
+ * Connections made before an assignment, from a namespace that can no
+ * longer reach the device, are closed with ECONNRESET. Nothing is sent to
+ * the peer. As with device removal, it finds out on its next send.
+ *
+ * The assignment holds a reference on the namespace, the way an open socket
+ * does, so deleting that namespace does not move the device: its destruction
+ * is deferred until the device moves to another namespace, on another
+ * assignment or when the transport unregisters.
*/
#include <linux/compat.h>
@@ -161,10 +182,14 @@
#include <linux/workqueue.h>
#include <net/sock.h>
#include <net/af_vsock.h>
+#include <linux/net_namespace.h>
+#include <net/genetlink.h>
#include <net/netns/vsock.h>
#include <uapi/linux/vm_sockets.h>
#include <uapi/asm-generic/ioctls.h>
+#include "vsock_nl_gen.h"
+
#define VSOCK_NET_MODE_STR_GLOBAL "global"
#define VSOCK_NET_MODE_STR_LOCAL "local"
@@ -206,8 +231,21 @@ static const struct vsock_transport *transport_g2h;
static const struct vsock_transport *transport_dgram;
/* Transport used for local communication */
static const struct vsock_transport *transport_local;
+/* Protects transport registration and the g2h device's netns. */
static DEFINE_MUTEX(vsock_register_mutex);
+/* Network namespace of the g2h device. Protected by
+ * vsock_register_mutex/RCU.
+ */
+static struct net __rcu *vsock_g2h_net = RCU_INITIALIZER(&init_net);
+static netns_tracker vsock_g2h_net_tracker;
+
+/* Held across an assign's swap and reset sweep, so that a later assign cannot
+ * move the device back before the sweep has closed every socket that lost it.
+ * Must be taken before vsock_register_mutex.
+ */
+static DEFINE_MUTEX(vsock_g2h_assign_mutex);
+
/**** UTILS ****/
/* Each bound VSocket is stored in the bind hash table and each connected
@@ -480,7 +518,7 @@ void vsock_remove_sock(struct vsock_sock *vsk)
}
EXPORT_SYMBOL_GPL(vsock_remove_sock);
-void vsock_for_each_connected_socket(struct vsock_transport *transport,
+void vsock_for_each_connected_socket(const struct vsock_transport *transport,
void (*fn)(struct sock *sk))
{
int i;
@@ -502,6 +540,37 @@ void vsock_for_each_connected_socket(struct vsock_transport *transport,
}
EXPORT_SYMBOL_GPL(vsock_for_each_connected_socket);
+/* Return the next connected socket of @transport that @match accepts, with a
+ * reference held. The scan starts at bucket *@bucket and leaves it where it
+ * stopped, so calling again resumes there. Unlike
+ * vsock_for_each_connected_socket(), the caller acts on the socket after
+ * vsock_table_lock is dropped, so it can take lock_sock().
+ */
+static struct sock *
+vsock_next_connected_socket(const struct vsock_transport *transport,
+ unsigned int *bucket,
+ bool (*match)(struct vsock_sock *vsk))
+{
+ struct vsock_sock *vsk;
+
+ spin_lock_bh(&vsock_table_lock);
+
+ for (; *bucket < ARRAY_SIZE(vsock_connected_table); (*bucket)++) {
+ list_for_each_entry(vsk, &vsock_connected_table[*bucket],
+ connected_table) {
+ if (vsk->transport == transport && match(vsk)) {
+ sock_hold(sk_vsock(vsk));
+ spin_unlock_bh(&vsock_table_lock);
+ return sk_vsock(vsk);
+ }
+ }
+ }
+
+ spin_unlock_bh(&vsock_table_lock);
+
+ return NULL;
+}
+
void vsock_add_pending(struct sock *listener, struct sock *pending)
{
struct vsock_sock *vlistener;
@@ -553,7 +622,42 @@ void vsock_enqueue_accept(struct sock *listener, struct sock *connected)
}
EXPORT_SYMBOL_GPL(vsock_enqueue_accept);
-static bool vsock_use_local_transport(unsigned int remote_cid)
+/* Return true if @t honours namespace assignment. One that does not keeps the
+ * reachability rules it had before VSOCK_CMD_DEV_NETNS_SET existed.
+ */
+static bool vsock_net_assignable(const struct vsock_transport *t)
+{
+ return t && t->netns_assign_allow;
+}
+
+static bool vsock_g2h_unreachable(const struct vsock_transport *t,
+ struct net *net)
+{
+ return t == transport_g2h && vsock_net_assignable(t) &&
+ !vsock_g2h_net_reachable(net);
+}
+
+/* Return the CID of the transport in @transport, as seen from @net.
+ *
+ * Returns VMADDR_CID_ANY if the transport supports net assignment but is not
+ * reachable from the net.
+ */
+static u32
+__vsock_registered_transport_cid(const struct vsock_transport **transport,
+ struct net *net)
+{
+ lockdep_assert_held(&vsock_register_mutex);
+
+ if (!*transport)
+ return VMADDR_CID_ANY;
+
+ if (vsock_g2h_unreachable(*transport, net))
+ return VMADDR_CID_ANY;
+
+ return (*transport)->get_local_cid();
+}
+
+static bool vsock_use_local_transport(struct net *net, unsigned int remote_cid)
{
lockdep_assert_held(&vsock_register_mutex);
@@ -563,11 +667,10 @@ static bool vsock_use_local_transport(unsigned int remote_cid)
if (remote_cid == VMADDR_CID_LOCAL)
return true;
- if (transport_g2h) {
+ if (transport_g2h && !vsock_g2h_unreachable(transport_g2h, net))
return remote_cid == transport_g2h->get_local_cid();
- } else {
- return remote_cid == VMADDR_CID_HOST;
- }
+
+ return remote_cid == VMADDR_CID_HOST;
}
static void vsock_deassign_transport(struct vsock_sock *vsk)
@@ -626,18 +729,20 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
break;
case SOCK_STREAM:
case SOCK_SEQPACKET:
- if (vsock_use_local_transport(remote_cid))
+ if (vsock_use_local_transport(sock_net(sk), remote_cid))
new_transport = transport_local;
else if (remote_cid <= VMADDR_CID_HOST ||
(remote_flags & VMADDR_FLAG_TO_HOST))
new_transport = transport_g2h;
else if (transport_h2g &&
(!transport_h2g->has_remote_cid ||
- transport_h2g->has_remote_cid(vsk, remote_cid)))
+ transport_h2g->has_remote_cid(sock_net(sk),
+ remote_cid)))
new_transport = transport_h2g;
else if (sock_net(sk)->vsock.g2h_fallback &&
transport_g2h && transport_g2h->has_remote_cid &&
- transport_g2h->has_remote_cid(vsk, remote_cid)) {
+ transport_g2h->has_remote_cid(sock_net(sk),
+ remote_cid)) {
vsk->remote_addr.svm_flags |= VMADDR_FLAG_TO_HOST;
new_transport = transport_g2h;
} else {
@@ -649,6 +754,11 @@ int vsock_assign_transport(struct vsock_sock *vsk, struct vsock_sock *psk)
goto err;
}
+ if (vsock_g2h_unreachable(new_transport, sock_net(sk))) {
+ ret = -ENETUNREACH;
+ goto err;
+ }
+
if (vsk->transport && vsk->transport == new_transport) {
ret = 0;
goto err;
@@ -715,21 +825,39 @@ EXPORT_SYMBOL_GPL(vsock_assign_transport);
* Provide safe access to static transport_{h2g,g2h,dgram,local} callbacks.
* Otherwise we may race with module removal. Do not use on `vsk->transport`.
*/
-static u32 vsock_registered_transport_cid(const struct vsock_transport **transport)
+static u32
+vsock_registered_transport_cid(const struct vsock_transport **transport,
+ struct net *net)
{
- u32 cid = VMADDR_CID_ANY;
+ u32 cid;
mutex_lock(&vsock_register_mutex);
- if (*transport)
- cid = (*transport)->get_local_cid();
+ cid = __vsock_registered_transport_cid(transport, net);
mutex_unlock(&vsock_register_mutex);
return cid;
}
-bool vsock_find_cid(unsigned int cid)
+/* Keep the CIDs checked by __vsock_find_cid() stable: transport registration
+ * and g2h device netns assignment both wait for vsock_cid_unlock().
+ */
+void vsock_cid_lock(void)
+{
+ mutex_lock(&vsock_register_mutex);
+}
+EXPORT_SYMBOL_GPL(vsock_cid_lock);
+
+void vsock_cid_unlock(void)
+{
+ mutex_unlock(&vsock_register_mutex);
+}
+EXPORT_SYMBOL_GPL(vsock_cid_unlock);
+
+bool __vsock_find_cid(struct net *net, unsigned int cid)
{
- if (cid == vsock_registered_transport_cid(&transport_g2h))
+ lockdep_assert_held(&vsock_register_mutex);
+
+ if (cid == __vsock_registered_transport_cid(&transport_g2h, net))
return true;
if (transport_h2g && cid == VMADDR_CID_HOST)
@@ -740,8 +868,273 @@ bool vsock_find_cid(unsigned int cid)
return false;
}
+EXPORT_SYMBOL_GPL(__vsock_find_cid);
+
+bool vsock_find_cid(struct net *net, unsigned int cid)
+{
+ bool found;
+
+ mutex_lock(&vsock_register_mutex);
+ found = __vsock_find_cid(net, cid);
+ mutex_unlock(&vsock_register_mutex);
+
+ return found;
+}
EXPORT_SYMBOL_GPL(vsock_find_cid);
+/* Return the namespace the g2h device is assigned to, with a reference held.
+ *
+ * The assignment itself holds a reference, so the namespace cannot be going
+ * away here and this never fails.
+ */
+struct net *vsock_g2h_net_get(netns_tracker *tracker)
+{
+ struct net *net;
+
+ rcu_read_lock();
+ net = rcu_dereference(vsock_g2h_net);
+ get_net_track(net, tracker, GFP_ATOMIC);
+ rcu_read_unlock();
+
+ return net;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_get);
+
+/* True if @net is still the namespace the device is assigned to. Cheap enough
+ * to call per packet on the RX path.
+ */
+bool vsock_g2h_net_eq(const struct net *net)
+{
+ return rcu_access_pointer(vsock_g2h_net) == net;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_eq);
+
+bool vsock_g2h_net_reachable(struct net *net)
+{
+ bool reachable;
+
+ rcu_read_lock();
+ reachable = vsock_net_check_mode(net, rcu_dereference(vsock_g2h_net));
+ rcu_read_unlock();
+
+ return reachable;
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_net_reachable);
+
+/* True if @vsk can reach the g2h device, or its transport ignores namespace
+ * assignment.
+ */
+bool vsock_g2h_reachable_sk(struct vsock_sock *vsk)
+{
+ if (!vsock_net_assignable(vsk->transport))
+ return true;
+
+ return vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));
+}
+EXPORT_SYMBOL_GPL(vsock_g2h_reachable_sk);
+
+/* Move @vsk to TCP_ESTABLISHED and into the connected table, unless the device
+ * has moved to a namespace @vsk cannot reach. Returns false without doing
+ * either in that case.
+ *
+ * The reset sweep walks the same table under the same lock, so an assign
+ * cannot land between the check and the insert: either the sweep finds @vsk
+ * and closes it, or @vsk is never added.
+ */
+bool vsock_maybe_set_connected(struct vsock_sock *vsk)
+{
+ struct list_head *list;
+ bool reachable;
+
+ list = vsock_connected_sockets(&vsk->remote_addr, &vsk->local_addr);
+
+ spin_lock_bh(&vsock_table_lock);
+ reachable = vsock_g2h_reachable_sk(vsk);
+ if (reachable) {
+ sk_vsock(vsk)->sk_state = TCP_ESTABLISHED;
+ __vsock_insert_connected(list, vsk);
+ }
+ spin_unlock_bh(&vsock_table_lock);
+
+ return reachable;
+}
+EXPORT_SYMBOL_GPL(vsock_maybe_set_connected);
+
+static bool vsock_g2h_should_reset(struct vsock_sock *vsk)
+{
+ return READ_ONCE(sk_vsock(vsk)->sk_state) != TCP_CLOSE &&
+ !READ_ONCE(vsk->close_work_scheduled) &&
+ !vsock_g2h_reachable_sk(vsk);
+}
+
+/* Close every connected socket of @t that can no longer reach the g2h device.
+ */
+static void vsock_g2h_reset_unreachable(const struct vsock_transport *t)
+{
+ struct vsock_sock *vsk;
+ unsigned int i = 0;
+ struct sock *sk;
+ bool reset;
+
+ lockdep_assert_held(&vsock_g2h_assign_mutex);
+ lockdep_assert_not_held(&vsock_register_mutex);
+
+ /* lock_sock() cannot be taken under vsock_table_lock, so pick the
+ * sockets one at a time, then recheck each under both locks.
+ */
+ while ((sk = vsock_next_connected_socket(t, &i,
+ vsock_g2h_should_reset))) {
+ vsk = vsock_sk(sk);
+
+ lock_sock(sk);
+
+ reset = false;
+ spin_lock_bh(&vsock_table_lock);
+ /* It may have been closed since we dropped the table lock. */
+ if (__vsock_in_connected_table(vsk) && vsk->transport == t &&
+ vsock_g2h_should_reset(vsk)) {
+ __vsock_remove_connected(vsk);
+ reset = true;
+ }
+ spin_unlock_bh(&vsock_table_lock);
+
+ if (reset) {
+ sock_set_flag(sk, SOCK_DONE);
+ WRITE_ONCE(vsk->peer_shutdown, SHUTDOWN_MASK);
+ sk->sk_state = TCP_CLOSING;
+ sk->sk_err = ECONNRESET;
+ sk_error_report(sk);
+ }
+
+ release_sock(sk);
+ sock_put(sk);
+ }
+}
+
+/* Point the g2h device at @net, taking the reference that keeps @net alive,
+ * and return the namespace it leaves behind.
+ */
+static struct net *vsock_g2h_net_swap(struct net *net, netns_tracker *old)
+{
+ lockdep_assert_held(&vsock_register_mutex);
+
+ *old = vsock_g2h_net_tracker;
+ get_net_track(net, &vsock_g2h_net_tracker, GFP_KERNEL);
+
+ return rcu_replace_pointer(vsock_g2h_net, net,
+ lockdep_is_held(&vsock_register_mutex));
+}
+
+/* Drop the namespace the device just left, once the readers that may still
+ * see it in vsock_g2h_net_get() are gone. Runs without the mutex held.
+ */
+static void vsock_g2h_net_release(struct net *old, netns_tracker *tracker)
+{
+ synchronize_rcu();
+ put_net_track(old, tracker);
+}
+
+static int vsock_nl_dev_netns_fill(struct sk_buff *msg, struct genl_info *info)
+{
+ struct net *net = genl_info_net(info);
+ struct net *g2h;
+ bool equal;
+ void *hdr;
+ s32 id;
+
+ g2h = rcu_dereference_protected(vsock_g2h_net,
+ lockdep_is_held(&vsock_register_mutex));
+ equal = net_eq(net, g2h);
+ if (!equal) {
+ if (vsock_net_assignable(transport_g2h) &&
+ !vsock_net_check_mode(net, g2h))
+ id = NETNSA_NSID_NOT_ASSIGNED;
+ else
+ id = peernet2id_alloc(net, g2h, GFP_KERNEL);
+ }
+
+ hdr = genlmsg_iput(msg, info);
+ if (!hdr)
+ return -EMSGSIZE;
+
+ if (!equal && nla_put_s32(msg, VSOCK_A_NETNS_ID, id)) {
+ genlmsg_cancel(msg, hdr);
+ return -EMSGSIZE;
+ }
+
+ genlmsg_end(msg, hdr);
+
+ return 0;
+}
+
+/* Move the g2h device to @net, which keeps @net alive until the device leaves
+ * again. Returns -ENODEV if no g2h transport is loaded, -EOPNOTSUPP if the
+ * loaded one cannot be moved, and -EADDRINUSE if a guest in @net already uses
+ * the device's CID.
+ */
+static int vsock_g2h_net_assign(struct net *net,
+ struct netlink_ext_ack *extack)
+{
+ const struct vsock_transport *t;
+ netns_tracker old_tracker;
+ struct net *old;
+ int ret;
+
+ /* See vsock_g2h_assign_mutex for the lock ordering. */
+ mutex_lock(&vsock_g2h_assign_mutex);
+ mutex_lock(&vsock_register_mutex);
+
+ ret = -ENODEV;
+ if (!transport_g2h) {
+ NL_SET_ERR_MSG(extack, "no guest-to-host transport is loaded");
+ goto unlock;
+ }
+
+ ret = -EOPNOTSUPP;
+ if (!vsock_net_assignable(transport_g2h)) {
+ NL_SET_ERR_MSG(extack,
+ "the loaded guest-to-host transport does not support namespace assignment");
+ goto unlock;
+ }
+
+ if (transport_h2g && !transport_h2g->has_remote_cid) {
+ NL_SET_ERR_MSG(extack,
+ "the loaded host-to-guest transport cannot check the device's CID");
+ goto unlock;
+ }
+
+ ret = -EADDRINUSE;
+ if (transport_h2g &&
+ transport_h2g->has_remote_cid(net,
+ transport_g2h->get_local_cid())) {
+ NL_SET_ERR_MSG(extack,
+ "a guest in the target namespace already uses the device's CID");
+ goto unlock;
+ }
+
+ old = vsock_g2h_net_swap(net, &old_tracker);
+ t = transport_g2h;
+
+ mutex_unlock(&vsock_register_mutex);
+
+ /* See vsock_maybe_set_connected() comment about synchronizing with
+ * connecting sockets.
+ */
+ vsock_g2h_reset_unreachable(t);
+
+ mutex_unlock(&vsock_g2h_assign_mutex);
+
+ vsock_g2h_net_release(old, &old_tracker);
+
+ return 0;
+
+unlock:
+ mutex_unlock(&vsock_register_mutex);
+ mutex_unlock(&vsock_g2h_assign_mutex);
+
+ return ret;
+}
+
static struct sock *vsock_dequeue_accept(struct sock *listener)
{
struct vsock_sock *vlistener;
@@ -908,7 +1301,8 @@ static int __vsock_bind(struct sock *sk, struct sockaddr_vm *addr)
* like AF_INET prevents binding to a non-local IP address (in most
* cases), we only allow binding to a local CID.
*/
- if (addr->svm_cid != VMADDR_CID_ANY && !vsock_find_cid(addr->svm_cid))
+ if (addr->svm_cid != VMADDR_CID_ANY &&
+ !vsock_find_cid(sock_net(sk_vsock(vsk)), addr->svm_cid))
return -EADDRNOTAVAIL;
switch (sk->sk_socket->type) {
@@ -1703,6 +2097,16 @@ static void vsock_connect_timeout(struct work_struct *work)
sock_put(sk);
}
+/* Avoid breaking the socket when another thread has changed its sock->state
+ * while we were asleep.
+ */
+static void vsock_connect_close(struct socket *sock)
+{
+ sock->sk->sk_state = TCP_CLOSE;
+ if (sock->state == SS_CONNECTING)
+ sock->state = SS_UNCONNECTED;
+}
+
static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
int addr_len, int flags)
{
@@ -1861,8 +2265,7 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
* sk_state == TCP_SYN_SENT, which hereby we break.
* In such case VIRTIO_VSOCK_OP_RST will follow.
*/
- sk->sk_state = TCP_CLOSE;
- sock->state = SS_UNCONNECTED;
+ vsock_connect_close(sock);
/* Try to cancel VIRTIO_VSOCK_OP_REQUEST skb sent out by
* transport->connect().
@@ -1876,10 +2279,8 @@ static int vsock_connect(struct socket *sock, struct sockaddr_unsized *addr,
}
err = sock_error(sk);
- if (err) {
- sk->sk_state = TCP_CLOSE;
- sock->state = SS_UNCONNECTED;
- }
+ if (err)
+ vsock_connect_close(sock);
out_wait:
finish_wait(sk_sleep(sk), &wait);
@@ -2795,6 +3196,7 @@ static long vsock_dev_do_ioctl(struct file *filp,
unsigned int cmd, void __user *ptr)
{
u32 __user *p = ptr;
+ struct net *net;
int retval = 0;
u32 cid;
@@ -2803,11 +3205,14 @@ static long vsock_dev_do_ioctl(struct file *filp,
/* To be compatible with the VMCI behavior, we prioritize the
* guest CID instead of well-know host CID (VMADDR_CID_HOST).
*/
- cid = vsock_registered_transport_cid(&transport_g2h);
+ net = current->nsproxy->net_ns;
+ cid = vsock_registered_transport_cid(&transport_g2h, net);
if (cid == VMADDR_CID_ANY)
- cid = vsock_registered_transport_cid(&transport_h2g);
+ cid = vsock_registered_transport_cid(&transport_h2g,
+ net);
if (cid == VMADDR_CID_ANY)
- cid = vsock_registered_transport_cid(&transport_local);
+ cid = vsock_registered_transport_cid(&transport_local,
+ net);
if (put_user(cid, p) != 0)
retval = -EFAULT;
@@ -2848,6 +3253,63 @@ static struct miscdevice vsock_device = {
.fops = &vsock_device_ops,
};
+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info)
+{
+ struct sk_buff *msg;
+ int err;
+
+ msg = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
+ if (!msg)
+ return -ENOMEM;
+
+ mutex_lock(&vsock_register_mutex);
+ if (transport_g2h) {
+ err = vsock_nl_dev_netns_fill(msg, info);
+ } else {
+ NL_SET_ERR_MSG(info->extack,
+ "no guest-to-host transport is loaded");
+ err = -ENODEV;
+ }
+ mutex_unlock(&vsock_register_mutex);
+
+ if (err) {
+ nlmsg_free(msg);
+ return err;
+ }
+
+ return genlmsg_reply(msg, info);
+}
+
+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info)
+{
+ struct nlattr *pid_attr = info->attrs[VSOCK_A_NETNS_PID];
+ struct nlattr *fd_attr = info->attrs[VSOCK_A_NETNS_FD];
+ struct net *net;
+ int err;
+
+ if (fd_attr && pid_attr) {
+ NL_SET_ERR_MSG(info->extack,
+ "netns-fd and netns-pid are mutually exclusive");
+ return -EINVAL;
+ }
+
+ if (fd_attr)
+ net = get_net_ns_by_fd(nla_get_u32(fd_attr));
+ else if (pid_attr)
+ net = get_net_ns_by_pid(nla_get_u32(pid_attr));
+ else
+ net = get_net(genl_info_net(info));
+ if (IS_ERR(net)) {
+ NL_SET_BAD_ATTR(info->extack, fd_attr ?: pid_attr);
+ return PTR_ERR(net);
+ }
+
+ err = vsock_g2h_net_assign(net, info->extack);
+ put_net(net);
+
+ return err;
+}
+
static int __vsock_net_mode_string(const struct ctl_table *table, int write,
void *buffer, size_t *lenp, loff_t *ppos,
enum vsock_net_mode mode,
@@ -3037,7 +3499,7 @@ static void vsock_net_init(struct net *net)
net->vsock.g2h_fallback = 1;
}
-static __net_init int vsock_sysctl_init_net(struct net *net)
+static __net_init int vsock_pernet_init(struct net *net)
{
vsock_net_init(net);
@@ -3047,14 +3509,14 @@ static __net_init int vsock_sysctl_init_net(struct net *net)
return 0;
}
-static __net_exit void vsock_sysctl_exit_net(struct net *net)
+static __net_exit void vsock_pernet_exit(struct net *net)
{
vsock_sysctl_unregister(net);
}
-static struct pernet_operations vsock_sysctl_ops = {
- .init = vsock_sysctl_init_net,
- .exit = vsock_sysctl_exit_net,
+static struct pernet_operations vsock_pernet_ops = {
+ .init = vsock_pernet_init,
+ .exit = vsock_pernet_exit,
};
static int __init vsock_init(void)
@@ -3063,6 +3525,8 @@ static int __init vsock_init(void)
vsock_init_tables();
+ get_net_track(&init_net, &vsock_g2h_net_tracker, GFP_KERNEL);
+
vsock_proto.owner = THIS_MODULE;
vsock_device.minor = MISC_DYNAMIC_MINOR;
err = misc_register(&vsock_device);
@@ -3084,15 +3548,23 @@ static int __init vsock_init(void)
goto err_unregister_proto;
}
- if (register_pernet_subsys(&vsock_sysctl_ops)) {
+ if (register_pernet_subsys(&vsock_pernet_ops)) {
err = -ENOMEM;
goto err_unregister_sock;
}
+ err = genl_register_family(&vsock_nl_family);
+ if (err) {
+ pr_err("Cannot register vsock netlink family: %d\n", err);
+ goto err_unregister_pernet;
+ }
+
vsock_bpf_build_proto();
return 0;
+err_unregister_pernet:
+ unregister_pernet_subsys(&vsock_pernet_ops);
err_unregister_sock:
sock_unregister(AF_VSOCK);
err_unregister_proto:
@@ -3100,15 +3572,20 @@ static int __init vsock_init(void)
err_deregister_misc:
misc_deregister(&vsock_device);
err_reset_transport:
+ put_net_track(&init_net, &vsock_g2h_net_tracker);
return err;
}
static void __exit vsock_exit(void)
{
+ genl_unregister_family(&vsock_nl_family);
misc_deregister(&vsock_device);
sock_unregister(AF_VSOCK);
proto_unregister(&vsock_proto);
- unregister_pernet_subsys(&vsock_sysctl_ops);
+ unregister_pernet_subsys(&vsock_pernet_ops);
+
+ put_net_track(rcu_dereference_protected(vsock_g2h_net, true),
+ &vsock_g2h_net_tracker);
}
const struct vsock_transport *vsock_core_get_transport(struct vsock_sock *vsk)
@@ -3175,13 +3652,18 @@ EXPORT_SYMBOL_GPL(vsock_core_register);
void vsock_core_unregister(const struct vsock_transport *t)
{
+ netns_tracker old_tracker;
+ struct net *old = NULL;
+
mutex_lock(&vsock_register_mutex);
if (transport_h2g == t)
transport_h2g = NULL;
- if (transport_g2h == t)
+ if (transport_g2h == t) {
transport_g2h = NULL;
+ old = vsock_g2h_net_swap(&init_net, &old_tracker);
+ }
if (transport_dgram == t)
transport_dgram = NULL;
@@ -3190,6 +3672,10 @@ void vsock_core_unregister(const struct vsock_transport *t)
transport_local = NULL;
mutex_unlock(&vsock_register_mutex);
+
+ /* The device is gone, so release the namespace it was holding. */
+ if (old)
+ vsock_g2h_net_release(old, &old_tracker);
}
EXPORT_SYMBOL_GPL(vsock_core_unregister);
diff --git a/net/vmw_vsock/virtio_transport.c b/net/vmw_vsock/virtio_transport.c
index 4f9aa9c4c3aa59..4123924536dd64 100644
--- a/net/vmw_vsock/virtio_transport.c
+++ b/net/vmw_vsock/virtio_transport.c
@@ -542,13 +542,13 @@ static bool virtio_transport_msgzerocopy_allow(void)
bool virtio_transport_stream_allow(struct vsock_sock *vsk, u32 cid, u32 port)
{
- return vsock_net_mode_global(vsk);
+ return vsock_g2h_net_reachable(sock_net(sk_vsock(vsk)));
}
static bool virtio_transport_seqpacket_allow(struct vsock_sock *vsk,
u32 remote_cid);
-static bool virtio_transport_has_remote_cid(struct vsock_sock *vsk, u32 cid)
+static bool virtio_transport_has_remote_cid(struct net *net, u32 cid)
{
/* The CID could be implemented by the host. Always assume it is. */
return true;
@@ -587,6 +587,7 @@ static struct virtio_transport virtio_transport = {
.seqpacket_has_data = virtio_transport_seqpacket_has_data,
.msgzerocopy_allow = virtio_transport_msgzerocopy_allow,
+ .netns_assign_allow = true,
.notify_poll_in = virtio_transport_notify_poll_in,
.notify_poll_out = virtio_transport_notify_poll_out,
@@ -616,7 +617,7 @@ virtio_transport_seqpacket_allow(struct vsock_sock *vsk, u32 remote_cid)
struct virtio_vsock *vsock;
bool seqpacket_allow;
- if (!vsock_net_mode_global(vsk))
+ if (!vsock_g2h_net_reachable(sock_net(sk_vsock(vsk))))
return false;
seqpacket_allow = false;
@@ -633,7 +634,12 @@ static void virtio_transport_rx_work(struct work_struct *work)
{
struct virtio_vsock *vsock =
container_of(work, struct virtio_vsock, rx_work);
+ struct virtio_transport *t = &virtio_transport;
+ netns_tracker ns_tracker;
struct virtqueue *vq;
+ struct net *net;
+
+ net = vsock_g2h_net_get(&ns_tracker);
mutex_lock(&vsock->rx_lock);
@@ -682,10 +688,15 @@ static void virtio_transport_rx_work(struct work_struct *work)
virtio_transport_deliver_tap_pkt(skb);
- /* Force virtio-transport into global mode since it
- * does not yet support local-mode namespacing.
+ /* Only grab a reference if the net changes underneath
+ * us.
*/
- virtio_transport_recv_pkt(&virtio_transport, skb, NULL);
+ if (unlikely(!vsock_g2h_net_eq(net))) {
+ put_net_track(net, &ns_tracker);
+ net = vsock_g2h_net_get(&ns_tracker);
+ }
+
+ virtio_transport_recv_pkt(t, skb, net);
}
} while (!virtqueue_enable_cb(vq));
@@ -694,6 +705,8 @@ static void virtio_transport_rx_work(struct work_struct *work)
virtio_vsock_rx_fill(vsock);
out_nofill:
mutex_unlock(&vsock->rx_lock);
+
+ put_net_track(net, &ns_tracker);
}
static int virtio_vsock_vqs_init(struct virtio_vsock *vsock)
diff --git a/net/vmw_vsock/virtio_transport_common.c b/net/vmw_vsock/virtio_transport_common.c
index 1e762a480df490..c1cbe834e4f59d 100644
--- a/net/vmw_vsock/virtio_transport_common.c
+++ b/net/vmw_vsock/virtio_transport_common.c
@@ -295,6 +295,9 @@ static struct sk_buff *virtio_transport_alloc_skb(struct virtio_vsock_pkt_info *
* since a socket assigned to a transport is required.
*
* Do not use on listener sockets!
+ *
+ * This checks that the socket can reach the g2h device, so device-only replies
+ * such as virtio_transport_reset_no_sock() must keep not using this path.
*/
static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,
struct virtio_vsock_pkt_info *info)
@@ -317,6 +320,9 @@ static int virtio_transport_send_pkt_info(struct vsock_sock *vsk,
if (unlikely(!t_ops))
return -EFAULT;
+ if (!vsock_g2h_reachable_sk(vsk))
+ return -ENETUNREACH;
+
src_cid = t_ops->transport.get_local_cid();
src_port = vsk->local_addr.svm_port;
if (!info->remote_cid) {
@@ -1468,8 +1474,8 @@ void virtio_transport_release(struct vsock_sock *vsk)
EXPORT_SYMBOL_GPL(virtio_transport_release);
static int
-virtio_transport_recv_connecting(struct sock *sk,
- struct sk_buff *skb)
+virtio_transport_recv_connecting(struct sock *sk, struct sk_buff *skb,
+ struct virtio_transport *t)
{
struct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);
struct vsock_sock *vsk = vsock_sk(sk);
@@ -1478,9 +1484,18 @@ virtio_transport_recv_connecting(struct sock *sk,
switch (le16_to_cpu(hdr->op)) {
case VIRTIO_VSOCK_OP_RESPONSE:
- sk->sk_state = TCP_ESTABLISHED;
+ if (!vsock_maybe_set_connected(vsk)) {
+ /* The net arg is required but unused: only g2h can fail
+ * vsock_maybe_set_connected(), and g2h
+ * virtio_transport_reset_no_sock() ignores the net arg.
+ */
+ virtio_transport_reset_no_sock(t, skb, sock_net(sk));
+ skerr = ECONNRESET;
+ err = -ENETUNREACH;
+ goto close;
+ }
+
sk->sk_socket->state = SS_CONNECTED;
- vsock_insert_connected(vsk);
sk->sk_state_change(sk);
break;
case VIRTIO_VSOCK_OP_INVALID:
@@ -1498,6 +1513,7 @@ virtio_transport_recv_connecting(struct sock *sk,
destroy:
virtio_transport_reset(vsk, skb);
+close:
sk->sk_state = TCP_CLOSE;
sk->sk_err = skerr;
sk_error_report(sk);
@@ -1736,8 +1752,6 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,
lock_sock_nested(child, SINGLE_DEPTH_NESTING);
- child->sk_state = TCP_ESTABLISHED;
-
vchild = vsock_sk(child);
vsock_addr_init(&vchild->local_addr, le64_to_cpu(hdr->dst_cid),
le32_to_cpu(hdr->dst_port));
@@ -1758,7 +1772,14 @@ virtio_transport_recv_listen(struct sock *sk, struct sk_buff *skb,
if (virtio_transport_space_update(child, skb))
child->sk_write_space(child);
- vsock_insert_connected(vchild);
+ if (!vsock_maybe_set_connected(vchild)) {
+ release_sock(child);
+ /* Only reached for g2h, whose send_pkt() ignores the netns. */
+ virtio_transport_reset_no_sock(t, skb, sock_net(sk));
+ sock_put(child);
+ return -ENETUNREACH;
+ }
+
vsock_enqueue_accept(sk, child);
virtio_transport_send_response(vchild, skb);
@@ -1859,7 +1880,7 @@ void virtio_transport_recv_pkt(struct virtio_transport *t,
kfree_skb(skb);
break;
case TCP_SYN_SENT:
- virtio_transport_recv_connecting(sk, skb);
+ virtio_transport_recv_connecting(sk, skb, t);
kfree_skb(skb);
break;
case TCP_ESTABLISHED:
diff --git a/net/vmw_vsock/vsock_nl_gen.c b/net/vmw_vsock/vsock_nl_gen.c
new file mode 100644
index 00000000000000..18f3d47e723d4c
--- /dev/null
+++ b/net/vmw_vsock/vsock_nl_gen.c
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause)
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN kernel source */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#include <net/netlink.h>
+#include <net/genetlink.h>
+
+#include "vsock_nl_gen.h"
+
+#include <uapi/linux/vsock_netlink.h>
+
+/* VSOCK_CMD_DEV_NETNS_SET - do */
+static const struct nla_policy vsock_dev_netns_set_nl_policy[VSOCK_A_NETNS_PID + 1] = {
+ [VSOCK_A_NETNS_FD] = { .type = NLA_U32, },
+ [VSOCK_A_NETNS_PID] = { .type = NLA_U32, },
+};
+
+/* Ops table for vsock */
+static const struct genl_split_ops vsock_nl_ops[] = {
+ {
+ .cmd = VSOCK_CMD_DEV_NETNS_SET,
+ .doit = vsock_nl_dev_netns_set_doit,
+ .policy = vsock_dev_netns_set_nl_policy,
+ .maxattr = VSOCK_A_NETNS_PID,
+ .flags = GENL_ADMIN_PERM | GENL_CMD_CAP_DO,
+ },
+ {
+ .cmd = VSOCK_CMD_DEV_NETNS_GET,
+ .doit = vsock_nl_dev_netns_get_doit,
+ .flags = GENL_CMD_CAP_DO,
+ },
+};
+
+struct genl_family vsock_nl_family __ro_after_init = {
+ .name = VSOCK_FAMILY_NAME,
+ .version = VSOCK_FAMILY_VERSION,
+ .netnsok = true,
+ .parallel_ops = true,
+ .module = THIS_MODULE,
+ .split_ops = vsock_nl_ops,
+ .n_split_ops = ARRAY_SIZE(vsock_nl_ops),
+};
diff --git a/net/vmw_vsock/vsock_nl_gen.h b/net/vmw_vsock/vsock_nl_gen.h
new file mode 100644
index 00000000000000..a2fd87344581af
--- /dev/null
+++ b/net/vmw_vsock/vsock_nl_gen.h
@@ -0,0 +1,20 @@
+/* SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Clause) */
+/* Do not edit directly, auto-generated from: */
+/* Documentation/netlink/specs/vsock.yaml */
+/* YNL-GEN kernel header */
+/* To regenerate run: tools/net/ynl/ynl-regen.sh */
+
+#ifndef _LINUX_VSOCK_GEN_H
+#define _LINUX_VSOCK_GEN_H
+
+#include <net/netlink.h>
+#include <net/genetlink.h>
+
+#include <uapi/linux/vsock_netlink.h>
+
+int vsock_nl_dev_netns_set_doit(struct sk_buff *skb, struct genl_info *info);
+int vsock_nl_dev_netns_get_doit(struct sk_buff *skb, struct genl_info *info);
+
+extern struct genl_family vsock_nl_family;
+
+#endif /* _LINUX_VSOCK_GEN_H */
diff --git a/tools/net/ynl/Makefile.deps b/tools/net/ynl/Makefile.deps
index 3eee34e0efcf9c..cd1450f1cac055 100644
--- a/tools/net/ynl/Makefile.deps
+++ b/tools/net/ynl/Makefile.deps
@@ -62,4 +62,5 @@ CFLAGS_tc:= $(call get_hdr_inc,__LINUX_RTNETLINK_H,rtnetlink.h) \
$(call get_hdr_inc,_TC_SKBEDIT_H,tc_act/tc_skbedit.h) \
$(call get_hdr_inc,_TC_TUNNEL_KEY_H,tc_act/tc_tunnel_key.h)
CFLAGS_tcp_metrics:=$(call get_hdr_inc,_LINUX_TCP_METRICS_H,tcp_metrics.h)
+CFLAGS_vsock:=$(call get_hdr_inc,_LINUX_VSOCK_NETLINK_H,vsock_netlink.h)
CFLAGS_wireguard:=$(call get_hdr_inc2,_LINUX_WIREGUARD_H,_WG_UAPI_WIREGUARD_H,wireguard.h)
diff --git a/tools/testing/selftests/vsock/Makefile b/tools/testing/selftests/vsock/Makefile
index c407c0afd9388e..2b066ba91bcd78 100644
--- a/tools/testing/selftests/vsock/Makefile
+++ b/tools/testing/selftests/vsock/Makefile
@@ -13,5 +13,10 @@ $(VSOCK_TEST_DIR)/vsock_test: $(VSOCK_TEST_SRCS)
TEST_PROGS += vmtest.sh
TEST_GEN_FILES := vsock_test
+TEST_FILES := \
+ ../../../net/ynl/pyynl/cli.py \
+ ../../../net/ynl/pyynl/lib \
+ ../../../../Documentation/netlink/specs/vsock.yaml
+
include ../lib.mk
diff --git a/tools/testing/selftests/vsock/config b/tools/testing/selftests/vsock/config
index 5f0a4f17dfc96c..4b31085558faae 100644
--- a/tools/testing/selftests/vsock/config
+++ b/tools/testing/selftests/vsock/config
@@ -109,3 +109,4 @@ CONFIG_FS_DAX=y
CONFIG_MEMORY_HOTPLUG=y
CONFIG_MEMORY_HOTREMOVE=y
CONFIG_ZONE_DEVICE=y
+CONFIG_USER_NS=y
diff --git a/tools/testing/selftests/vsock/vmtest.sh b/tools/testing/selftests/vsock/vmtest.sh
index 310dfc2a39ad57..9614532a56285f 100755
--- a/tools/testing/selftests/vsock/vmtest.sh
+++ b/tools/testing/selftests/vsock/vmtest.sh
@@ -17,6 +17,20 @@ readonly KERNEL_CHECKOUT=$(realpath "${SCRIPT_DIR}"/../../../../)
source "${SCRIPT_DIR}"/../kselftest/ktap_helpers.sh
readonly VSOCK_TEST="${SCRIPT_DIR}"/vsock_test
+
+# "make install" copies the ynl CLI, its lib package and the spec next to this
+# script (see TEST_FILES); in a source tree they stay where they are built.
+if [[ -r "${SCRIPT_DIR}"/cli.py ]]; then
+ readonly YNL_CLI="${SCRIPT_DIR}"/cli.py
+ readonly YNL_LIB="${SCRIPT_DIR}"/lib
+ readonly VSOCK_SPEC="${SCRIPT_DIR}"/vsock.yaml
+else
+ readonly YNL_DIR="${KERNEL_CHECKOUT}"/tools/net/ynl/pyynl
+ readonly YNL_CLI="${YNL_DIR}"/cli.py
+ readonly YNL_LIB="${YNL_DIR}"/lib
+ readonly SPEC_DIR="${KERNEL_CHECKOUT}"/Documentation/netlink/specs
+ readonly VSOCK_SPEC="${SPEC_DIR}"/vsock.yaml
+fi
readonly TEST_GUEST_PORT=51000
readonly TEST_HOST_PORT=50000
readonly TEST_HOST_PORT_LISTENER=50001
@@ -73,6 +87,15 @@ readonly TEST_NAMES=(
ns_delete_vm_ok
ns_delete_host_ok
ns_delete_both_ok
+ ns_guest_local_connect_to_host_fails
+ ns_guest_assign_g2h_netns_connect_to_host_ok
+ ns_guest_assign_g2h_netns_by_pid_ok
+ ns_guest_assign_g2h_netns_init_ns_connect_fails
+ ns_guest_assign_g2h_netns_host_connect_ok
+ ns_guest_assign_g2h_netns_pins_ns_ok
+ ns_guest_assign_g2h_netns_old_conn_send_fails
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails
)
readonly TEST_DESCS=(
# vm_server_host_client
@@ -149,12 +172,48 @@ readonly TEST_DESCS=(
# ns_delete_both_ok
"Check that deleting the VM and host's namespaces does not break the socket connection"
+
+ # ns_guest_local_connect_to_host_fails
+ "Check a guest process in a local ns cannot reach the host without the netns assign."
+
+ # ns_guest_assign_g2h_netns_connect_to_host_ok
+ "Check a guest process in a local ns reaches the host once the vsock device is assigned to it."
+
+ # ns_guest_assign_g2h_netns_by_pid_ok
+ "Check the vsock device can be assigned to a ns given by PID from outside it."
+
+ # ns_guest_assign_g2h_netns_init_ns_connect_fails
+ "Check the guest's initial ns loses vsock once the device is assigned to another ns."
+
+ # ns_guest_assign_g2h_netns_host_connect_ok
+ "Check the host reaches a guest listener in the ns the vsock device is assigned to."
+
+ # ns_guest_assign_g2h_netns_pins_ns_ok
+ "Check the assignment keeps the ns alive when deleted, and that reassigning releases it."
+
+ # ns_guest_assign_g2h_netns_old_conn_send_fails
+ "Check connections made before the assign stop sending once they lose the device."
+
+ # ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ "Check assigning the guest's vsock device to a namespace needs CAP_NET_ADMIN."
+
+ # ns_guest_assign_g2h_netns_unpriv_user_ns_fails
+ "Check an unprivileged user cannot claim the guest's vsock device via a user ns."
)
readonly USE_SHARED_VM=(
vm_server_host_client
vm_client_host_server
vm_loopback
+ ns_guest_local_connect_to_host_fails
+ ns_guest_assign_g2h_netns_connect_to_host_ok
+ ns_guest_assign_g2h_netns_by_pid_ok
+ ns_guest_assign_g2h_netns_init_ns_connect_fails
+ ns_guest_assign_g2h_netns_host_connect_ok
+ ns_guest_assign_g2h_netns_pins_ns_ok
+ ns_guest_assign_g2h_netns_old_conn_send_fails
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails
)
readonly NS_MODES=("local" "global")
@@ -316,6 +375,43 @@ check_deps() {
fi
}
+check_ns_guest_deps() {
+ local tname=$1
+ local deps="unshare python3"
+ local dep
+
+ if [[ ! "${tname}" =~ ^ns_guest_ ]]; then
+ return 0
+ fi
+
+ # test-specific guest dep checks
+ case "${tname}" in
+ ns_guest_assign_g2h_netns_no_cap_net_admin_fails | \
+ ns_guest_assign_g2h_netns_unpriv_user_ns_fails)
+ deps="${deps} setpriv"
+ ;;
+ esac
+
+ for dep in ${deps}; do
+ if [[ ! -x $(command -v "${dep}") ]]; then
+ log_host "no ${dep} for test ${tname}"
+ return 1
+ fi
+ done
+
+ if ! python3 -c "import yaml" &>/dev/null; then
+ log_host "no python3 yaml module for test ${tname}"
+ return 1
+ fi
+
+ if [[ ! -r "${YNL_CLI}" ]] || [[ ! -r "${VSOCK_SPEC}" ]]; then
+ log_host "no ynl cli or vsock spec for test ${tname}"
+ return 1
+ fi
+
+ return 0
+}
+
check_netns() {
local tname=$1
@@ -401,6 +497,19 @@ setup_home() {
mkdir -p "$(dirname "${SSH_KEY_PATH}")"
ssh-keygen -t ed25519 -f "${SSH_KEY_PATH}" -N "" -q
cp "${VSOCK_TEST}" "${TEST_HOME}"/vsock_test
+
+ mkdir -p "${TEST_HOME}"/ynl
+ if [[ -r "${YNL_CLI}" ]]; then
+ cp "${YNL_CLI}" "${TEST_HOME}"/ynl/
+ cp -r "${YNL_LIB}" "${TEST_HOME}"/ynl/
+ cp "${VSOCK_SPEC}" "${TEST_HOME}"/ynl/
+ fi
+
+ # One of the tests runs the CLI as an unprivileged user, so the CLI
+ # has to be reachable by one.
+ chmod -R a+rX "${TEST_HOME}"/ynl
+
+ chmod 755 "${TEST_HOME}"
}
create_pidfile() {
@@ -528,6 +637,82 @@ vm_wait_for_ssh() {
done
}
+# Create a local mode namespace in the VM and echo the pid holding it open.
+vm_ns_start() {
+ local ns=$1
+ local initns
+ local nspid
+ local newns
+ local i
+
+ local mode=/proc/sys/net/vsock/child_ns_mode
+
+ if ! vm_ssh "${ns}" -- "echo local > ${mode}" &>/dev/null; then
+ return
+ fi
+
+ nspid=$(vm_ssh "${ns}" -- "unshare -n sleep infinity" \
+ '>/dev/null 2>&1 & echo $!')
+ if [[ -z "${nspid}" ]]; then
+ return
+ fi
+
+ initns=$(vm_ssh "${ns}" -- "readlink /proc/self/ns/net")
+ for ((i = 0; i < WAIT_PERIOD_MAX; i++)); do
+ newns=$(vm_ssh "${ns}" -- "readlink /proc/${nspid}/ns/net" \
+ 2>/dev/null)
+ if [[ -n "${newns}" ]] && [[ "${newns}" != "${initns}" ]]; then
+ echo "${nspid}"
+ return
+ fi
+ sleep 1
+ done
+
+ vm_ns_stop "${ns}" "${nspid}"
+}
+
+# Returns once the holder is gone, so that the namespace is unreferenced and
+# the kernel can start tearing it down.
+vm_ns_stop() {
+ local ns=$1
+ local nspid=$2
+
+ vm_ssh "${ns}" <<-EOF &>/dev/null
+ kill ${nspid}
+ for ((i = 0; i < ${WAIT_PERIOD_MAX}; i++)); do
+ kill -0 ${nspid} 2>/dev/null || break
+ sleep 1
+ done
+ EOF
+}
+
+# Runs in the guest's initial namespace when <nspid> is empty. The command must
+# not contain single quotes.
+vm_ns_exec() {
+ local ns=$1
+ local nspid=$2
+ local cmd=$3
+
+ if [[ -z "${nspid}" ]]; then
+ vm_ssh "${ns}" -- "${cmd}"
+ return
+ fi
+
+ vm_ssh "${ns}" -- nsenter -t "${nspid}" -n sh -c "'${cmd}'"
+}
+
+vm_ns_assign_g2h() {
+ local ns=$1
+ local nspid=$2
+
+ vm_ns_exec "${ns}" "${nspid}" "python3 /root/ynl/cli.py --no-schema \
+ --spec /root/ynl/vsock.yaml --do dev-netns-set"
+}
+
+vm_reset_g2h() {
+ vm_ns_assign_g2h "init_ns" "" &>/dev/null
+}
+
# derived from selftests/net/net_helper.sh
wait_for_listener()
{
@@ -564,17 +749,33 @@ wait_for_listener()
done
}
-vm_wait_for_listener() {
+# Runs in the guest's initial namespace when <nspid> is empty.
+vm_ns_wait_for_listener() {
local ns=$1
- local port=$2
- local protocol=$3
+ local nspid=$2
+ local port=$3
+ local protocol=$4
+ local nsenter=
+ local args
+
+ [[ -n "${nspid}" ]] && nsenter="nsenter -t ${nspid} -n"
+ args="${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}"
vm_ssh "${ns}" <<EOF
$(declare -f wait_for_listener)
-wait_for_listener ${port} ${WAIT_PERIOD} ${WAIT_PERIOD_MAX} ${protocol}
+export -f wait_for_listener
+${nsenter} bash -c "wait_for_listener ${args}"
EOF
}
+vm_wait_for_listener() {
+ local ns=$1
+ local port=$2
+ local protocol=$3
+
+ vm_ns_wait_for_listener "${ns}" "" "${port}" "${protocol}"
+}
+
host_wait_for_listener() {
local ns=$1
local port=$2
@@ -1421,6 +1622,392 @@ test_ns_delete_both_ok() {
check_ns_delete_doesnt_break_connection "both"
}
+# Send a string from the guest to a host listener and leave what the host
+# received in <outfile>.
+guest_send_to_host() {
+ local ns=$1
+ local nspid=$2
+ local port=$3
+ local outfile=$4
+ local cmd="echo TEST | socat -u STDIN VSOCK-CONNECT:2:${port}"
+ local pid
+
+ socat -u VSOCK-LISTEN:"${port}" STDOUT > "${outfile}" 2>/dev/null &
+ pid=$!
+ host_wait_for_listener "${ns}" "${port}" "vsock"
+
+ vm_ns_exec "${ns}" "${nspid}" "${cmd}" 2>/dev/null
+
+ timeout "${WAIT_PERIOD}" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ # Wait for the listener to actually go, or the next test binding the
+ # same port races it and silently reads nothing.
+ terminate_pids "${pid}"
+ wait "${pid}" 2>/dev/null
+}
+
+# Send a string from the host to a listener in the guest and leave what the
+# guest received in <outfile>.
+host_send_to_guest() {
+ local ns=$1
+ local nspid=$2
+ local port=$3
+ local outfile=$4
+ local cmd="socat -u VSOCK-LISTEN:${port} STDOUT"
+ local dst="VSOCK-CONNECT:${VSOCK_CID}:${port}"
+ local pid
+
+ vm_ns_exec "${ns}" "${nspid}" "${cmd}" > "${outfile}" 2>/dev/null &
+ pid=$!
+ vm_ns_wait_for_listener "${ns}" "${nspid}" "${port}" "vsock"
+
+ echo TEST | socat -u STDIN "${dst}" 2>/dev/null
+
+ timeout "${WAIT_PERIOD}" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ vm_ns_exec "${ns}" "${nspid}" \
+ "pkill -f VSOCK-LISTEN:${port}" &>/dev/null
+ terminate_pids "${pid}"
+ wait "${pid}" 2>/dev/null
+}
+
+ns_old_conn_cleanup() {
+ local port=$1
+ local pid=$2
+ local sender=$3
+ local outfile=$4
+ local nspid=$5
+
+ vm_ns_exec "init_ns" "" "pkill -f VSOCK-CONNECT:2:${port}" &>/dev/null
+ terminate_pids "${pid}" "${sender}"
+ wait "${pid}" "${sender}" 2>/dev/null
+ rm -f "${outfile}"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+}
+
+test_ns_guest_assign_g2h_netns_old_conn_send_fails() {
+ local gap=$(( WAIT_PERIOD * 3 ))
+ local port=12346
+ local elapsed
+ local started
+ local outfile
+ local result
+ local sender
+ local nspid
+ local pid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ socat -u VSOCK-LISTEN:"${port}" STDOUT > "${outfile}" 2>/dev/null &
+ pid=$!
+ host_wait_for_listener "init_ns" "${port}" "vsock"
+
+ # Send a message, wait, then send another. While waiting, assign the
+ # device to a namespace. Confirm the second message does not arrive.
+ started=${SECONDS}
+ vm_ssh "init_ns" -- \
+ "(echo FIRST; sleep ${gap}; echo SECOND) |" \
+ "socat -u STDIN VSOCK-CONNECT:2:${port}" &>/dev/null &
+ sender=$!
+
+ timeout "$(( WAIT_PERIOD * WAIT_PERIOD_MAX ))" \
+ bash -c 'while [[ ! -s '"${outfile}"' ]]; do sleep 1; done'
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ ns_old_conn_cleanup "${port}" "${pid}" "${sender}" \
+ "${outfile}" "${nspid}"
+ return "${KSFT_FAIL}"
+ fi
+ elapsed=$(( SECONDS - started ))
+
+ sleep $(( gap + WAIT_PERIOD ))
+
+ result=$(cat "${outfile}")
+ ns_old_conn_cleanup "${port}" "${pid}" "${sender}" \
+ "${outfile}" "${nspid}"
+
+ if [[ "${result}" != *FIRST* ]]; then
+ log_host "no connection before the assign: [${result}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ if [[ $(( elapsed + 1 )) -ge ${gap} ]]; then
+ log_host "connect and assign took ${elapsed}s of a ${gap}s gap"
+ return "${KSFT_SKIP}"
+ fi
+
+ if [[ "${result}" == *SECOND* ]]; then
+ log_host "old connection still delivered after the assign"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_local_connect_to_host_fails() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" == TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_connect_to_host_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_by_pid_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ssh "init_ns" -- python3 /root/ynl/cli.py --no-schema \
+ --spec /root/ynl/vsock.yaml --do dev-netns-set \
+ --json "'{\"netns-pid\": ${nspid}}'"; then
+ log_host "failed to assign the vsock device by PID"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_init_ns_connect_fails() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" == TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_host_connect_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ outfile=$(mktemp)
+ host_send_to_guest "init_ns" "${nspid}" "${port}" "${outfile}"
+
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_pins_ns_ok() {
+ local port=12345
+ local outfile
+ local result
+ local nspid
+
+ nspid=$(vm_ns_start "init_ns")
+ if [[ -z "${nspid}" ]]; then
+ log_host "failed to create a namespace inside the guest"
+ return "${KSFT_FAIL}"
+ fi
+
+ if ! vm_ns_assign_g2h "init_ns" "${nspid}"; then
+ log_host "failed to assign the vsock device to the guest ns"
+ vm_ns_stop "init_ns" "${nspid}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ vm_ns_stop "init_ns" "${nspid}"
+ sleep "${WAIT_PERIOD}"
+
+ outfile=$(mktemp)
+ guest_send_to_host "init_ns" "" "${port}" "${outfile}"
+ result=$(cat "${outfile}")
+ if [[ "${result}" == TEST ]]; then
+ log_host "device returned to the init ns instead of pinning it"
+ rm -f "${outfile}"
+ vm_reset_g2h
+ return "${KSFT_FAIL}"
+ fi
+
+ # Assigning it back is what releases the deleted namespace.
+ vm_reset_g2h
+
+ guest_send_to_host "init_ns" "" "$(( port + 1 ))" "${outfile}"
+ result=$(cat "${outfile}")
+ rm -f "${outfile}"
+
+ if [[ "${result}" != TEST ]]; then
+ log_host "device did not come back on reassign: [${result}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+check_assign_g2h_eperm() {
+ local wrapper=$1
+ local out
+
+ if out=$(vm_ssh "init_ns" -- "${wrapper}" python3 /root/ynl/cli.py \
+ --no-schema --spec /root/ynl/vsock.yaml \
+ --do dev-netns-set 2>&1); then
+ log_host "assign unexpectedly succeeded under '${wrapper}'"
+ return "${KSFT_FAIL}"
+ fi
+
+ if [[ "${out}" != *"Operation not permitted"* ]]; then
+ log_host "no EPERM under '${wrapper}': [${out}]"
+ return "${KSFT_FAIL}"
+ fi
+
+ return "${KSFT_PASS}"
+}
+
+test_ns_guest_assign_g2h_netns_no_cap_net_admin_fails() {
+ check_assign_g2h_eperm "unshare -n setpriv --bounding-set=-net_admin"
+}
+
+test_ns_guest_assign_g2h_netns_unpriv_user_ns_fails() {
+ local unpriv_uid=65534
+ local unpriv
+
+ unpriv="setpriv --reuid=${unpriv_uid} --regid=${unpriv_uid}"
+ unpriv="${unpriv} --clear-groups"
+
+ if ! vm_ssh "init_ns" -- "${unpriv} unshare -Urn true"; then
+ log_host "unprivileged user namespaces unavailable, skipping"
+ return "${KSFT_SKIP}"
+ fi
+
+ check_assign_g2h_eperm "${unpriv} unshare -Urn"
+}
+
shared_vm_test() {
local tname
@@ -1453,7 +2040,8 @@ run_shared_vm_tests() {
continue
fi
- if ! check_netns "${arg}"; then
+ if ! check_netns "${arg}" ||
+ ! check_ns_guest_deps "${arg}"; then
check_result "${KSFT_SKIP}" "${arg}"
continue
fi
@@ -1517,7 +2105,8 @@ run_ns_tests() {
continue
fi
- if ! check_netns "${arg}"; then
+ if ! check_netns "${arg}" ||
+ ! check_ns_guest_deps "${arg}"; then
check_result "${KSFT_SKIP}" "${arg}"
continue
fi
|
| 15/3 | 2026/11/18 10:11 | llm | kmsan-evaluator |
2mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 27249 output: 45 thoughts: 4807 Thoughts: **KMSAN Evaluation of VSOCK Namespace Patch** Okay, I've meticulously reviewed this patch series, and my expert intuition is on high alert for potential uninitialized memory exposures, the kind that KMSAN is designed to catch. The goal is to determine if this new code warrants the expense of dedicated KMSAN runs, or if standard KASAN and other tools will suffice. I'm focusing on areas where data is passed to userspace, where local variables could be uninitialized, or where buffers are allocated and manipulated. My initial assessment is that the changes are primarily focused on networking namespace management for VSOCK devices, and that the code carefully initializes all relevant variables. I haven't seen any red flags yet! Let's dissect the most pertinent parts. In `vsock_nl_dev_netns_fill`, the `id` variable is conditionally assigned based on the `equal` variable. However, it's assigned in *both* branches of the `if` statement, and only used in the `!equal` case, and the `!equal` case short-circuits. So `id` will always be initialized before use. The same goes for the `put_s32` call to netlink, which ensures padding is handled by the netlink helpers. I don't see anything suspicious in the netlink handling. The `vsock_dev_do_ioctl` function, it is good to go as well. The `cid` value returned by `vsock_registered_transport_cid` is *always* initialized within its calls, which should make the put_user call safe. `vhost_vsock_set_cid` looks equally safe, with `ret` being assigned a value in all code paths. Looking into `vsock_nl_dev_netns_set_doit`, the `net` variable is initialized based on the presence or absence of either of `fd_attr` or `pid_attr` and the `else` case in the code. Checking `vsock_g2h_net_assign`, all the variables used in `vsock_g2h_net_assign` are initialized. And the local variables are properly initialized, including the `old_tracker` variable, by the `vsock_g2h_net_swap` function. `old_tracker` is properly released. In `vsock_core_unregister`, similar logic applies, all the variables used in the code are always initialized. The `old_tracker` is initialized and released properly. Even in the `virtio_transport_rx_work` and `virtio_transport_recv_connecting` functions, variables are tracked. Both have calls to tracker initialization. `ns_tracker` is used as an input to `put_net_track`, which releases the net ns. I've examined the code paths and don't see any obvious cases where uninitialized memory could be read and leak information to userspace or cause crashes. I am confident that the code changes either initialize the data or handle initialization errors properly, so they do not introduce KMSAN-specific risks. Therefore, I believe **NeedsKMSAN=false** is the correct setting. Standard KASAN coverage should be sufficient for this patch series. |
| 16/3 | 2026/11/18 10:14 | tool | read-file |
0mArgs:{
"File": "net/vmw_vsock/virtio_transport_common.c",
"FirstLine": 1470,
"LineCount": 55
}Results: {
"Contents": "1470:\t\t\tsock_set_flag(sk, SOCK_DONE);\n1471:\t\t\tvirtio_transport_remove_sock(vsk);\n1472:\t\t}\n1473:\t}\n1474:\tEXPORT_SYMBOL_GPL(virtio_transport_release);\n1475:\t\n1476:\tstatic int\n1477:\tvirtio_transport_recv_connecting(struct sock *sk, struct sk_buff *skb,\n1478:\t\t\t\t\t struct virtio_transport *t)\n1479:\t{\n1480:\t\tstruct virtio_vsock_hdr *hdr = virtio_vsock_hdr(skb);\n1481:\t\tstruct vsock_sock *vsk = vsock_sk(sk);\n1482:\t\tint skerr;\n1483:\t\tint err;\n1484:\t\n1485:\t\tswitch (le16_to_cpu(hdr-\u003eop)) {\n1486:\t\tcase VIRTIO_VSOCK_OP_RESPONSE:\n1487:\t\t\tif (!vsock_maybe_set_connected(vsk)) {\n1488:\t\t\t\t/* The net arg is required but unused: only g2h can fail\n1489:\t\t\t\t * vsock_maybe_set_connected(), and g2h\n1490:\t\t\t\t * virtio_transport_reset_no_sock() ignores the net arg.\n1491:\t\t\t\t */\n1492:\t\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1493:\t\t\t\tskerr = ECONNRESET;\n1494:\t\t\t\terr = -ENETUNREACH;\n1495:\t\t\t\tgoto close;\n1496:\t\t\t}\n1497:\t\n1498:\t\t\tsk-\u003esk_socket-\u003estate = SS_CONNECTED;\n1499:\t\t\tsk-\u003esk_state_change(sk);\n1500:\t\t\tbreak;\n1501:\t\tcase VIRTIO_VSOCK_OP_INVALID:\n1502:\t\t\tbreak;\n1503:\t\tcase VIRTIO_VSOCK_OP_RST:\n1504:\t\t\tskerr = ECONNRESET;\n1505:\t\t\terr = 0;\n1506:\t\t\tgoto destroy;\n1507:\t\tdefault:\n1508:\t\t\tskerr = EPROTO;\n1509:\t\t\terr = -EINVAL;\n1510:\t\t\tgoto destroy;\n1511:\t\t}\n1512:\t\treturn 0;\n1513:\t\n1514:\tdestroy:\n1515:\t\tvirtio_transport_reset(vsk, skb);\n1516:\tclose:\n1517:\t\tsk-\u003esk_state = TCP_CLOSE;\n1518:\t\tsk-\u003esk_err = skerr;\n1519:\t\tsk_error_report(sk);\n1520:\t\treturn err;\n1521:\t}\n1522:\t\n1523:\tstatic bool\n1524:\tvirtio_transport_recv_enqueue(struct vsock_sock *vsk,\n"
} |
| 17/3 | 2026/11/18 10:14 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 33595 output: 45 thoughts: 75 Thoughts: Here's my summary, as though I'm thinking through this code: **Analyzing Potential Connection Reset Issues in Virtio Transport** Okay, so I'm digging into this `virtio_transport_recv_connecting` function, and I've spotted something interesting. It's setting both `skerr` to `ECONNRESET` and `err` to `-ENETUNREACH` before jumping to the `close` label. My initial reaction is, why are we setting both? They are both initialized, so it's not a case where the previous value is undefined. `ECONNRESET` makes sense for a connection reset, but `-ENETUNREACH` seems... off, unless it's a very specific context. I need to understand what's triggering this dual error setting. It's a bit redundant, isn't it? Let's see if there is similar logic in other parts of the code. Let me check `virtio_transport_recv_listen` around line 1750. I want to see if this pattern is used anywhere else to see if there is some logic I'm missing. |
| 18/3 | 2026/11/18 10:15 | tool | read-file |
0mArgs:{
"File": "net/vmw_vsock/virtio_transport_common.c",
"FirstLine": 1735,
"LineCount": 55
}Results: {
"Contents": "1735:\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1736:\t\t\treturn -ENOMEM;\n1737:\t\t}\n1738:\t\n1739:\t\t/* __vsock_release() might have already flushed accept_queue.\n1740:\t\t * Subsequent enqueues would lead to a memory leak.\n1741:\t\t */\n1742:\t\tif (sk-\u003esk_shutdown == SHUTDOWN_MASK) {\n1743:\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1744:\t\t\treturn -ESHUTDOWN;\n1745:\t\t}\n1746:\t\n1747:\t\tchild = vsock_create_connected(sk);\n1748:\t\tif (!child) {\n1749:\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1750:\t\t\treturn -ENOMEM;\n1751:\t\t}\n1752:\t\n1753:\t\tlock_sock_nested(child, SINGLE_DEPTH_NESTING);\n1754:\t\n1755:\t\tvchild = vsock_sk(child);\n1756:\t\tvsock_addr_init(\u0026vchild-\u003elocal_addr, le64_to_cpu(hdr-\u003edst_cid),\n1757:\t\t\t\tle32_to_cpu(hdr-\u003edst_port));\n1758:\t\tvsock_addr_init(\u0026vchild-\u003eremote_addr, le64_to_cpu(hdr-\u003esrc_cid),\n1759:\t\t\t\tle32_to_cpu(hdr-\u003esrc_port));\n1760:\t\n1761:\t\tret = vsock_assign_transport(vchild, vsk);\n1762:\t\t/* Transport assigned (looking at remote_addr) must be the same\n1763:\t\t * where we received the request.\n1764:\t\t */\n1765:\t\tif (ret || vchild-\u003etransport != \u0026t-\u003etransport) {\n1766:\t\t\trelease_sock(child);\n1767:\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1768:\t\t\tsock_put(child);\n1769:\t\t\treturn ret;\n1770:\t\t}\n1771:\t\n1772:\t\tif (virtio_transport_space_update(child, skb))\n1773:\t\t\tchild-\u003esk_write_space(child);\n1774:\t\n1775:\t\tif (!vsock_maybe_set_connected(vchild)) {\n1776:\t\t\trelease_sock(child);\n1777:\t\t\t/* Only reached for g2h, whose send_pkt() ignores the netns. */\n1778:\t\t\tvirtio_transport_reset_no_sock(t, skb, sock_net(sk));\n1779:\t\t\tsock_put(child);\n1780:\t\t\treturn -ENETUNREACH;\n1781:\t\t}\n1782:\t\n1783:\t\tvsock_enqueue_accept(sk, child);\n1784:\t\tvirtio_transport_send_response(vchild, skb);\n1785:\t\n1786:\t\trelease_sock(child);\n1787:\t\n1788:\t\tsk-\u003esk_data_ready(sk);\n1789:\t\treturn 0;\n"
} |
| 19/3 | 2026/11/18 10:15 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 34851 output: 36 thoughts: 1536 Thoughts: **Analyzing vsock and Netlink for Potential Uninitialized Memory Issues** Okay, let's dive into this. My initial focus is on the `vsock` module, specifically looking for any opportunities for uninitialized memory to leak or be exposed, particularly in the context of Netlink interactions. First, I examined `vsock_connect_close` and `vsock_connect`. Nothing jumps out immediately. The code seems sound, and I see no obvious issues with uninitialized memory there. Specifically, the check after `transport->connect()` and the handling of `sock_error(sk)` both call `vsock_connect_close` which is safe. Next, I went back to `vsock_nl_dev_netns_fill` and, specifically, the Netlink attribute handling. The key here is the interaction between `peernet2id_alloc` and `nla_put_s32`. `peernet2id_alloc` returns an integer: either a positive ID or a negative error code (or `NETNSA_NSID_NOT_ASSIGNED`). `nla_put_s32` is straightforward: it takes the result and puts it as a 32-bit integer attribute. The `&value` inside `nla_put_s32` points to the local stack variable `id`, so the value is passed by value and thus copied. The worst case scenario is it puts a negative error code or `NETNSA_NSID_NOT_ASSIGNED`. `equal` being true means the function exits early, with nothing being put, so that path is safe. `genlmsg_iput` correctly handles the Netlink header. This looks clean. I then briefly checked `vsock_nl_gen.c` to see if there was any potential for uninitalized data in the structure there. This looks like standard generic netlink family code and is unlikely to cause a problem. Finally, I glanced at `drivers/vhost/vsock.c`, specifically `vhost_transport_has_remote_cid`. It looks like the net struct is being passed in directly, rather than being derived from `vsk`, which is cleaner. I will use read-file to confirm this. |
| 20/3 | 2026/11/18 10:15 | tool | read-file |
0mArgs:{
"File": "drivers/vhost/vsock.c",
"FirstLine": 90,
"LineCount": 25
}Results: {
"Contents": " 90:\t\n 91:\t\treturn NULL;\n 92:\t}\n 93:\t\n 94:\tstatic bool vhost_transport_has_remote_cid(struct net *net, u32 cid)\n 95:\t{\n 96:\t\tbool found;\n 97:\t\n 98:\t\trcu_read_lock();\n 99:\t\tfound = !!vhost_vsock_get(cid, net);\n 100:\t\trcu_read_unlock();\n 101:\t\treturn found;\n 102:\t}\n 103:\t\n 104:\tstatic void\n 105:\tvhost_transport_do_send_pkt(struct vhost_vsock *vsock,\n 106:\t\t\t\t struct vhost_virtqueue *vq)\n 107:\t{\n 108:\t\tstruct vhost_virtqueue *tx_vq = \u0026vsock-\u003evqs[VSOCK_VQ_TX];\n 109:\t\tint pkts = 0, total_len = 0;\n 110:\t\tbool added = false;\n 111:\t\tbool restart_tx = false;\n 112:\t\n 113:\t\tmutex_lock(\u0026vq-\u003emutex);\n 114:\t\n"
} |
| 21/3 | 2026/11/18 10:15 | llm | kmsan-evaluator |
0mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 37233 output: 43 thoughts: 1285 Thoughts: **Code Review: vsock Implementation - Initial Thoughts** Okay, this code looks remarkably clean at first glance. Let's delve into these functions and confirm that the details hold up to scrutiny. I'm starting with `vsock_next_connected_socket`. The logic seems sound: it iterates through the connected sockets table, using a provided `match` function to filter the results. The use of a bucket and the starting point within that bucket looks like a standard optimization to avoid iterating the whole table every time. Importantly, it acquires a reference with `sock_hold` before releasing the table lock to hand off to the caller. This ensures the sock isn't freed under us. Excellent. And, the resumption of the search from the point at which it left off is important. Next, I'm analyzing `vsock_g2h_reset_unreachable`. This is a bit more complex. The function aims to reset unreachable sockets, and the double locking strategy (acquiring `vsock_table_lock` and then `lock_sock`) is critical. The comments highlight the need to re-check the socket state after releasing the first lock. I see the re-check is implemented properly, ensuring that the socket hasn't been closed by the time they reacquire the second lock. This race condition is handled correctly. The use of `SOCK_DONE`, `SHUTDOWN_MASK`, `TCP_CLOSING`, and `ECONNRESET` is standard for socket closure and error reporting. The initialization of local variables like `i` and `reset` are, as expected, properly initialized. Now, on to `vsock_maybe_set_connected`. This function looks straightforward: it attempts to set a socket to the established state. The use of `vsock_g2h_reachable_sk` to determine reachability is important, and the initialization of reachable is correct. The `__vsock_insert_connected` seems to be inserting the socket into a list. All the initializations look good. The use of the spinlock is appropriate, given the shared data structure. Finally, I'm examining `vsock_find_cid` and `__vsock_find_cid`. The function `__vsock_find_cid` is guarded by the mutex lock. I need to make sure this `mutex_lock` is correct. The logic is a simple check of CIDs against known values. It looks like it verifies if a given CID has already been registered with the given transport. The use of `lockdep_assert_held` and `mutex_lock` indicates this is properly synchronized. The initialization of variables is as it should be. Let me now consider `vsock_dev_do_ioctl` to see the ioctl handling. I'll read around line 3196 in `net/vmw_vsock/af_vsock.c` to understand the device interaction. |
| 22/3 | 2026/11/18 10:16 | tool | read-file |
0mArgs:{
"File": "net/vmw_vsock/af_vsock.c",
"FirstLine": 3195,
"LineCount": 40
}Results: {
"Contents": "3195:\tstatic long vsock_dev_do_ioctl(struct file *filp,\n3196:\t\t\t\t unsigned int cmd, void __user *ptr)\n3197:\t{\n3198:\t\tu32 __user *p = ptr;\n3199:\t\tstruct net *net;\n3200:\t\tint retval = 0;\n3201:\t\tu32 cid;\n3202:\t\n3203:\t\tswitch (cmd) {\n3204:\t\tcase IOCTL_VM_SOCKETS_GET_LOCAL_CID:\n3205:\t\t\t/* To be compatible with the VMCI behavior, we prioritize the\n3206:\t\t\t * guest CID instead of well-know host CID (VMADDR_CID_HOST).\n3207:\t\t\t */\n3208:\t\t\tnet = current-\u003ensproxy-\u003enet_ns;\n3209:\t\t\tcid = vsock_registered_transport_cid(\u0026transport_g2h, net);\n3210:\t\t\tif (cid == VMADDR_CID_ANY)\n3211:\t\t\t\tcid = vsock_registered_transport_cid(\u0026transport_h2g,\n3212:\t\t\t\t\t\t\t\t net);\n3213:\t\t\tif (cid == VMADDR_CID_ANY)\n3214:\t\t\t\tcid = vsock_registered_transport_cid(\u0026transport_local,\n3215:\t\t\t\t\t\t\t\t net);\n3216:\t\n3217:\t\t\tif (put_user(cid, p) != 0)\n3218:\t\t\t\tretval = -EFAULT;\n3219:\t\t\tbreak;\n3220:\t\n3221:\t\tdefault:\n3222:\t\t\tretval = -ENOIOCTLCMD;\n3223:\t\t}\n3224:\t\n3225:\t\treturn retval;\n3226:\t}\n3227:\t\n3228:\tstatic long vsock_dev_ioctl(struct file *filp,\n3229:\t\t\t\t unsigned int cmd, unsigned long arg)\n3230:\t{\n3231:\t\treturn vsock_dev_do_ioctl(filp, cmd, (void __user *)arg);\n3232:\t}\n3233:\t\n3234:\t#ifdef CONFIG_COMPAT\n"
} |
| 23/3 | 2026/11/18 10:16 | llm | kmsan-evaluator |
1mModel:gemini-3.8-flash Args: null Results: null Tokens: input: 39758 output: 452 thoughts: 1750 Thoughts: **KMSAN Needs Analysis** Alright, let's break this down. My primary concern is whether this patch series introduces any potential for uninitialized memory reads or information leaks, necessitating KMSAN. I've gone through each of the potential problem areas carefully. Firstly, I checked for kernel structures sent to userspace. In `vsock_nl_dev_netns_fill`, `id` is local to the function, and either explicitly initialized, or the code path that uses it is skipped. In `vsock_dev_do_ioctl`, `cid` is assigned unconditionally before being passed to `put_user`. So, no issues there. Secondly, I looked for conditional logic based on potentially uninitialized variables. This patch series doesn't exhibit any such behavior. All variables are initialized before use, especially those controlling branching or conditional execution. Thirdly, I considered complex data structure allocation. While there's a new field, `netns_assign_allow` in `struct vsock_transport`, it's a boolean, statically initialized, and its default values are set to `0` or `false`. Nothing alarming there. Finally, I checked for bounds or length manipulations that might expose uninitialized memory. No such changes were made. Packet handling still relies on established reachability checks and handles resets appropriately. So, where are the risks? This patch touches concurrency. I'm thinking races around netns assignment, socket connections, reset sweeps, and RCU dereferencing `vsock_g2h_net`. Also, locking bugs and deadlocks due to the mutex ordering of `vsock_g2h_assign_mutex`, `vsock_register_mutex`, `vsock_table_lock`, and `lock_sock` are possible. I'm watching for reference counting issues with netns references and socket references. Use-after-free or NULL pointer dereferences are always on my mind when locking and reference counting are involved. Network namespace reachability logic bugs and connection/reset bugs also need careful scrutiny. However, none of these issues represent *uninitialized memory* bugs or kernel information leaks. These are concurrency, locking, and resource management issues. KASAN and LOCKDEP are fully equipped to catch those memory safety and locking issues that could arise (UAF, refcount underflow, deadlocks, lock inversions). The standard build includes all we need. Let me double-check. I'm focusing on those stack variables, just in case: * In `vsock_nl_dev_netns_fill`, `id` is either initialized by `peernet2id_alloc` or explicitly set to `NETNSA_NSID_NOT_ASSIGNED`, or is not accessed. * In `vsock_g2h_reset_unreachable`, variables like `sk`, `vsk`, `i`, and `reset` are all initialized. * `vsock_g2h_net_assign` starts with `ret` initialized. `old_tracker` is initialized within `vsock_g2h_net_swap`, and `old` is returned from the same. * `vsock_nl_dev_netns_set_doit`, I check `pid_attr`, `fd_attr`, `net`, and `err` all are initialized. * `vhost_vsock_set_cid` returns before `ret` gets uninitialized. * `vsock_dev_do_ioctl`, `cid` is initialized before use. I am confident, all the local variables used are initialized. In summary, this patch adds netlink management for network namespace assignment, updates transports for namespace mode checks, adds synchronization (mutexes, RCU), and socket teardown. The risks are locking order, reference counting of network namespaces, and socket state transitions. But KASAN, LOCKDEP, and refcount sanitizers handle these properly. No uninitialized memory or information leaks exist. I'm ready to mark `NeedsKMSAN` as `false`. I will now call `set-results`. |
| 24/3 | 2026/11/18 10:17 | tool | set-results |
0mArgs:{
"KMSANReasoning": "The patch series introduces a Generic Netlink control interface (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET) and transport reachability checks to support assigning the guest-to-host vsock device to specific network namespaces.\n\nEvaluating KMSAN vs KASAN applicability:\n- Data sent to userspace: In the netlink dump/get path (vsock_nl_dev_netns_fill), the netns ID is sent via nla_put_s32(), which writes a 4-byte scalar value, with netlink attribute alignment padding zeroed by netlink helpers. The local variable 'id' is guaranteed to be initialized when !equal, and is never evaluated when equal is true. Similarly, IOCTL_VM_SOCKETS_GET_LOCAL_CID writes a u32 CID that is unconditionally initialized before put_user(). There are no uninitialized struct fields, padding, or kernel-to-user info-leak risks.\n- Local variables and control flow: All local variables across the new functions (e.g. vsock_nl_dev_netns_set_doit, vsock_g2h_net_assign, vsock_g2h_reset_unreachable, vhost_vsock_set_cid) are fully initialized prior to evaluation.\n- Primary bug risks: The changes introduce complex locking (ordering between vsock_g2h_assign_mutex, vsock_register_mutex, vsock_table_lock, and socket locks), RCU dereferencing of vsock_g2h_net, network namespace reference tracking (get_net_track/put_net_track), and connected socket cleanup logic. Any potential defects here would manifest as deadlocks, race conditions, use-after-free, or refcount imbalances, all of which are covered by LOCKDEP and standard KASAN builds.\n\nTherefore, there are no uninitialized memory risks that justify running a dedicated KMSAN fuzzing session.",
"NeedsKMSAN": false
}Results: {
"KMSANReasoning": "The patch series introduces a Generic Netlink control interface (VSOCK_CMD_DEV_NETNS_SET and VSOCK_CMD_DEV_NETNS_GET) and transport reachability checks to support assigning the guest-to-host vsock device to specific network namespaces.\n\nEvaluating KMSAN vs KASAN applicability:\n- Data sent to userspace: In the netlink dump/get path (vsock_nl_dev_netns_fill), the netns ID is sent via nla_put_s32(), which writes a 4-byte scalar value, with netlink attribute alignment padding zeroed by netlink helpers. The local variable 'id' is guaranteed to be initialized when !equal, and is never evaluated when equal is true. Similarly, IOCTL_VM_SOCKETS_GET_LOCAL_CID writes a u32 CID that is unconditionally initialized before put_user(). There are no uninitialized struct fields, padding, or kernel-to-user info-leak risks.\n- Local variables and control flow: All local variables across the new functions (e.g. vsock_nl_dev_netns_set_doit, vsock_g2h_net_assign, vsock_g2h_reset_unreachable, vhost_vsock_set_cid) are fully initialized prior to evaluation.\n- Primary bug risks: The changes introduce complex locking (ordering between vsock_g2h_assign_mutex, vsock_register_mutex, vsock_table_lock, and socket locks), RCU dereferencing of vsock_g2h_net, network namespace reference tracking (get_net_track/put_net_track), and connected socket cleanup logic. Any potential defects here would manifest as deadlocks, race conditions, use-after-free, or refcount imbalances, all of which are covered by LOCKDEP and standard KASAN builds.\n\nTherefore, there are no uninitialized memory risks that justify running a dedicated KMSAN fuzzing session.",
"NeedsKMSAN": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|