From 5316779d3516ac4022a173acb0c91c1a37f5c815 Mon Sep 17 00:00:00 2001 From: Samuel Ortiz Date: Tue, 19 Dec 2017 15:24:25 +0100 Subject: [PATCH] qemu: Add VSOCK support VSOCK sockets are added through a vhost PCI device. It takes a device ID and a context ID, the latter being the endpoint value to be reached from the host. Signed-off-by: Samuel Ortiz --- qemu/qemu.go | 39 +++++++++++++++++++++++++++++++++++++++ qemu/qemu_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/qemu/qemu.go b/qemu/qemu.go index 3b3c22c140..7c5e33b3a7 100644 --- a/qemu/qemu.go +++ b/qemu/qemu.go @@ -892,6 +892,45 @@ func (bridgeDev BridgeDevice) QemuParams(config *Config) []string { return qemuParams } +// VSOCKDevice represents a AF_VSOCK socket. +type VSOCKDevice struct { + ID string + + ContextID uint32 +} + +const ( + // MinimalGuestCID is the smallest valid context ID for a guest. + MinimalGuestCID uint32 = 3 + + // VhostVSOCKPCI is the VSOCK vhost device type. + VhostVSOCKPCI = "vhost-vsock-pci" + + // VSOCKGuestCID is the VSOCK guest CID parameter. + VSOCKGuestCID = "guest-cid" +) + +// Valid returns true if the VSOCKDevice structure is valid and complete. +func (vsock VSOCKDevice) Valid() bool { + if vsock.ID == "" || vsock.ContextID < MinimalGuestCID { + return false + } + + return true +} + +// QemuParams returns the qemu parameters built out of the VSOCK device. +func (vsock VSOCKDevice) QemuParams(config *Config) []string { + var qemuParams []string + + deviceParam := fmt.Sprintf("%s,id=%s,%s=%d", VhostVSOCKPCI, vsock.ID, VSOCKGuestCID, vsock.ContextID) + + qemuParams = append(qemuParams, "-device") + qemuParams = append(qemuParams, deviceParam) + + return qemuParams +} + // RTCBaseType is the qemu RTC base time type. type RTCBaseType string diff --git a/qemu/qemu_test.go b/qemu/qemu_test.go index 47bd0e452d..2f9de21a6b 100644 --- a/qemu/qemu_test.go +++ b/qemu/qemu_test.go @@ -311,6 +311,34 @@ func TestAppendDeviceVFIO(t *testing.T) { testAppend(vfioDevice, deviceVFIOString, t) } +var deviceVSOCKString = "-device vhost-vsock-pci,id=vhost-vsock-pci0,guest-cid=4" + +func TestAppendVSOCK(t *testing.T) { + vsockDevice := VSOCKDevice{ + ID: "vhost-vsock-pci0", + ContextID: 4, + } + + testAppend(vsockDevice, deviceVSOCKString, t) +} + +func TestVSOCKValid(t *testing.T) { + vsockDevice := VSOCKDevice{ + ID: "vhost-vsock-pci0", + ContextID: MinimalGuestCID - 1, + } + + if vsockDevice.Valid() { + t.Fatalf("VSOCK Context ID is not valid") + } + + vsockDevice.ID = "" + + if vsockDevice.Valid() { + t.Fatalf("VSOCK ID is not valid") + } +} + func TestAppendEmptyDevice(t *testing.T) { device := SerialDevice{}