Compare commits

..

1195 Commits

Author SHA1 Message Date
Rob Bradford
96be82296f release: Release v0.7.0
Expand release notes and bump Cargo.toml.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-30 16:26:08 +01:00
Rob Bradford
5115ad6e56 vmm: config: Support on/off/true/false for all booleans
Migrate missing boolean controls over to the Toggle to handle all
values.

Fixes: #936

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-30 15:21:09 +02:00
Rob Bradford
d5bfa2dfc8 vmm, vhost_user_block: Make parameter names match --disk
Make the --block-backend parameters match the --disk parameters.

Fixes: #898

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-30 15:20:55 +02:00
Sebastien Boeuf
2f0bc06bec vmm: Update default devices names as "internal"
Let's put an underscore "_" in front of each device name to identify
when it has been set internally.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
aaba6e777f vmm: Add virtio-console to the list of Migratable devices
The virtio-console was not added to the list of Migratable devices,
which is fixed from this patch.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
9ab4bb1ae2 devices: serial: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
06487131f9 vm-virtio: pci: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

It is based off the name from the virtio device attached to this
transport layer.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
eeb7e10d1f vm-virtio: mmio: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

It is based off the name from the virtio device attached to this
transport layer.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
9d84ef5073 vmm: Make the virtio identifier mandatory
Because we know we will need every virtio device to be identified with a
unique id, we can simplify the code by making the identifier mandatory.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
14350f5de4 devices: ioapic: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
556871570e vm-virtio: iommu: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
052eff1ca7 vm-virtio: console: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
354c2a4b3d vm-virtio: vhost-user-net: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
46e0b3ff75 vm-virtio: vhost-user-blk: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
bb7fa71fcb vm-virtio: vhost-user-fs: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
ec5ff395cf vm-virtio: vsock: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
9b53044aae vm-virtio: mem: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
1592a9292f vm-virtio: pmem: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
2e91b73881 vm-virtio: rng: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
9eb7413fab vm-virtio: net: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
be946caf4b vm-virtio: blk: Expect an identifier upon device creation
This identifier is chosen from the DeviceManager so that it will manage
all identifiers across the VM, which will ensure uniqueness.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
ff9c8b847f vmm: Always generate the next device name
Even in the context of "mmio" feature, we need the next device name to
be generated as we need to identify virtio-mmio devices to support
snapshot and restore functionalities.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
8183141399 vmm: Add an identifier to the ioapic device
This will be later used to identify each device used by the VM in order
to perform introspection and snapshot/restore properly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
e4386c8bb7 vmm: Add an identifier to the virtio-iommu device
This will be later used to identify each device used by the VM in order
to perform introspection and snapshot/restore properly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
75ddd2a244 vmm: Add an identifier to the --console device
This will be later used to identify each device used by the VM in order
to perform introspection and snapshot/restore properly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
eac350c454 vmm: Add an identifier to the virtio-mem device
This will be later used to identify each device used by the VM in order
to perform introspection and snapshot/restore properly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
6802ef5406 vmm: Add an identifier to the --rng device
This will be later used to identify each device used by the VM in order
to perform introspection and snapshot/restore properly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
d71d52e9b0 vmm: Fix virtio-console creation with virtual IOMMU
If the virtio-console device is supposed to be placed behind the virtual
IOMMU, this must be explicitly propagated through the code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
b08fde5928 vmm: Fix virtio-rng creation with virtual IOMMU
If the virtio-rng device is supposed to be placed behind the virtual
IOMMU, this must be explicitly propagated through the code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Sebastien Boeuf
8031ac33c3 vmm: Fix virtio-vsock creation with virtual IOMMU
If the virtio-vsock device is supposed to be placed behind the virtual
IOMMU, this must be explicitly propagated through the code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 19:34:31 +01:00
Samuel Ortiz
50134969b9 Jenkins: Run musl unit and integration tests on master branch
And use a bumped up container image for that.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 17:57:01 +01:00
Samuel Ortiz
ce794f7858 ci: Pass target triple to the test scripts
We pass it to the integration and unit tests script through --libc.
Cargo tests are left unmodified.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-29 17:57:01 +01:00
Samuel Ortiz
33b0e15804 resources: Add musl tools and toolchain to the Dockerfile
And fix the libssl install for building it with musl.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-29 17:57:01 +01:00
Samuel Ortiz
ad9374bd68 dev_cli: Add --libc to the build and test commands
We only support musl and gnu, default is gnu.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-29 17:57:01 +01:00
Rob Bradford
8cef35745b vmm: seccomp: Add fork, gettid and pipe2 syscalls to permitted list
This is needed for self spawning with the musl target.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 17:57:01 +01:00
Rob Bradford
ce7678f29f vmm: seccomp: Add tkill syscall to permitted list
This is needed for rebooting on the musl target.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 17:57:01 +01:00
Rob Bradford
12758d7fad vmm: seccomp: Add epoll_pwait syscall to permitted list
This is needed for basic operation on the musl target.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 17:57:01 +01:00
Samuel Ortiz
86fcd19b8a build: Initial musl support
Fix all build failures and add musl to the gihub workflows.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-29 17:57:01 +01:00
Sebastien Boeuf
a5de49558e vmm: Only allow removal of specific types of virtio device
Now that all virtio devices are assigned with identifiers, they could
all be removed from the VM. This is not something that we want to allow
because it does not make sense for some devices. That's why based on the
device type, we remove the device or we return an error to the user.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 13:33:19 +01:00
Sebastien Boeuf
9ed880d74e vmm: Add an identifier to the --fs device
By giving the devices ids this effectively enables the removal of the
device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 13:33:19 +01:00
Sebastien Boeuf
7e0ab6b56d vmm: Fix pmem device creation
The parameters regarding the attachment to the virtio-iommu device was
not propagated correclty, and any modification to the configuration was
not stored back into it.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-29 13:33:19 +01:00
Rob Bradford
3012975c17 tests: Enhance vsock integration test to support hotplug
Test basic vsock functionality works with hotplugged vsock device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
6c2bca5f1b bin: ch-remote: Add support for adding vsock devices
Add support for adding a vsock device using the HTTP API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
8de7448d44 vmm: api: Add "add-vsock" API entry point
This allows the hotplugging of vsock devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
bf09a1e695 openapi: Add "id" field to VsockConfig
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
a76cf0865f vmm: vm: Remove vsock device from config
When doing device unplug remove the vsock device from the configuration
if present.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
99422324a7 vmm: vm: Add "add_vsock()"
Add the vsock device to the device manager and patch the config to add
the new vsock device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
1d61c476a1 vmm: device_manager: Add support for hotplugging virtio-vsock devices
Create a new VirtioVsock device and add it to the PCI bus upon hotplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
f8501a3bd3 vmm: config: Move --vsock syntax to VsockConfig
This means it can be reused with ch-remote.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Sebastien Boeuf
6e049e0da1 vmm: Add an identifier to the --vsock device
It's possible to have multiple vsock devices so in preparation for
hotplug/unplug it is important to be able to have a unique identifier
for each device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-29 12:44:49 +01:00
Rob Bradford
10348f73e4 vmm, main: Support only zero or one vsock devices
The Linux kernel does not support multiple virtio-vsock devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-28 20:07:18 +02:00
Rob Bradford
9d1f95a3cc openapi: Add missing "id" field
NetConfig/DiskConfig/PmemConfig/FsConfig were all missing the id field
in the API yaml file.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-28 18:27:45 +02:00
dependabot-preview[bot]
30e2e51588 build(deps): bump serde_json from 1.0.51 to 1.0.52
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.51 to 1.0.52.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.51...v1.0.52)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-28 14:09:57 +02:00
dependabot-preview[bot]
dd9d0d0440 build(deps): bump micro_http from 0d87a94 to c9ffb90
Bumps [micro_http](https://github.com/firecracker-microvm/micro-http) from `0d87a94` to `c9ffb90`.
- [Release notes](https://github.com/firecracker-microvm/micro-http/releases)
- [Commits](0d87a94c8e...c9ffb90aeb)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-28 10:21:55 +01:00
dependabot-preview[bot]
cdc8493a05 build(deps): bump thiserror from 1.0.15 to 1.0.16
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.15 to 1.0.16.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.15...1.0.16)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-28 08:01:55 +02:00
dependabot-preview[bot]
f5debc4bc0 build(deps): bump libssh2-sys from 0.2.16 to 0.2.17
Bumps [libssh2-sys](https://github.com/alexcrichton/ssh2-rs) from 0.2.16 to 0.2.17.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/libssh2-sys-0.2.16...libssh2-sys-0.2.17)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-27 09:10:14 +02:00
dependabot-preview[bot]
37dfb4cbb3 build(deps): bump hermit-abi from 0.1.11 to 0.1.12
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.11 to 0.1.12.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/compare/hermit-abi-0.1.11...hermit-abi-0.1.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-27 09:10:02 +02:00
Muminul Islam
e1a07ce3c4 vmm: vm: Unpark the threads before shutdown when the current state is paused
If the current state is paused that means most of the handles got killed by pthread_kill
We need to unpark those threads to make the shutdown worked. Otherwise
The shutdown API hangs and the API is not responding afterwards. So
before the shutdown call we need to resume the VM make it succeed.

Fixes: #817

Signed-off-by: Muminul Islam <muislam@microsoft.com>
2020-04-27 09:09:12 +02:00
Rob Bradford
1df38daf74 vmm, tests: Make specifying a size optional for virtio-pmem
If a size is specified use it (in particular this is required if the
destination is a directory) otherwise seek in the file to get the size
of the file.

Add a new check that the size is a multiple of 2MiB otherwise the kernel
will reject it.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-24 18:30:05 +01:00
Rob Bradford
7481e4d959 vmm: config: Validate that shared memory is enabled if using vhost-user
Check that if any device using vhost-user (net & disk with
vhost_user=true) or virtio-fs is enabled then check shared memory is
also enabled.

Fixes: #848

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-24 16:01:49 +01:00
Bo Chen
2ac6971a8b vmm: MemoryManager: Cleanup the usage of std::ffi/io/result
Signed-off-by: Bo Chen <chen.bo@intel.com>
2020-04-23 21:39:51 +02:00
Bo Chen
3f42f86d81 vmm: Add the 'shared' and 'hugepages' controls to MemoryConfig
The new 'shared' and 'hugepages' controls aim to replace the 'file'
option in MemoryConfig. This patch also updated all related integration
tests to use the new controls (instead of providing explicit paths to
"/dev/shm" or "/dev/hugepages").

Fixes: #1011

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
Signed-off-by: Bo Chen <chen.bo@intel.com>
2020-04-23 21:39:51 +02:00
dependabot-preview[bot]
d6aa717913 build(deps): bump syn from 1.0.17 to 1.0.18
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.17 to 1.0.18.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.17...1.0.18)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-23 21:32:53 +02:00
Jose Carlos Venegas Munoz
3eaeba4b55 vm-virtio: Fix FS_IO callback for virtio-fs
FS_IO is part of the actions a vhost-user-fs daemon can ask the VMM to
perform on its behalf. It is meant to read/write the content from a file
descriptor directly into a guest memory region. This region can either
be a RAM region or the dedicated cache region for virtio-fs.

The way FS_IO was implemented, it was only expecting the guest physical
address provided through the "cache_offset" field to refer to the cache
region. Unfortunately, this was only implementing FS_IO partially.

This patch extends the existing FS_IO implementation by checking the GPA
against the cache region as a first step, but if it is not part of the
cache region address range, then we fallback onto searching for a RAM
region that could match. If there is a matching RAM region, we retrieve
the corresponding host address to let the VMM read/write from/to it.

Fixes: #1054

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2020-04-23 15:01:28 +01:00
dependabot-preview[bot]
df14a68e87 build(deps): bump smallvec from 1.3.0 to 1.4.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.3.0 to 1.4.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.3.0...v1.4.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-23 14:38:39 +02:00
Samuel Ortiz
e685854f16 gh: Separate the build and release jobs
The release one is always skipped for PRs which can be confusing for
e.g. dependabot.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-23 13:45:12 +02:00
Rob Bradford
c790bba905 tests: Migrate from Ubuntu Eoan to Focal
This is the latest LTS release.

Fixes: #989

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-23 13:01:02 +02:00
dependabot-preview[bot]
e525af7a61 build(deps): bump ryu from 1.0.3 to 1.0.4
Bumps [ryu](https://github.com/dtolnay/ryu) from 1.0.3 to 1.0.4.
- [Release notes](https://github.com/dtolnay/ryu/releases)
- [Commits](https://github.com/dtolnay/ryu/compare/1.0.3...1.0.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-23 12:29:14 +02:00
Sebastien Boeuf
3e8a6ba0c0 ci: Ignore test_snapshot_restore
The newly added integration test "test_snapshot_restore" is very
unstable, which causes our CI to fail on most pull requests, which is
not acceptable. That's why we ignore this test until we can fix the
stability issue.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-23 11:38:47 +02:00
dependabot-preview[bot]
9ebf052538 build(deps): bump cc from 1.0.51 to 1.0.52
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.51 to 1.0.52.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.51...1.0.52)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-22 22:19:53 +02:00
Sebastien Boeuf
f6b150a34d ci: Add integration test for VM migration
Now that we have multiple virtio devices supporting snapshot and restore
operations, we can add a new integration test to validate the migration
feature works as expected.

The important part is virtio-net as it is used to ssh into the VM to
verify the VM has been restored in the proper state.

This test only works for virtio-mmio for now. Further support for
testing virtio-pci will be added once the virtio-pci transport layer
will support migration.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-22 22:19:31 +02:00
dependabot-preview[bot]
9f08f537e0 build(deps): bump pin-utils from 0.1.0-alpha.4 to 0.1.0
Bumps [pin-utils](https://github.com/rust-lang-nursery/pin-utils) from 0.1.0-alpha.4 to 0.1.0.
- [Release notes](https://github.com/rust-lang-nursery/pin-utils/releases)
- [Commits](https://github.com/rust-lang-nursery/pin-utils/compare/0.1.0-alpha.4...0.1.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-22 20:18:42 +02:00
Yang Zhong
9c7215d620 docs: Add the vhost-user-blk test doc
This doc describe how to use vhost-user-blk in Cloud Hypervisor
with SPDK. With this doc, we can setup simple test environment on
Ubuntu release.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-04-22 20:18:23 +02:00
dependabot-preview[bot]
35744375e0 build(deps): bump cc from 1.0.50 to 1.0.51
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.50 to 1.0.51.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.50...1.0.51)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-22 17:10:21 +02:00
Yi Sun
4fc75cf2b0 vm-virtio: Implement Snapshottable trait for Console
This patch implements the Snapshottable trait for virtio-console, which
enables migration support for it. A VM with a virtio-console device
attached can be snapshot and then restored without issues.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-22 14:45:16 +02:00
Yi Sun
d41ce909a2 vm-virtio: Implement Snapshottable trait for Pmem
This brings the migration support to virtio-pmem device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-22 14:45:02 +02:00
dependabot-preview[bot]
f626bd60c5 build(deps): bump parking_lot_core from 0.7.1 to 0.7.2
Bumps [parking_lot_core](https://github.com/Amanieu/parking_lot) from 0.7.1 to 0.7.2.
- [Release notes](https://github.com/Amanieu/parking_lot/releases)
- [Changelog](https://github.com/Amanieu/parking_lot/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Amanieu/parking_lot/compare/0.7.1...core-0.7.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-22 09:12:08 +02:00
Martin Xu
5a380a6918 vmm: memory_manager: Support non-power-of-2 block sizes
Replace alignment calculation of start address with functionally
equivalent version that does not assume that the block size is a power
of two.

Signed-off-by: Martin Xu <martin.xu@intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-22 09:11:51 +02:00
dependabot-preview[bot]
f8ee89a514 build(deps): bump arc-swap from 0.4.5 to 0.4.6
Bumps [arc-swap](https://github.com/vorner/arc-swap) from 0.4.5 to 0.4.6.
- [Release notes](https://github.com/vorner/arc-swap/releases)
- [Changelog](https://github.com/vorner/arc-swap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/arc-swap/compare/v0.4.5...v0.4.6)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-21 22:08:17 +02:00
Sebastien Boeuf
49322c5ebe vm-virtio: Implement the Snapshottable trait for Net
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-21 21:25:03 +02:00
Sebastien Boeuf
24c2b67aa4 vm-virtio: Improve virtio-net rx queue processing
The frame buffer must be updated depending on the amount read from it,
which depends on the number and depth of descriptors available at the
time of the processing.

This patch handles this buffer update, and allow for large buffers to be
correctly processed in multiple rounds.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 21:25:03 +02:00
Sebastien Boeuf
03dd24978e vm-virtio: Restore queues based on used index
On the restore path, using the available and used indexes read from
memory to fill the Queue structure was a mistake. Indeed, the available
index is written from the guest and it reflects the last available index
in the descriptor table. But the driver might have queued a lot of
buffers which have not yet been used by the device. This leads to a
situation where the next_avail from Queue is completely different from
the one we can read from memory.

Instead, the right way to determine the next_avail index that should be
used by the device is by relying on the used index from the memory. This
index represents the correct information we're looking for as it has
been updated before the snapshot to let the guest know the next index to
process.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 21:25:03 +02:00
Sebastien Boeuf
cf707da1a8 vm-virtio: Extend Queue helpers
First, this modifies the existing helpers on how to get indexes for
available and used rings from memory. Instead of updating the queue
through each helper, they are now used as simple getters.

Based on these new getters, we could create a new helper to determine if
the queue has some available descriptors already queued from the driver
side. This helper is going to be particularly helpful when trying to
determine from a virtio thread if a queue is already loaded with some
available buffers that can be used to send information to the guest.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 21:25:03 +02:00
Sebastien Boeuf
c22fd39170 vmm: Remove virtio device's userspace mapping on hot-unplug
When a virtio device is dynamically removed from the VM through the
hot-unplug mechanism, every mapping associated with it must be properly
removed.

Based on the previous patches letting a VirtioDevice expose the list of
userspace mappings associated with it, this patch can now remove all the
KVM userspace memory regions through the MemoryManager.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
Sebastien Boeuf
0a97c25464 vmm: Extend MemoryManager to remove userspace mappings
The same way we added a helper for creating userspace memory mappings
from the MemoryManager, this patch adds a new helper to remove some
previously added mappings.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
Sebastien Boeuf
b2de1cd523 vm-virtio: Implement shutdown() for virtio-fs
Since the virtio-fs device is backed by a vhost-user process, it is
important to implement the proper shutdown() function from the
VirtioDevice trait, as vhost-user-blk and vhost-user-net do.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
Sebastien Boeuf
fbcf3a7a7a vm-virtio: Implement userspace_mappings() for virtio-pmem
When hot-unplugging the virtio-pmem from the VM, we don't remove the
associated userspace mapping. This patch will let us fix this in a
following patch. For now, it simply adapts the code so that the Pmem
device knows about the mapping associated with it. By knowing about it,
it can expose it to the caller through the new userspace_mappings()
function.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
Sebastien Boeuf
b0353992d6 vm-virtio: Implement userspace_mappings() for virtio-fs
This will help when we will implement the hot-unplug of the virtio-fs
device, as we will have to remove correctly the userspace mappings
associated with the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
Sebastien Boeuf
3fb0a02fa2 vm-virtio: Get userspace mappings from VirtioDevice
Introduce new getter function to the VirtioDevice trait, as it will
allow the caller to retrieve the list of userspace mappings associated
with the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-21 10:02:21 +01:00
dependabot-preview[bot]
8b823e5e34 build(deps): bump backtrace-sys from 0.1.35 to 0.1.36
Bumps [backtrace-sys](https://github.com/alexcrichton/backtrace-rs) from 0.1.35 to 0.1.36.
- [Release notes](https://github.com/alexcrichton/backtrace-rs/releases)
- [Commits](https://github.com/alexcrichton/backtrace-rs/compare/backtrace-sys-0.1.35...backtrace-sys-0.1.36)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-20 21:49:34 +00:00
Sebastien Boeuf
c23b48888d ci: Factorize virtio-fs hotplug integration tests
There is some duplication between regular and hotplug virtio-fs tests
that can be factorized by adding a simple hotplug flag to choose if each
test should run with or without hotplugging the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-20 20:36:26 +02:00
Dean Sheather
f68b08bfdb tests: add integration tests for vm.add-fs route
Adds integration tests with and without dax for the new vm.add-fs route.

Signed-off-by: Dean Sheather <dean@coder.com>
2020-04-20 20:36:26 +02:00
Sebastien Boeuf
18f7789a81 vmm: Add hotplugged virtio devices to the DeviceManager list
The hotplugged virtio devices were not added to the list of virtio
devices from the DeviceManager. This patch fixes it, as it was causing
hotplugged virtio-fs devices from not supporting memory hotplug, since
they were never getting the update as they were not part of the list of
virtio devices held by the DeviceManager.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-20 20:36:26 +02:00
Dean Sheather
c2abadc293 vmm: Add ability to add virtio-fs device post-boot
Adds DeviceManager method `make_virtio_fs_device` which creates a single
device, and modifies `make_virtio_fs_devices` to use this method.

Implements the new `vm.add-fs route`.

Signed-off-by: Dean Sheather <dean@coder.com>
2020-04-20 20:36:26 +02:00
Dean Sheather
bb2139a408 vmm/api: Add vm.add-fs route
Currently unimplemented. Once implemented, this API will allow for
creating virtio-fs devices in the VM after it has booted.

Signed-off-by: Dean Sheather <dean@coder.com>
2020-04-20 20:36:26 +02:00
Sebastien Boeuf
d35e775ed9 vmm: Update KVM userspace mapping when PCI BAR remapping
In the context of the shared memory region used by virtio-fs in order to
support DAX feature, the shared region is exposed as a dedicated PCI
BAR, and it is backed by a KVM userspace mapping.

Upon BAR remapping, the BAR is moved to a different location in the
guest address space, and the KVM mapping must be updated accordingly.

Additionally, we need the VirtioDevice to report the updated guest
address through the shared memory region returned by get_shm_regions().
That's why a new setter is added to the VirtioDevice trait, so that
after the mapping has been updated for KVM, we can tell the VirtioDevice
the new guest address the shared region is located at.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-20 16:01:25 +02:00
Sebastien Boeuf
49cc73a4ca vm-virtio: pci: Make sure to return the correct list of BARs
By adding the shared memory regions to the list of BARs, we make sure
the DeviceManager will register it as a BAR on the PCI bus. Without
this, when PCI BAR reprogramming happens, the PCI bus errors since it
does not know about any BAR at the specified address.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-20 16:01:25 +02:00
Yi Sun
187b1eec8b vm-virtio: Implement the Snapshottable trait for Block
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-17 19:29:41 +02:00
Samuel Ortiz
a484aa7be6 vm-virtio: Implement the Snapshottable trait for Rng
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-17 19:29:41 +02:00
Sebastien Boeuf
ac7178ef2a vmm: Keep migratable devices list as a Vec
The order the elements are pushed into the list is important to restore
them in the right order. This is particularly important for MmioDevice
(or VirtioPciDevice) and their VirtioDevice counterpart.

A device must be fully ready before its associated transport layer
management can trigger its restoration, which will end up activating the
device in most cases.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 19:29:41 +02:00
Sebastien Boeuf
b6fdbf7a44 vm-virtio: Implement Snapshottable trait for MmioDevice
Any virtio device relying on the mmio transport layer can be snapshotted
and restored thanks to this new patch. From the MmioDevice perspective,
it is mainly a matter of saving the information about the virtqueues as
the restore path will need them to activate the device (if needed
because it has been activated before being snapshotted).

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 19:29:41 +02:00
Sebastien Boeuf
12fec55064 vm-virtio: Add helpers to update queue indexes
In anticipation for adding snapshot/restore support to virtio devices,
this commit introduces two new helpers updating the available and used
indexes of a queue, relying on the guest memory.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 19:29:41 +02:00
Samuel Ortiz
fd45e94510 vm-virtio: Add the ability to serialize a Queue
This commit relies on serde to serialize and deserialize the content of
a Queue structure. This will be useful information to store when
implementing snapshot/restore feature for virtio devices.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-17 19:29:41 +02:00
Sergio Lopez
b7faf4fdc1 vhost_user_fs: Add the WRITE_KILL_PRIV write flag.
Add the WRITE_KILL_PRIV write flag, corresponding to
FUSE_WRITE_KILL_PRIV introduced in 7.31, and use to only remove the
setuid and setgid bits (by switching credentials) conditionally.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
0870028fde vhost_user_fs: Add the IOCTL_COMPAT_32 flag
Add the IOCTL_COMPAT_32 flag, corresponding to FUSE_IOCTL_COMPAT_32
introduced in FUSE 7.30.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
592cfbafb3 vhost_user_fs: Add the EXPLICIT_INVAL_DATA capability flag
Add EXPLICIT_INVAL_DATA capability flag, corresponding to
FUSE_EXPLICIT_INVAL_DATA introduced in FUSE 7.30.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
621ea837fa vhost_user_fs: Add the ZERO_MESSAGE_OPENDIR capability flag
Add ZERO_MESSAGE_OPENDIR capability flag, corresponding to
FUSE_NO_OPENDIR_SUPPORT introduced in FUSE 7.29.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
a2830da7c0 vhost_user_fs: Add the CACHE_SYMLINKS flag
Add the CACHE_SYMLINKS flag, corresponding to FUSE_CACHE_SYMLINKS
introduced in FUSE 7.28.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
926a414b90 vhost_user_fs: Add support for MAX_PAGES
Add support for MAX_PAGES, corresonding to FUSE_MAX_PAGES introduced
in FUSE 7.28.

This allows us to negotiate with the kernel the maximum number of
pages that we support to transfer in a single request.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
747f31d82c vhost_user_fs: Add the ABORT_ERROR flag
Add the ABORT_ERROR flag, corresponding to FUSE_ABORT_ERROR,
introduced in FUSE 7.27.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
5eb903a509 vhost_user_fs: Add support for FOPEN_CACHE_DIR
Add support for FOPEN_CACHE_DIR, a flag that allows us to tell the
guest that it's safe to cache a directory, introduced in FUSE 7.28.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Sergio Lopez
97e2d5d266 vhost_user_fs: Add support for CopyFileRange
Add support for the CopyFileRange request, introduced in FUSE 7.28.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-04-17 15:42:40 +01:00
Rob Bradford
b8cfdab8b6 pci: configuration: Use correct algorithm for BAR size reporting
When reporting the BAR size it is necessary to return a value that is
encoded such that all the bits are set that represent the mask of the
natural alignment of the field.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-17 15:20:50 +02:00
Rob Bradford
9bd5ec8967 pci, vfio, vm-virtio: Specify a PCI revision ID of 1 for virtio-pci
Add support for specifying the PCI revision in the PCI configuration and
populate this with the value of 1 for virtio-pci devices.

The virtio-pci specification is slightly ambiguous only saying that
transitional (i.e. devices that support legacy and virtio 1.0) should
set this to 0. In practice it seems that software expects the revision
to be set to 1 for modern only devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-17 13:46:48 +02:00
Rob Bradford
e7e0e8ac38 vmm, devices: Add firmware debug port device
OVMF and other standard firmwares use I/O port 0x402 as a simple debug
port by writing ASCII characters to it. This is gated under a feature
that is not enabled by default.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-17 12:54:00 +02:00
Sebastien Boeuf
82d0cdff4f vhost_user_net: Simplify match values for handle_event()
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Sebastien Boeuf
a517be4eac vhost_user_blk: Add multithreaded multiqueue support
After all the previous refactoring patches, we can finally create
multiple threads under the same backend. This is directly combined with
multiqueues so that it will create one thread per queue.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Sebastien Boeuf
13c8283fbe vhost_user_blk: Make everything private when possible
Doing some cleanup as most of the code does not need to be public.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Sebastien Boeuf
a31f5f8106 vhost_user_blk: Move disk initialization to VhostUserBlkBackend
Anticipating the follow up patches to run multiple threads for the same
backend, we need the initialization of the disk to happen in the high
level structure VhostUserBlkBackend.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Sebastien Boeuf
e78e34b36a vhost_user_blk: Make DiskFile sharable across threads
The DiskFile will need to be shared across multiple threads when running
multiple queues across these threads. That's why it needs to be put
inside an Arc. The reason for the Mutex is because execute() expects a
mutable object implementing Read + Write + Seek. Unfortunately, this
create a contention point as the object needs to be locked from each
thread, reducing the performance gain we will get with multiple threads.

The need for an immutable object would solve this problem, and it will
be addressed later through follow up patches.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Sebastien Boeuf
808586ece7 vhost_user_blk: Simplify the code by removing VringWorker
There is no need for retrieving the VringWorker since we don't need to
register some extra file descriptors to the epoll loop.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-17 12:52:28 +02:00
Rob Bradford
ea82632c70 tests: Enhance test_pmem_hotplug to also unplug device
Ensure that the device is removed and the removed device stays away
after a reboot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
6389418fa6 tests: Enhance test_disk_hotplug to also unplug device
Ensure that the device is removed and the removed device stays away
after a reboot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
f9a0445c3d vmm: vm: Remove device from configuration after unplug
This ensures that a device that is removed will not reappear after a
reboot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
444e5c2a04 vmm: device_manager: Generalise NoAvailableVfioDeviceName
We now support assigning device ids for VFIO and virtio-pci devices so
this error can be generalised.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
5bab9c3894 vmm: device_manager: Assign ids to pmem/net/disk devices if absent
If the id has not been provided by the user generate an incrementing id.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
514491a051 vmm: device_manager: Support unplugging virtio-pci devices
Extend the eject_device() method on DeviceManager to also support
virtio-pci devices being unplugged.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
2fa652aa4c vm-virtio: pci: Add virtio_device() accessor
Add an accessor to return the underlying VirtioDevice. This is useful
for managing the removal of the device from internal datastructures when
handling virtio-pci device unplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
476e4ce24f vmm: device_manager: Add virtio-pci devices into id to BDF map
In order to support hotplugging there is a map of human readable device
id to PCI BDF map.

As the device id is part of the specific device configuration (e.g.
NetConfig) it is necessary to return the id through from the helper
functions that create the devices through to the functions that add
those devices to the bus. This necessitates changing a great deal of
function prototypes but otherwise has little impact.

Currently only if an id is supplied by the user as part of the device
configuration is it populated into this map. A later commit will
populate with an autogenerated name where none is supplied by the user.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
b38470df4b vmm: config: Add "id" parameter to {Net, Disk, Pmem}Config
This id will be used to unplug the device if the user has chosen an id.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
Rob Bradford
1beb62ed2d vmm: vm: Don't panic on kernel load error
Rather than panic()ing when we get a kernel loading error populate the
error upwards.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-16 17:03:25 +02:00
dependabot-preview[bot]
a8ec8f3326 build(deps): bump hermit-abi from 0.1.10 to 0.1.11
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.10 to 0.1.11.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/compare/hermit-abi-0.1.10...hermit-abi-0.1.11)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-15 18:27:24 +00:00
dependabot-preview[bot]
6cc8248a37 build(deps): bump num_cpus from 1.12.0 to 1.13.0
Bumps [num_cpus](https://github.com/seanmonstar/num_cpus) from 1.12.0 to 1.13.0.
- [Release notes](https://github.com/seanmonstar/num_cpus/releases)
- [Changelog](https://github.com/seanmonstar/num_cpus/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/num_cpus/compare/v1.12.0...v1.13.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-15 18:27:18 +00:00
Rob Bradford
8ff3633782 vm-virtio: pci: Update the BARs used by the VirtioPciDevice
In order to support freeing the memory that is allocated we need to make
sure that we update the internal representation so that free_bars() can
correctly free the memory if the device has its BARs moved.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-15 12:02:19 +02:00
Rob Bradford
56207a0328 pci: Print out details of the BAR moving upon error
In particular include the old and new bases as well as the length.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-15 12:02:19 +02:00
Rob Bradford
a216c2ebd3 vm-virtio: pci: Implement free_bars() for VirtioPciDevice
Implement the free_bars() method from the PciDevice trait which is used
as part of the device removal process. Although there is only one BAR
allocated by VirtioPciDevice simplify the code by using a vector.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-15 12:02:19 +02:00
Rob Bradford
72fdfff15d vmm: device_manager: Remove unused "_mmap_regions" member
Now that ownership of the memory regions used for the virtio-pmem and
vhost-user-fs devices have been moved into those devices it is no longer
necessary to track them inside DeviceManager.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-14 17:46:11 +01:00
Rob Bradford
70ecd6bab4 vmm, virtio: fs: Move freeing of mappped region into device
Move the release of the managed memory region from the DeviceManager to
the vhost-user-fs device. This ensures that the memory will be freed when
the device is unplugged which will lead to it being Drop()ed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-14 17:46:11 +01:00
Rob Bradford
0c6706a510 vmm, virtio: pmem: Move freeing of mappped region into device
Move the release of the managed memory region from the DeviceManager to
the virtio-pmem device. This ensures that the memory will be freed when
the device is unplugged which will lead to it being Drop()ed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-14 17:46:11 +01:00
Sebastien Boeuf
6565e478e6 vhost_user_net: Enable multithreaded multiqueue support
By implementing queues_per_thread(), this patch fills the last missing
bit to enable multithreaded multiqueue support for the vhost-user-net
backend implementation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
1a0a2c0182 vhost_user_backend: Provide the thread ID to handle_event()
By adding a "thread_id" parameter to handle_event(), the backend crate
can now indicate to the backend implementation which thread triggered
the processing of some events.

This is applied to vhost-user-net backend and allows for simplifying a
lot the code since each thread is identical.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
cfffb7edb0 vhost_user_backend: Allow for one exit_event per thread
By adding the "thread_index" parameter to the function exit_event() from
the VhostUserBackend trait, the backend crate now has the ability to ask
the backend implementation about the exit event related to a specific
thread.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
b927dceed8 vhost_user_net: Prepare for multithreaded support
In order to prepare for the support of multithreaded multiqueues, the
structure VhostUserNetThread is simplified to hold only one RX queue,
one TX queue, and one TAP interface.

Following this change, VhostUserNetBackend now holds a list of threads
instead of going through each thread to handle multiqueues.

These changes decouple neatly the abstraction between the backend and
each thread. This allows for a lot of simplification since we now know
all threads are identical, hence the handling of events becomes very
straightforward.

One important point is that each thread can be locked when in use,
without causing any contention with other threads since the backend
doesn't need to be locked anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
cd2b03f6ed vhost_user_backend: Return a list of vring workers
Now that multiple worker threads can be run from the backend crate, it
is important that each backend implementation can access every worker
thread.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
d9eec0de14 vhost_user_backend: Add the ability to start multiple threads
In order to support multiqueues running on multiple threads for
increasing the IO performances, this commit introduces a new function
queues_per_thread() to the VhostUserBackend trait.

This gives each backend implementation the opportunity to define which
queues belong to which thread.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
40e4dc6339 vhost_user_backend: Change handle_event as immutable
By changing the mutability of this function, after adapting all
backends, we should be able to implement multithreads with
multiqueues support without hitting a bottleneck on the backend
locking.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
8f434df1fb vhost_user: Adapt backends to let handle_event be immutable
Both blk, net and fs backends have been updated to avoid the requirement
of having handle_event(&mut self). This will allow the backend crate to
avoid taking a write lock onto the backend object, which will remove the
potential contention point when multiple threads will be handling
multiqueues.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
Sebastien Boeuf
b1554642e4 vmm: seccomp: Add missing mremap() syscall
While testing self spawned vhost-user backends, it appeared that the
backend was aborting due to a missing system call in the seccomp
filters. mremap() was the culprit and this patch simply adds it to the
whitelist.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-14 14:11:41 +02:00
dependabot-preview[bot]
886c0f9093 build(deps): bump libc from 0.2.68 to 0.2.69
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.68 to 0.2.69.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.68...0.2.69)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-14 09:27:04 +01:00
dependabot-preview[bot]
6c164c761b build(deps): bump thiserror from 1.0.14 to 1.0.15
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.14 to 1.0.15.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.14...1.0.15)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-13 08:33:58 +02:00
dependabot-preview[bot]
0071ac8c30 build(deps): bump parking_lot from 0.10.0 to 0.10.2
Bumps [parking_lot](https://github.com/Amanieu/parking_lot) from 0.10.0 to 0.10.2.
- [Release notes](https://github.com/Amanieu/parking_lot/releases)
- [Changelog](https://github.com/Amanieu/parking_lot/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Amanieu/parking_lot/compare/0.10.0...0.10.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-11 01:25:39 +02:00
dependabot-preview[bot]
2b7fbcb99a build(deps): bump lock_api from 0.3.3 to 0.3.4
Bumps [lock_api](https://github.com/Amanieu/parking_lot) from 0.3.3 to 0.3.4.
- [Release notes](https://github.com/Amanieu/parking_lot/releases)
- [Changelog](https://github.com/Amanieu/parking_lot/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Amanieu/parking_lot/compare/lock_api-0.3.3...lock_api-0.3.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-10 19:20:27 +02:00
dependabot-preview[bot]
d1155c7c7f build(deps): bump parking_lot_core from 0.7.0 to 0.7.1
Bumps [parking_lot_core](https://github.com/Amanieu/parking_lot) from 0.7.0 to 0.7.1.
- [Release notes](https://github.com/Amanieu/parking_lot/releases)
- [Changelog](https://github.com/Amanieu/parking_lot/blob/master/CHANGELOG.md)
- [Commits](https://github.com/Amanieu/parking_lot/compare/0.7.0...0.7.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-10 19:20:17 +02:00
Rob Bradford
28abfa9de5 vmm: openapi: Mark "initramfs" field nullable
This should make it a pointer in the Go generated code so that it will
be ommitted and thus not populated with an unhelpful default value.

Fixes: #1015

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-09 23:25:18 +02:00
Rob Bradford
c260640fd5 vmm: config: Use Default::default() value for initramfs field
This ensures that the field is filled with None when it is not specified
as part of the deserialisation step.

Fixes: #1015

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-09 17:28:45 +02:00
Alejandro Jimenez
4617aefd60 tests: Test initramfs loading with PVH boot
Add an integration test to verify loading an initramfs using the
PVH boot protocol.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-04-09 17:28:03 +02:00
Alejandro Jimenez
7134f3129f vmm: Allow PVH boot with initramfs
We can now allow guests that specify an initramfs to boot
using the PVH boot protocol.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-04-09 17:28:03 +02:00
Alejandro Jimenez
0fc3936448 arch: Support loading initramfs with PVH boot protocol
Fill and write to guest memory the necessary boot module
structure to allow a guest using the PVH boot protocol
to load an initramfs image.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-04-09 17:28:03 +02:00
dependabot-preview[bot]
b9f193703a build(deps): bump smallvec from 1.2.0 to 1.3.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.2.0 to 1.3.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.2.0...v1.3.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-09 06:07:36 +00:00
Rob Bradford
2d3f518c72 vmm: config: Error if both socket and path are specified for a disk
This allows the validation of this requirement for both command line
booted VMs and those booted via the API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
eeb7e2529d vmm: config: Move max vCPUs > boot vCPUs check to validate()
This allows the validation of this requirement for both command line
booted VMs and those booted via the API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
12edb24678 vmm: config: Validate that serial/console file mode has a path
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
31928fb103 main: Consistently use eprintln!() for error messages
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
11dd609fa5 main: Only try and parse VM options on VM boot path
As the VmConfig::Parse() also does validation work it only make sense to
parse the VM options on the VM boot path only.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
aaf382eee2 vmm: Move kernel check to VmConfig::validate() method
Replace the existing VmConfig::valid() check with a call into
.validate() as part of earlier config setup or boot API checks.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
3b0da2d895 vmm: vm: Validate configuration on API boot
When performing an API boot validate the configuration. For now only
some very basic validation is performed but in subsequent commits
the validation will be extended.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Rob Bradford
99b2ada4d0 vmm: Start splitting configuration parsing and validation
The configuration comes from a variety of places (commandline, REST API
and restore) however some validation was only happening on the command
line parsing path.  Therefore introduce a new ability to validate the
configuration before proceeding so that this can be used for commandline
and API boots.

For now move just the console and serial output mode validation under
the new validation API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-08 12:06:09 +01:00
Sebastien Boeuf
0ea706faf5 vmm: openapi: Update OpenAPI definition with RestoreConfig
Making sure the OpenAPI definition is up to date with newly added
structure and parameters to support VM restoration.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
8d9d22436a vmm: Add "prefault" option when restoring
Now that the restore path uses RestoreConfig structure, we add a new
parameter called "prefault" to it. This will give the user the ability
to populate the pages corresponding to the mapped regions backed by the
snapshotted memory files.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
a517ca23a0 vmm: Move restore parameters into common RestoreConfig structure
The goal here is to move the restore parameters into a dedicated
structure that can be reused from the entire codebase, making the
addition or removal of a parameter easier.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
6712958f23 vmm: memory: Add prefault option when creating region
When CoW can be used, the VM restoration time is reduced, but the pages
are not populated. This can lead to some slowness from the guest when
accessing these pages.

Depending on the use case, we might prefer a slower boot time for better
performances from guest runtime. The way to achieve this is to prefault
the pages in this case, using the MAP_POPULATE flag along with CoW.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
b2cdee80b6 vmm: memory: Restore with Copy-on-Write when possible
This patch extends the previous behavior on the restore codepath.
Instead of copying the memory regions content from the snapshot files
into the new memory regions, the VMM will use the snapshot region files
as the backing files behind each mapped region. This is done in order to
reduce the time for the VM to be restored.

When the source VM has been initially started with a backing file, this
means it has been mapped with the MAP_SHARED flag. For this case, we
cannot use the CoW trick to speed up the VM restore path and we simply
fallback onto the copy of the memory regions content.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
d771223b2f vmm: memory: Extend new() to support external backing files
Whenever a MemoryManager is restored from a snapshot, the memory regions
associated with it might need to directly back the mapped memory for
increased performances. If that's the case, a list of external regions
is provided and the MemoryManager should simply ignore what's coming
from the MemoryConfig.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
ee5a041a0f vmm: memory: Add Copy-on-Write parameter when creating region
Now that we can choose specific mmap flags for the guest RAM, we create
a new parameter "copy_on_write" meaning that the memory mappings backed
by a file should be performed with MAP_PRIVATE instead of MAP_SHARED.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
Sebastien Boeuf
be4e1e8712 vmm: memory: Use fine grained mmap wrapper
In order to anticipate the need for special mmap flags when memory
mapping the guest RAM, we need to switch from from_file() wrapper to
build() wrapper.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-08 10:56:14 +02:00
dependabot-preview[bot]
f0ab002ef1 build(deps): bump openssl-sys from 0.9.54 to 0.9.55
Bumps [openssl-sys](https://github.com/sfackler/rust-openssl) from 0.9.54 to 0.9.55.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-sys-v0.9.54...openssl-sys-v0.9.55)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-08 06:04:24 +00:00
Sebastien Boeuf
b9f9f01fcc vmm: Extend seccomp filters to allow snapshot/restore
A few KVM ioctls were missing in order to perform both snapshot and
restore while keeping seccomp enabled.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-07 12:26:10 +02:00
Sebastien Boeuf
6eb721301c vmm: Enable restore feature
This connects the dots together, making the request from the user reach
the actual implementation for restoring the VM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-07 12:26:10 +02:00
Sebastien Boeuf
53613319cc vmm: Enable snapshot feature
This connects the dots together, making the request from the user reach
the actual implementation for snapshotting the VM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
2cd0bc0a2c vmm: Create initial VM from its snapshot
The MemoryManager is somehow a special case, as its restore() function
was not implemented as part of the Snapshottable trait. Instead, and
because restoring memory regions rely both on vm.json and every memory
region snapshot file, the memory manager is restored at creation time.
This makes the restore path slightly different from CpuManager, Vcpu,
DeviceManager and Vm, but achieve the correct restoration of the
MemoryManager along with its memory regions filled with the correct
content.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
b55b83c6e8 vmm: vm: Implement the Transportable trait
This is only implementing the send() function in order to store all Vm
states into a file.

This needs to be extended for live migration, by adding more transport
methods, and also the recv() function must be implemented.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
1ed357cf34 vmm: vm: Implement the Snapshottable trait
By aggregating snapshots from the CpuManager, the MemoryManager and the
DeviceManager, Vm implements the snapshot() function from the
Snapshottable trait.
And by restoring snapshots from the CpuManager, the MemoryManager and
the DeviceManager, Vm implements the restore() function from the
Snapshottable trait.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
20ba271b6c vmm: memory_manager: Implement the Transportable trait
This implements the send() function of the Transportable trait, so that
the guest memory regions can be saved into one file per region.

This will need to be extended for live migration, as it will require
other transport methods and the recv() function will need to be
implemented too.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Yi Sun
e606112cef vmm: memory_manager: Implement the Snapshottable trait
In order to snapshot the content of the guest RAM, the MemoryManager
must implement the Snapshottable trait.

Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-07 12:26:10 +02:00
Yi Sun
50b3f008d1 vmm: cpu: Implement the Snapshottable trait
Implement the Snapshottable trait for Vcpu, and then implements it for
CpuManager. Note that CpuManager goes through the Snapshottable
implementation of Vcpu for every vCPU in order to implement the
Snapshottable trait for itself.

Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Sebastien Boeuf
f787c409c4 vmm: cpu: Factorize vcpu starting code
Anticipating the need for a slightly different function for restoring
vCPUs, this patch factorizes most of the vCPU creation, so that it can
be reused for migration purposes.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-07 12:26:10 +02:00
Cathy Zhang
722f9b6628 vmm: cpu: Get and set KVM vCPU state
These two new helpers will be useful to capture a vCPU state and being
able to restore it at a later time.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Cathy Zhang
13756490b5 vmm: cpu: Track all Vcpus through CpuManager
In anticipation for the CpuManager to aggregate all Vcpu snapshots
together, this change makes sure the CpuManager has a handle onto
every vCPU.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
a0d5dbce6c vmm: device_manager: Implement the Snapshottable trait
Based on the list of Migratable devices stored by the DeviceManager, the
DeviceManager can implement the Snapshottable trait by aggregating all
devices snapshots together.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Yi Sun
93d3abfd6e vmm: device_manager: Make serial and ioapic devices migratable
Serial and Ioapic both implement the Migratable trait, hence the
DeviceManager can store them in the list of Migratable devices.

Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-07 12:26:10 +02:00
Samuel Ortiz
12b036a824 Cargo: Update dependencies for the KVM serialization work
We need the project to rely on kvm-bindings and kvm-ioctls branches
which include the serde derive to be able to serialize and deserialize
some KVM structures.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-07 12:26:10 +02:00
Yang Zhong
183529d024 vmm: Cleanup warning from build
Remove unnecessary parentheses from code and this will cleanup
the warning from cargo build.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-04-07 09:45:31 +02:00
Rob Bradford
22958261aa main: Print human readable error for command line error
Fixes: #367

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
c7dfbd8a84 vmm: config: Implement fmt::Display for error
Fixes: #367

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
d8119fda13 vmm: config: Remove unused error entries
These entries are not currently used.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
1a10f16ad0 vmm: config: Consolidate size parsing code
The parse_size helper function can now be consolidated into the
ByteSized FromStr implementation.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
f449486b9b vmm: config: Make toggle parsing more tolerant
Support "true" and "false" as well as well as capitalised forms.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
a4e0ce58c7 vmm: config: Consolidate on/off parsing
Now all parsing code makes use of the Toggle and it's FromStr support
move the helper function into the from_str() implementation.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
c731a943d4 vmm: config: Port vsock to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
37264cf21b vmm: config: Add unit testing for vsock
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
8665898ff3 vmm: config: Port device parsing to OptionParser
Also make the "path" option required and generate an error if it is not
provided.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
a85e2fa735 vmm: config: Add unit test for VFIO device parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
bed282b801 vmm: config: Add "valueless" options to OptionParser
Valueless options are those like "off" or "tty" as used by the console
options.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
2ae3392d32 vmm: config: Port console parsing to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
143d63c88e vmm: config: Add unit test for console parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
5ab58e743a vmm: config: Port pmem option to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
233ad78b3a vmm: config: Add parsing test for pmem
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
13dc637350 vmm: config: Port filesystem parsing to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
7a071c28db vmm: config: Implement unit testing for virtio-fs parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
e4cd3072d4 vmm: config: Port RNG options to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
708dbb973a vmm: config: Add RNG parsing unit test
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
057e71d266 vmm: config: Accept empty value strings
The integration tests and documentation make use of empty value strings
like "--net tap=" accept them but return None so that the default value
will be used as expected.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
218c780f67 vmm: config: Port network parsing to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
a5747a843e net_util: Implement FromStr for MacAddr
This allows it to be used with str::parse().

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
8754720e2d vmm: config: Add unit test for net parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
224e3ddef4 vmm: config: Switch disk parsing to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
9e10244716 vmm: config: Add unit test for disk parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
e40ae6274b vmm: config: Port memory option parsing to OptionParser
This simplifies the parsing of the option by using OptionParser along
with its automatic conversion behaviour.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
be32065aa4 vmm: config: Add "ByteSized" type for simplifying parsing of byte sizes
Byte sizes are quantities ending in "K", "M", "G" and by implementing
this type with a FromStr implementation the values can be converted
using .parse().

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
f01bd7d56d vmm: config: Implement FromStr for HotplugMethod
This allows the use of .parse() to automatically convert the string to
the enum.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
746138039d vmm: config: Add a Toggle type for "on/off" strings
Some of the config parameters take an "on" or "off". Add a way to
neatly parse that.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
929142bc2e vmm: config: Add memory parsing unit test
Before porting over to OptionParser add a unit test to validate the
current memory parsing code. This showed up a bug where the "size=" was
always required. Temporarily resolve this by assigning the string a
default value which will later be replaced when the code is refactored.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
68203ea414 vmm: config: Port CPU parsing to OptionParser
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
9e6a2825ba vmm: config: Add unit test for CPU parsing
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
Rob Bradford
9e7231cd69 vmm: config: Introduce basic OptionParser
This will be used to simplify and consolidate much of the parsing code
used for command line parameters.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-06 10:31:24 +01:00
dependabot-preview[bot]
1e20b5727d build(deps): bump serde_json from 1.0.50 to 1.0.51
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.50 to 1.0.51.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.50...v1.0.51)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-06 05:31:07 +00:00
dependabot-preview[bot]
baf4850052 build(deps): bump serde_derive from 1.0.105 to 1.0.106
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.105 to 1.0.106.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.105...v1.0.106)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-04 14:22:07 +00:00
dependabot-preview[bot]
00230905ff build(deps): bump serde from 1.0.105 to 1.0.106
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.105 to 1.0.106.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.105...v1.0.106)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-04 13:58:41 +00:00
Samuel Ortiz
447af8e702 vmm: vm: Factorize the device and cpu managers creation routine
Into a new_from_memory_manager() routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
c73c9b112c vmm: vm: Open kernel and initramfs once all managers are created
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
0646a90626 vmm: cpu: Pass CpusConfig to simplify the new() prototype
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
b584ec3fb3 vmm: memory_manager: Own the system allocator
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
ef2b11ee6c vmm: memory_manager: Pass MemoryConfig to simplify the new() prototype
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
622f3f8fb6 vmm: vm: Avoid ioapic variable creation
For a more readable VM creation routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
164e810069 vmm: cpu: Move CPUID patching to CpuManager
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
1a2c1f9751 vmm: vm: Factorize the KVM setup code
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
3eb11069d0 arch: regs: Rename and export create_msr_entries
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
c3a3490331 arch: regs: Make create_msr_entries more readable
By using simple macros.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Samuel Ortiz
7a50646c02 vmm: device_manager: Convert migratable_devices to a map
We must be able to map a migratable component id to its device.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-03 18:05:18 +01:00
Rob Bradford
8ba37a98a7 .gitignore: Add build directory
This directory contains the source code for crates that we pull in and
should be excluded.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-04-03 15:44:14 +01:00
Yi Sun
b3e4111e1d devices: serial: Implement the Snapshottable trait
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-02 19:02:57 +02:00
Yi Sun
98741573e7 devices: ioapic: Implement the Snapshottable trait
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-02 19:02:57 +02:00
Sebastien Boeuf
3ef1c00cfb ch-remote: Fix snapshot and restore subcommands
So that they are listed and can be used as expected.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 17:55:30 +01:00
Sebastien Boeuf
dc97b67dac main: Fix restore CLI
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 17:55:30 +01:00
Sebastien Boeuf
859a96181f ch-remote: Add --restore option
Introduce restore wrapper to ch-remote.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 13:24:25 +01:00
Sebastien Boeuf
35c0ea6c25 ch-remote: Add --snapshot option
Introduce the snapshot wrapper to ch-remote.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
fe2d884605 main: Support VM restore from the command line
Through the new CLI --restore option.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
8f300bed83 vmm: api: Add a /api/v1/vm.restore endpoint
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
92c73c3b78 vmm: Add a VmRestore command
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
39d4f817f0 vmm: http: Add a /api/v1/vm.snapshot endpoint
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
cf8f8ce93a vmm: api: Add a Snapshot command
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-02 13:24:25 +01:00
Sebastien Boeuf
452475c280 vmm: Add migration helpers
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 13:24:25 +01:00
Samuel Ortiz
1b1a2175ca vm-migration: Define the Snapshottable and Transportable traits
A Snapshottable component can snapshot itself and
provide a MigrationSnapshot payload as a result.

A MigrationSnapshot payload is a map of component IDs to a list of
migration sections (MigrationSection). As component can be made of
several Migratable sub-components (e.g. the DeviceManager and its
device objects), a migration snapshot can be made of multiple snapshot
itself.
A snapshot is a list of migration sections, each section being a
component state snapshot. Having multiple sections allows for easier and
backward compatible migration payload extensions.

Once created, a migratable component snapshot may be transported and this
is what the Transportable trait defines, through 2 methods: send and recv.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
Signed-off-by: Yi Sun <yi.y.sun@linux.intel.com>
2020-04-02 13:24:25 +01:00
Sebastien Boeuf
2d17f4384a vmm: seccomp: Add missing open() syscall
On some systems, the open() system call is used by Cloud-Hypervisor,
that's why it should be part of the seccomp filters whitelist.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-04-02 09:56:48 +02:00
dependabot-preview[bot]
bf135a29f7 build(deps): bump linux-loader from 2adddce to 61d95eb
Bumps [linux-loader](https://github.com/rust-vmm/linux-loader) from `2adddce` to `61d95eb`.
- [Release notes](https://github.com/rust-vmm/linux-loader/releases)
- [Commits](2adddce25b...61d95eb67b)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-02 06:35:44 +00:00
dependabot-preview[bot]
da4aaee778 build(deps): bump vmm-sys-util from 0.4.0 to 0.5.0
Bumps [vmm-sys-util](https://github.com/rust-vmm/vmm-sys-util) from 0.4.0 to 0.5.0.
- [Release notes](https://github.com/rust-vmm/vmm-sys-util/releases)
- [Changelog](https://github.com/rust-vmm/vmm-sys-util/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-vmm/vmm-sys-util/compare/v0.4.0...v0.5.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-04-01 12:02:19 +00:00
dependabot-preview[bot]
6a934c32ee build(deps): bump proc-macro-hack from 0.5.14 to 0.5.15
Bumps [proc-macro-hack](https://github.com/dtolnay/proc-macro-hack) from 0.5.14 to 0.5.15.
- [Release notes](https://github.com/dtolnay/proc-macro-hack/releases)
- [Commits](https://github.com/dtolnay/proc-macro-hack/compare/0.5.14...0.5.15)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-31 15:56:27 +00:00
dependabot-preview[bot]
3b891cd304 build(deps): bump micro_http from e89ed14 to 0d87a94
Bumps [micro_http](https://github.com/firecracker-microvm/micro-http) from `e89ed14` to `0d87a94`.
- [Release notes](https://github.com/firecracker-microvm/micro-http/releases)
- [Commits](e89ed14707...0d87a94c8e)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-31 07:31:12 +00:00
dependabot-preview[bot]
d5199ad91d build(deps): bump anyhow from 1.0.27 to 1.0.28
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.27 to 1.0.28.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.27...1.0.28)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-31 06:00:23 +00:00
dependabot-preview[bot]
6a0b4d7a7c build(deps): bump proc-macro2 from 1.0.9 to 1.0.10
Bumps [proc-macro2](https://github.com/alexcrichton/proc-macro2) from 1.0.9 to 1.0.10.
- [Release notes](https://github.com/alexcrichton/proc-macro2/releases)
- [Commits](https://github.com/alexcrichton/proc-macro2/compare/1.0.9...1.0.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-30 20:59:50 +00:00
dependabot-preview[bot]
31bbe0e509 build(deps): bump hermit-abi from 0.1.9 to 0.1.10
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.9 to 0.1.10.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/compare/hermit-abi-0.1.9...hermi-abi-0.1.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-30 06:59:35 +00:00
dependabot-preview[bot]
7f098168ac build(deps): bump hermit-abi from 0.1.8 to 0.1.9
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.8 to 0.1.9.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/compare/hermit-abi-0.1.8...hermit-abi-0.1.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-30 05:16:35 +00:00
dependabot-preview[bot]
00a1eced55 build(deps): bump thiserror from 1.0.13 to 1.0.14
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.13 to 1.0.14.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.13...1.0.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-29 19:25:57 +00:00
dependabot-preview[bot]
f24b74246d build(deps): bump serde_json from 1.0.48 to 1.0.50
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.48 to 1.0.50.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.48...v1.0.50)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-28 20:33:37 +00:00
Sebastien Boeuf
e4ea8b0bef vmm: Add missing syscalls to the seccomp filters
Both clock_gettime and gettimeofday syscalls where missing when running
Cloud-Hypervisor on a Linux host without vDSO enabled. On a system with
vDSO enabled, the syscalls performed by vDSO were not filtered, that's
why we didn't have to whitelist them.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-27 16:50:52 +00:00
Eryu Guan
33be24bd5a vhost-user-fs: return EINVAL if req is out of range in fs_slave_mmap/unmap/sync
Return libc::EINVAL instead of custom "Wrong offset" error, as mmap(2)
returns EINVAL when offset/len is invalid.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-27 11:27:56 +01:00
Eryu Guan
78b5cbc63a vhost-user-fs: validate fs_slave_map/unmap/sync request
In fs_slave_map/unmap/sync, we only made sure offset < cache_size, but
didn't validate (offset + len). We should ensure [offset, offset+len]
is within cache range as well.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-27 11:27:56 +01:00
Sebastien Boeuf
0c29c2ec49 ci: Extend VFIO test with memory hotplug
One more time, we're extending the VFIO integration test to verify that
a VFIO device passed through a VM is still usable after some new memory
has been hotplugged.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-27 09:35:39 +01:00
Sebastien Boeuf
9e18177654 vmm: Add memory hotplug support to VFIO PCI devices
Extend the update_memory() method from DeviceManager so that VFIO PCI
devices can update their DMA mappings to the physical IOMMU, after a
memory hotplug has been performed.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-27 09:35:39 +01:00
Sebastien Boeuf
cc67131ecc vmm: Retrieve new memory region when memory is extended
Whenever the memory is resized, it's important to retrieve the new
region to pass it down to the device manager, this way it can decide
what to do with it.

Also, there's no need to use a boolean as we can instead use an Option
to carry the information about the region. In case of virtio-mem, there
will be no region since the whole memory has been reserved up front by
the VMM at boot. This means only the ACPI hotplug will return a region
and is the only method that requires the memory to be updated from the
device manager.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-27 09:35:39 +01:00
Sebastien Boeuf
e4a034aef9 vfio: Add support for memory hotplug
Whenever the guest memory is extended, the IOMMU mappings related to
each VFIO device must be updated. This allows subsequent RAM accesses
to be authorized by the physical IOMMU for the newly added RAM region.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-27 09:35:39 +01:00
Samuel Ortiz
8fc7bf2953 vmm: Move to the latest linux-loader
Commit 2adddce2 reorganized the crate for a cleaner multi architecture
(x86_64 and aarch64) support.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-27 08:48:20 +01:00
Sebastien Boeuf
785812d976 vmm: Fallback to legacy boot if PVH is enabled along with initramfs
For now, the codebase does not support booting from initramfs with PVH
boot protocol, therefore we need to fallback to the legacy boot.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
5157ba10d1 resources: enable initramfs in kernel config
so that we can use the kernel compiled for the integration tests

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
3b470d4f4b tests: add support for initramfs
the integration test creates an initramfs image based on AlpineLinux mini root filesystem
with a simple /init script that just echoes a string to the console. The string
is passed via the kernel cmdline as an environment variable.

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
6cce7b9560 arch: load initramfs and populate zero page
* load the initramfs File into the guest memory, aligned to page size
* finally setup the initramfs address and its size into the boot params
  (in configure_64bit_boot)

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
1f9bc68c54 openapi: Add initramfs support
added InitramfsConfig property to the REST API spec

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
4db252b418 main, vmm: add --initramfs cli option
currently unused, the initramfs argument is added to the cli,
and stored in vmm::config:VmConfig as an Option(InitramfsConfig(PathBuf))

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Damjan Georgievski
0ce7de3ef5 arch: provide mechanism to get page size
This is a copy of the same code in vm-allocator, until a better place is
found for general use.

Signed-off-by: Damjan Georgievski <gdamjan@gmail.com>
2020-03-26 11:59:03 +01:00
Rob Bradford
4b110d5b73 tests: Add integration test for hotplugging network device
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
f3f4d07595 ch-remote: Add support for hotplugging network devices
Call the new HTTP API for hotplugging network devices using the same
syntax as coldplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
c73c31b66e docs: Update API documentation to include "vm.add-net"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
6244beb9d5 openapi: Add "vm.add-net" entry point
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
57c3fa4b1e vmm: Add "add-net" to the API
Add the HTTP and internal API entry points for adding a network device
at runtime.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
f664cddec9 vmm: Add support for adding network devices to the VM
The persistent memory will be hotplugged via DeviceManager and saved in
the config for later use.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
8f323e61d8 vmm: Add support to DeviceManager for hotplugging network devices
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
42a9896fe4 vmm: device_manager: Refactor make_virtio_net_devices
Split it into a method that creates a single device which is called by
the multiple device version so this can be used when dynamically adding
a device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Rob Bradford
9df601a1df bin, vmm: Centralise the net syntax
This will allow the syntax to be reused with cloud-hypervsor binary and
ch-remote.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 17:58:06 +01:00
Samuel Ortiz
41d7b3a387 vmm: memory_manager: Only send the GED notification for the ACPI method
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
15d9ec0149 openapit: Add hotplug_method to MemoryConfig
Add hotplug_method to MemoryConfig in cloud-hypervisor.yaml.

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
abbd69abee tests: Add integration test test_virtio_mem
Add integration test test_virtio_mem for virtio-mem.

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
4a7a2cff8c tests: Add test for hotplug_size and hotplug_method
Add test for hotplug_size and hotplug_method.

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
e63f98182a vmm: device: Add make_virtio_mem_devices
Add make_virtio_mem_devices to add virtio-mem to vmm.

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
e6b934a56a vmm: Add support for virtio-mem
This commit adds new option hotplug_method to memory config.
It can set the hotplug method to "acpi" or "virtio-mem".

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Hui Zhu
51d102c708 vm-virtio: Add virtio-mem device
The basic idea of virtio-mem is to provide a flexible, cross-architecture
memory hot plug and hot unplug solution that avoids many limitations
imposed by existing technologies, architectures, and interfaces. More
details can be found in https://lkml.org/lkml/2019/12/12/681.

This commit add virtio-mem device.

Signed-off-by: Hui Zhu <teawater@antfin.com>
2020-03-25 15:54:16 +01:00
Rob Bradford
8d05fb86e3 tests: Add integration test for hotplugging pmem device
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
0b0510108d ch-remote: Add support for hotplugging persistent memory
Call the new HTTP API for hotplugging persistent memory using the same
syntax as coldplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
44aef8f438 docs: Update API documentation to include "vm.add-pmem"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
75878dd90a openapi: Add "vm.add-pmem" entry point
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
f6f4c68fb4 vmm: Add "add-pmem" to the API
Add the HTTP and internal API entry points for adding persistent memory
at runtime.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
15de30f141 vmm: Add support for adding pmem devices to the VM
The persistent memory will be hotplugged via DeviceManager and saved in
the config for later use.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
f7def621dd vmm: Add support to DeviceManager for hotplugging pmem devices
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
8c3ea8cd76 vmm: device_manager: Refactor make_virtio_pmem_devices
Split it into a method that creates a single device which is called by
the multiple device version so this can be used when dynamically adding
a device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Rob Bradford
a7296bbb52 bin, vmm: Centralise the pmem syntax
This will allow the syntax to be reused with cloud-hypervisor binary and
ch-remote.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 13:18:17 +01:00
Eryu Guan
61e34331c2 virtio-fs: validate request len in fs_slave_io()
We made sure gpa is in cache range, but not the end addr of request,
which is (gpa + len). If the end addr of request is beyond dax cache
window, vmm would corrupt guest memory or crash.

Fix it by making sure end addr of request is within cache range as well.
And while we're at it, return EFAULT if the request is out of range, as
write(2)/read(2) returns EFAULT when buffer is outside accessible
address space.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-25 13:12:26 +01:00
Rob Bradford
4c9d15d44c vmm: Fix copy and paste error message
vm_remove_device was copied from vm_add_device but the error message
wasn't correctly updated.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
96d4f1e39e tests: Add integration test for hotplugging disk device
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
05ce2dc820 ch-remote: Add support for hotplugging disks
Call the new HTTP API for hotplugging disks using the same syntax as
disk coldplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
eec1a32d95 docs: Update API documentation to include "vm.add-disk"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
82cad99c0b openapi: Add "vm.add-disk" entry point
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
f2151b2734 vmm: Add "add-disk" to the API
Add the HTTP and internal API entry points for adding disks at runtime.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
164ec2b8e6 vmm: Add support for adding disks to the VM
The disk will be hotplugged via DeviceManager and saved in the config
for later use.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
b3082c1984 vmm: Add support to DeviceManager for hotplugging disks
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
2be703ca92 vmm: device_manager: Refactor make_virtio_block_devices
Split it into a method that creates a single device which is called by
the multiple device version so this can be used when dynamically adding
a device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
Rob Bradford
66da29d8dd bin, vmm: Centralise the disk syntax
This will allow the syntax to be reused with cloud-hypervsor binary and
ch-remote.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-25 09:35:53 +00:00
dependabot-preview[bot]
ede288789a build(deps): bump micro_http from e712d6a to e89ed14
Bumps [micro_http](https://github.com/firecracker-microvm/micro-http) from `e712d6a` to `e89ed14`.
- [Release notes](https://github.com/firecracker-microvm/micro-http/releases)
- [Commits](e712d6ae23...e89ed14707)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-25 06:43:09 +00:00
Sebastien Boeuf
c1e6d0022b ci: Add memory resizing use case to vhost-user tests
All vhost-user-blk, vhost-user-net and virtio-fs integration tests are
extended with memory resizing. The point is to validate that we can
hotplug some memory and keep these backends to work as expected.

Just a note that because memory resizing is not supported by mmio, we
limit these extensions to all non-mmio use cases.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
890582b5a2 ci: Factorize kernel command line
The same Clear Linux kernel command line was repeated again and again in
the code. That's why this commit takes care of factorizing it, which
simplifies the code but also simplify maintenance whenever we'd need to
update the block UUID.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
4de258477e ci: Fix mmio tests with direct kernel boot
The hypervisor-fw does not support virtio-blk through mmio transport
layer, therefore we can only run tests with mmio if these tests boot
directly to kernel.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
f2682463a4 ci: Factorize integration tests booting from vhost-user-blk
Remove duplicated code for all boot related tests relying on
vhost-user-blk.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
5a5b3cf23b ci: Factorize vhost-user-blk integration tests
All the non-boot related vhost-user-blk tests are factorized to remove
code duplication.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
dd8debf201 ci: Run vhost-user-blk tests for mmio builds
There's no reason mmio builds cannot support vhost-user-blk, therefore
there's no reason to skip these tests for mmio.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
0c9c72c583 ci: Unify vhost-user-blk integration tests
As a first step towards factorizing as many vhost-user-blk tests as
possible, this patch takes care of unifying their expected output.

It also makes a clear separation between the tests booting from
vhost-user-blk from the ones passing an extra volume.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
c95851f48f ci: Run vhost-user-net tests for mmio transport
No reason to skip vhost-user-net integration tests for the mmio
transport build.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
68293fc0e8 ci: Factorize vhost-user-net one step further
In order to limit code duplication, vhost-user-net integration tests are
further factorized, as they now include the self spawning test.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
d75e7456fc vm-virtio: vhost-user: Send memory update to the backend
In order to keep vhost-user backend to work across guest memory resizing
happening when memory is hot-plugged or hot-unplugged, both blk, net and
fs devices are implementing the notifier to let the backend know.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
7ff82af4b2 vm-virtio: vhost-user: Factorize SET_MEM_TABLE setup
By factorizing the setup of the memory table for vhost-user, we
anticipate the fact that vhost-user devices are going to reuse this
function when the guest memory will be updated.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
e54f8ec8a5 vmm: Update memory through DeviceManager
Whenever the VM memory is resized, DeviceManager needs to be notified
so that it can subsequently notify each virtio devices about it.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
Sebastien Boeuf
bc874a9b6f vm-virtio: Add update_memory() to VirtioDevice trait
The virtio devices backed by a vhost-user backend must send an update to
the associated backend with the new file descriptors corresponding to
the memory regions.

This patch allows such devices to be notified when such update needs to
happen.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 19:01:15 +00:00
dependabot-preview[bot]
93becca82a build(deps): bump backtrace from 0.3.45 to 0.3.46
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.45 to 0.3.46.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.45...0.3.46)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-24 16:49:27 +00:00
Sebastien Boeuf
feb8d7ae90 vmm: Separate seccomp filters between VMM and API threads
This separates the filters used between the VMM and API threads, so that
we can apply different rules for each thread.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Sebastien Boeuf
5120c275a2 main: Add seccomp support
This change introduces a new CLI option --seccomp. This allows the user
to enable/disable the seccomp filters when needed. Because the user now
has the possibility to disable the seccomp filters, and because the
Cloud-Hypervisor project wants to enforce the maximum security by
default, the seccomp filters are now applied by default.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Sebastien Boeuf
f1a23d712f vmm: api: Add seccomp to the HTTP API thread
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Sebastien Boeuf
db62cb3f4d vmm: Add seccomp filter to the VMM thread
This commit introduces the application of the seccomp filter to the VMM
thread. The filter is empty for now (SeccompLevel::None).

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Sebastien Boeuf
cb98d90097 vmm: Create new seccomp_filter module
Based on the seccomp crate, we create a new vmm module responsible for
creating a seccomp filter that will be applied to the VMM main thread.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Sebastien Boeuf
708f02dc26 vmm: Pull seccomp crate from Firecracker
The seccomp crate from Firecracker is nicely implemented, documented and
tested, which is a good reason for relying on it to create and apply
seccomp filters.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-24 14:59:57 +01:00
Eryu Guan
18fbd303ab vhost-user-fs: return correct result of fs_slave_io()
Virtio-fs daemon expects fs_slave_io() returns the number of bytes
read/written on success, but we always return 0 and make userspace think
nothing has been read/written.

Fix it by returning the actual bytes read/written. Note that This
depends on the corresponding fix in vhost crate.

Fixes: #949
Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-24 14:55:56 +01:00
Samuel Ortiz
bbc385c3f3 devices: ioapic: Remove unused MsiMessage structure
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-24 12:53:46 +00:00
Samuel Ortiz
2fc86ffea6 dev_cli: Always pull the latest container image
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-23 19:54:40 +01:00
Samuel Ortiz
4b462a54ee Dockerfile: Add cpio and bsdtar to the container image
To be able to build initrd images.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-23 19:54:40 +01:00
Rob Bradford
8acc15a63c build: Bump vm-memory and linux-loader dependencies
linux-loader depends on vm-memory so must be updated at the same time.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-23 14:27:41 +00:00
dependabot-preview[bot]
38ed560d3a build(deps): bump thiserror from 1.0.12 to 1.0.13
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.12 to 1.0.13.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.12...1.0.13)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-23 07:12:27 +00:00
dependabot-preview[bot]
9f67de4735 build(deps): bump proc-macro-hack from 0.5.12 to 0.5.14
Bumps [proc-macro-hack](https://github.com/dtolnay/proc-macro-hack) from 0.5.12 to 0.5.14.
- [Release notes](https://github.com/dtolnay/proc-macro-hack/releases)
- [Commits](https://github.com/dtolnay/proc-macro-hack/compare/0.5.12...0.5.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-22 18:40:56 +00:00
dependabot-preview[bot]
ebab8090ee build(deps): bump thiserror from 1.0.11 to 1.0.12
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.11 to 1.0.12.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.11...1.0.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-21 08:38:25 +00:00
dependabot-preview[bot]
c67e407620 build(deps): bump syn from 1.0.16 to 1.0.17
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.16 to 1.0.17.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.16...1.0.17)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-21 08:38:11 +00:00
Rob Bradford
bdcfe1efbd tests: Add "discard_writes" pmem test
Factorise test_virtio_pmem to test changes are not persisted if file is
readonly.

As virtio-mem is now supported in the upstream kernel we can switch to
using the firmware.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-20 14:46:34 +01:00
Rob Bradford
70986022d8 tests: Make the test_virtio_pmem test use a temporary file
Rather than using a raw OS disk image. This will be useful when the test
is extended to doing I/O on the image.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-20 14:46:34 +01:00
Rob Bradford
f7197e8415 vmm: Add a "discard_writes=" to --pmem
This opens the backing file read-only, makes the pages in the mmap()
read-only and also makes the KVM mapping read-only. The file is also
mapped with MAP_PRIVATE to make the changes local to this process only.

This is functional alternative to having support for making a
virtio-pmem device readonly. Unfortunately there is no concept of
readonly virtio-pmem (or any type of NVDIMM/PMEM) in the Linux kernel so
to be able to have a block device that is appears readonly in the guest
requires significant specification and kernel changes.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-20 14:46:34 +01:00
Rob Bradford
d11a67b0fe vmm: Use more generic MmapRegion constructor
Switch to MmapRegion::build() and fill in the fields appropriately.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-20 14:46:34 +01:00
Rob Bradford
7257e890ef vmm: Add "readonly" parameter MemoryManager::create_userspace_mapping
Use this boolean to turn on the KVM_MEM_READONLY flag to indicate that
this memory mapping should not be writable by the VM.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-20 14:46:34 +01:00
Samuel Ortiz
03cb26cc70 release: v0.6.0
Expand the release notes and bump Cargo.toml.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-20 12:26:27 +01:00
Samuel Ortiz
3e9a39ca13 github: Upload the ch-remote asset
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-20 12:26:27 +01:00
Qiu Wenbo
c503118d16 vmm: fix a corrupted stack caused by get_win_size
According to `asm-generic/termios.h`, the `struct winsize` should be:

struct winsize {
        unsigned short ws_row;
        unsigned short ws_col;
        unsigned short ws_xpixel;
        unsigned short ws_ypixel;
};

The ioctl of TIOCGWINSZ will trigger a segfault on aarch64.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2020-03-20 07:30:06 +01:00
Rob Bradford
0788600702 build: Remove "pvh_boot" feature flag
This feature is stable and there is no need for this to be behind a
flag. This will also reduce the time needed to run the integration test
as we will not be running them all again under the flag.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-19 13:05:44 +00:00
Rob Bradford
477bc17f18 bin: Share VFIO device syntax between cloud-hypervisor and ch-remote
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-18 23:38:55 +00:00
dependabot-preview[bot]
96be2dbeff build(deps): bump serde_derive from 1.0.104 to 1.0.105
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.104 to 1.0.105.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.104...v1.0.105)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-18 20:49:40 +00:00
dependabot-preview[bot]
5a335fc408 build(deps): bump serde from 1.0.104 to 1.0.105
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.104 to 1.0.105.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.104...v1.0.105)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-18 20:00:16 +00:00
Jose Carlos Venegas Munoz
a31ffef085 openapi: Add hotplug_size for memory hotplug
Add hotplug_size, needed to be defined when hotplug is used.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2020-03-18 19:06:07 +00:00
Rob Bradford
87990f9e67 vmm: Add virtio-pci device to B/D/F hash table
This table currently contains only all the VFIO devices and it should
really contain all the PCI devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-18 19:05:58 +00:00
Rob Bradford
fb185fa839 vmm: Always return PCI B/D/F from add_virtio_pci_device
Previously this was only returned if the device had an IOMMU mapping and
whether the device should be added to the virtio-iommu. This was already
captured earlier as part of creating the device so use that information
instead.

Always returning the B/D/F is helpful as it facilitates virtio PCI
device hotplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-18 19:05:58 +00:00
dependabot-preview[bot]
462082c52f build(deps): bump arc-swap from 0.4.4 to 0.4.5
Bumps [arc-swap](https://github.com/vorner/arc-swap) from 0.4.4 to 0.4.5.
- [Release notes](https://github.com/vorner/arc-swap/releases)
- [Changelog](https://github.com/vorner/arc-swap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/arc-swap/compare/v0.4.4...v0.4.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-18 19:00:24 +00:00
Sergio Lopez
c821e96e2a vhost_user_fs: Implement support for FUSE_LSEEK
Implement missing support for FUSE_LSEEK, which basically implies
calling to libc::lseek on the file handle. As this operation alters
the file offset, we take a write lock on the File's RwLock.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-18 18:15:28 +00:00
Cathy Zhang
5aa9abca5e docs: Add document for vhost-user-net test with OVS/DPDK
Add a document to illustrate how to test vhost-user-net function with
OpenVSwitch + DPDK as backend.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-03-18 16:43:09 +01:00
Sergio Lopez
6329219749 vm-virtio: queue: Use a SeqCst fence on get_used_event
On x86_64, a hint to the compiler is not enough, we need to issue a
MFENCE instruction. Replace the Acquire fence with a SeqCst one.

Without this, it's still possible to miss an used_event update,
leading to the omission of a notification, possibly stalling the
vring.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-18 13:36:17 +00:00
Samuel Ortiz
63eeed29cc vm: Comment on the VM config update from memory hotplug
I spent a few minutes trying to understand why we were unconditionally
updating the VM config memory size, even if the guest memory resizing
did not happen.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-18 12:48:40 +01:00
dependabot-preview[bot]
0895bcb5dd build(deps): bump proc-macro-hack from 0.5.11 to 0.5.12
Bumps [proc-macro-hack](https://github.com/dtolnay/proc-macro-hack) from 0.5.11 to 0.5.12.
- [Release notes](https://github.com/dtolnay/proc-macro-hack/releases)
- [Commits](https://github.com/dtolnay/proc-macro-hack/compare/0.5.11...0.5.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-18 08:21:54 +00:00
dependabot-preview[bot]
0541f5aa54 build(deps): bump proc-macro-nested from 0.1.3 to 0.1.4
Bumps [proc-macro-nested](https://github.com/dtolnay/proc-macro-hack) from 0.1.3 to 0.1.4.
- [Release notes](https://github.com/dtolnay/proc-macro-hack/releases)
- [Commits](https://github.com/dtolnay/proc-macro-hack/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-17 21:36:51 +00:00
dependabot-preview[bot]
51f51ea17d build(deps): bump libc from 0.2.67 to 0.2.68
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.67 to 0.2.68.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.67...0.2.68)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-17 21:36:38 +00:00
Samuel Ortiz
9cf67d133f arch: x86: Always set the bootloader type
We set it to 0xff, which is for unregistered loaders.
The kernel checks that the bootloader ID is set when e.g. loading
ramdisks, so not setting it when we get a bootparams header from the
loader will prevent the kernel from loading ramdisks.

Fixes: #918

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-17 19:11:38 +01:00
Samuel Ortiz
ad354700c9 arch: x86: Extract common bootparams settings
We're going to add more common settings, so let's avoid duplication
between the 2 branches.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-17 19:11:38 +01:00
Rob Bradford
28a5f9dc19 vmm: acpi: Remove unused IORT related structures
The IORT table for virtio-iommu use was removed and replaced with a
purely virtio based solution. Although the table construction was
removed these structures were left behind.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-17 12:46:26 +00:00
Liu Bo
5c1207c198 vhost-user-fs: handle FS_IO request
Virtiofs's dax window can be used as read/write's source (e.g. mmap a file
on virtiofs), but the dax window area is not shared with vhost-user
backend, i.e. virtiofs daemon.

To make those IO work, addresses of this kind of IO source are routed to
VMM via FS_IO requests to perform a read/write from an fd directly to the
given GPA.

This adds the support of FS_IO request to clh's vhost-user-fs master part.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-03-17 08:23:38 +01:00
dependabot-preview[bot]
f61f78eac6 build(deps): bump anyhow from 1.0.26 to 1.0.27
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.26 to 1.0.27.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.26...1.0.27)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-15 09:03:20 +00:00
Alejandro Jimenez
efb2447801 pvh: Add integration test to validate PVH boot
Add an integration test that builds cloud-hypervisor with
the pvh_boot feature and boots a kernel built with CONFIG_PVH.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
da084fade7 pvh: Add unit tests for initial sregs and control registers
Validate correct GDT entries, initial segment configuration, and control
register bits that are required by PVH boot protocol.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
64941bfcad pvh: Add unit tests for start_info and memory map structures
Expand the unit tests to cover the configure_system() code when
using the PVH boot protocol. Verify the method for adding memory
map table entries in the format specified by PVH boot protocol.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
9e247c4e06 pvh: Introduce "pvh_boot" feature
Use a new feature called "pvh_boot" to enable using the PVH boot
protocol if the guest kernel supports it. The feature can be enabled
by building with:

cargo build [--release] --features "pvh_boot"

Once performance has been evaluated, this can be made part of the
default set of features so that any guest that supports it boots
using PVH as the preferred option as is the case in QEMU.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
a22bc3559f pvh: Write start_info structure to guest memory
Fill the hvm_start_info and related memory map structures as
specified in the PVH boot protocol. Write the data structures
to guest memory at the GPA that will be stored in %rbx when
the guest starts.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
840a9a97ff pvh: Initialize vCPU regs/sregs for PVH boot
Set the initial values of the KVM vCPU registers as specified in
the PVH boot ABI:

https://xenbits.xen.org/docs/unstable/misc/pvh.html

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
24f0e42e6a pvh: Introduce EntryPoint struct
In order to properly initialize the kvm regs/sregs structs for
the guest, the load_kernel() return type must specify which
boot protocol to use with the entry point address it returns.

Make load_kernel() return an EntryPoint struct containing the
required information. This structure will later be used
in the vCPU configuration methods to setup the appropriate
initial conditions for the guest.

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Alejandro Jimenez
98b956886e pvh: Add definitions for PVH boot protocol support
Create supporting definitions to use the hvm start info and memory
map table entry struct definitions from the linux-loader crate in
order to enable PVH boot protocol support

Signed-off-by: Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
2020-03-13 18:29:44 +01:00
Rob Bradford
6e6ef8348b build: Fix log dependency
@dependabot bumped the dependency to 0.4.10 but this is no longer a
valid version so downgrade appropriately.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-13 17:27:38 +01:00
dependabot-preview[bot]
291f1cef29 build(deps): bump linux-loader from 0c754f3 to 0ce5bfa
Bumps [linux-loader](https://github.com/rust-vmm/linux-loader) from `0c754f3` to `0ce5bfa`.
- [Release notes](https://github.com/rust-vmm/linux-loader/releases)
- [Commits](0c754f380a...0ce5bfa70d)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-13 16:26:50 +00:00
Sergio Lopez
07cc73bddc vhost_user_fs: add a flag to disable extended attributes
Extended attributes (xattr) support has a huge impact on write
performance. The reason for this is that, if enabled, FUSE sends a
setxattr request after each write operation, and due to the inode
locking inside the kernel during said request, the ability to execute
the operations in parallel becomes heavily limited.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-13 15:20:34 +00:00
Sergio Lopez
710520e9a1 vhost_user_fs: Process requests in parallel with a thread pool
This change enables vhost_user_fs to process multiple requests in
parallel by scheduling them into a ThreadPool (from the Futures
crate).

Parallelism on a single file is limited by the nature of the operation
executed on it. A recent commit replaced the Mutex that protects the
File within HandleData with a RwLock, to allow some operations (at
this moment, only "read" and "write") to proceed in parallel by
acquiring a read lock.

A more complex approach was also implemented [1], involving
instrumentation through vhost_user_backend to be able to serialize
completions, reducing the pressure on the vring RwLock. This strategy
improved the performance on some corner cases, while making it worse
on other, more common ones. This fact, in addition to it requiring
wider changes through the source code, prompted me to drop it in favor
of this one.

[1] https://github.com/slp/cloud-hypervisor/tree/vuf_async

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-13 15:20:34 +00:00
Sergio Lopez
90309b5106 vm-virtio: queue: Add methods to switch a descriptor context
"DescriptorChain"s are tied to the lifetime of the referenced
GuestMemoryMmap object (for good reasons), but sometimes (i.e., when
processing descriptors from different contexts) we may need to switch
them to point a different GuestMemoryMmap.

Here we introduce the structure DescriptorHead, which holds the data
needed to rebuild a DescriptorChain, the method "get_head" which
returns the DescriptorHead for a DescriptorChain, and the method
"new_from_head", which allows to create a new DescriptorChain with a
DescriptorHead and a new reference to a GuestMemoryMmap.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-13 15:20:34 +00:00
Sergio Lopez
2294c2d2c9 Add .rustfmt.toml to the project
For rustfmt to accept modern syntax like "async move", a .rustfmt.toml
with "edition = 2018" needs to be created.

https://github.com/rust-lang/rustfmt/issues/3149

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-13 15:20:34 +00:00
Sergio Lopez
48c4885b47 vhost_user_fs: replace HandleData's File Mutex with RwLock
Replace HandleData's File Mutex with a RwLock to have more granularity
on the lock. This allows operations on the same File that are safe to
be run in parallel (at this moment, read and write), to acquire a read
lock to avoid waiting on each other.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-13 15:20:34 +00:00
Samuel Ortiz
134e64c612 arch, qcow: Fix 1.42.0 clippy warnings
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-13 12:26:15 +00:00
Samuel Ortiz
6ea85ca86c resources: Dockerfile: Update Rust toolchain
To the latest stable version: 1.42.0

Fixes: #909

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-13 12:26:15 +00:00
Rob Bradford
4579afa091 vmm: For --disk error if socket and path is specified
This is an error as the path should be specfied by the unmanaged
backend.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-13 11:41:52 +00:00
Rob Bradford
7e599b4450 vmm: Make disk path optional
When using "--disk" with a vhost socket and not using self spawning then
it is not necessary or helpful to specify the path.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-13 11:41:52 +00:00
Samuel Ortiz
477d924528 github: Build from a rust toolchain matrix
So that we can run our builds against several toolchains (beta, stable,
nightly).

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-13 11:41:34 +00:00
Rob Bradford
4f2469e054 main: Remove "--vhost-user-net"
This option was superseded by using "--net" with "vhost_user=true". This
option wasn't being parsed any more but was left over.

Fixes: #806

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-13 11:00:43 +00:00
Sebastien Boeuf
8d785bbd5f pci: Fix the PciBus using HashMap instead of Vec
By using a Vec to hold the list of devices on the PciBus, there's a
problem when we use unplug. Indeed, the vector of devices gets reduced
and if the unplugged device was not the last one from the list, every
other device after this one is shifted on the bus.

To solve this problem, a HashMap is used. This allows to keep track of
the exact place where each device stands on the bus.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-13 10:54:34 +01:00
dependabot-preview[bot]
04f2ccd16d build(deps): bump ryu from 1.0.2 to 1.0.3
Bumps [ryu](https://github.com/dtolnay/ryu) from 1.0.2 to 1.0.3.
- [Release notes](https://github.com/dtolnay/ryu/releases)
- [Commits](https://github.com/dtolnay/ryu/compare/1.0.2...1.0.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-13 08:44:41 +00:00
dependabot-preview[bot]
02265bb589 build(deps): bump regex-syntax from 0.6.16 to 0.6.17
Bumps [regex-syntax](https://github.com/rust-lang/regex) from 0.6.16 to 0.6.17.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-13 08:14:13 +00:00
Jose Carlos Venegas Munoz
40b38a4222 openapi: Make desired_ram int64 format
The option desired_ram is in byte, make larger the amount of memory to
add.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2020-03-12 23:17:56 +01:00
Rob Bradford
ca3b39c0be bin: Fix wrapping in help strings
Some of the help strings had extra newlines in them or otherwise strange
wrapping. The strings were rewrapped with the nightly version of rustfmt
that supports string formatting.

Fixes: #899

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 18:03:18 +00:00
Rob Bradford
ee1ba56cfe build: Use "wrap_help" feature for clap
This prevents the output being wrapped at 120 characters and giving
strange results.

Fixes: #899

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 18:03:18 +00:00
Sergio Lopez
3957d1ee27 vhost_user_backend: call get_used_event from needs_notification
This change, combined with the compiler hint to inline get_used_event,
shortens the window between the memory read and the actual check by
calling get_used_event from needs_notification.

Without it, when putting enough pressure on the vring, it's possible
that a notification is wrongly omitted, causing the queue to stall.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-12 14:34:21 +00:00
Sergio Lopez
536323d9fb vm-virtio: queue: hint that get_used_event should be inlined
get_used_event is used from vhost_user_backend:needs_notification to
check whether an interrupt must be sent to the guest to notify there
are new items in the queue. Shorten the update window by asking the
the compiler to inline this method, so a write won't slip between the
read of the memory contents and the actual check.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-12 14:34:21 +00:00
Sergio Lopez
401e1d2489 vm-virtio: queue: fix a barrier comment at update_avail_event
The barrier had a comment coming from other context. Adjust it to be
relevant to its own context.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-12 14:34:21 +00:00
Sergio Lopez
e0bdfe826e vm-virtio: queue: add a missing memory barrier in get_used_event
Add a missing memory barrier in get_used_event to make sure we see the
last value written by the guest.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-03-12 14:34:21 +00:00
Sebastien Boeuf
df2570a472 resources: Simplify kernel config filename
Since we only keep one single version of the kernel config file in our
repository, there is no reason to keep the filename complex.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-12 14:07:11 +01:00
Sebastien Boeuf
9ab648b8f7 resources: Enable VIRTIO_MEM support
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-12 14:07:11 +01:00
Sebastien Boeuf
03398532dc ci: Bump to kernel 5.6-rc4
The kernel version is updated from 5.5-rc1 to 5.6-rc4, including the
updated kernel config file.

The kernel branch contains virtio-fs, virtio-iommu and virtio-mem
patches that are not upstream yet. It also contains one fix for
virtio-vsock which will be merged upstream in the next release.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-12 14:07:11 +01:00
Rob Bradford
abccf766ce tests: Use ch-remote to add/remove devices in test_vfio
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 12:56:10 +01:00
Rob Bradford
5c3ce9dd00 tests: Extend ch-remote helper to support optional single argument
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 12:56:10 +01:00
Rob Bradford
9a7d9c9465 ch-remote: Support removing VFIO devices
Add a "remove-device" command that allows removing VFIO devices from the
VM after boot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 12:56:10 +01:00
Rob Bradford
0d53ba4395 ch-remote: Support adding VFIO devices
Add an "add-device" command that allows adding VFIO devices to the VM
after boot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 12:56:10 +01:00
Rob Bradford
babefbd9bf main: Remove spurious second help line for "--device"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-12 12:56:10 +01:00
Samuel Ortiz
63c5d09537 github: Trigger the build job on PRs
And not on pushes only.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-12 11:27:43 +01:00
Samuel Ortiz
8cbb6d0faf github: Replace Travis CI with github actions
We define 1 workflow with 2 jobs: One for the regular build and another
one for creating a release and uploading the corresponding assets.
They both run conditionally, depending on the gihtub event that triggered
the action.

Fixes: #825

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-12 09:18:01 +01:00
Sebastien Boeuf
efba48dddb vmm: Don't put a VFIO device behind the vIOMMU by default
With some of the factorization that happened to be able to support VFIO
hotplug, one mistake was made. In case a vIOMMU is created through a
virtio-iommu device, and no matter the "iommu" option value from the
VFIO device parameter, the VFIO device was always placed behind the
virtual IOMMU.

This commit fixes this wrong behavior by making sure the device
configuration is taken into account to decide if it should be attached
or not to the virtual IOMMU.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 19:50:31 +01:00
Sebastien Boeuf
34412c9b41 vmm: Add id option to VFIO hotplug
Add a new id option to the VFIO hotplug command so that it matches the
VFIO coldplug semantic.

This is done by refactoring the existing code for VFIO hotplug, where
VmAddDeviceData structure is replaced by DeviceConfig. This structure is
the one used whenever a VFIO device is coldplugged, which is why it
makes sense to reuse it for the hotplug codepath.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 19:50:31 +01:00
Samuel Ortiz
18dc916380 vmm: Switch to the micro-http package
It's been extracted from the Firecracker code base.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-03-11 17:38:01 +01:00
Sebastien Boeuf
9023444ad3 vmm: Add id field to --device through CLI
Add the ability to specify the "id" associated with a device, by adding
an extra option to the parameter --device.

This new option is not mandatory, and by default, the VMM will take care
of finding a unique identifier.

If the identifier provided by the user through this new option is not
unique, an error will be thrown and the VM won't be started.

Fixes #881

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:57 +00:00
Sebastien Boeuf
f4a956a60a vmm: Remove 32 bits MMIO range from correct address space
The 32 bits MMIO address space is handled separately from the 64 bits
one. For this reason, we need to invoke the appropriate freeing function
to remove a range from this address space.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Sebastien Boeuf
432eb5b70a vmm: Free PCI BARs when unplugging PCI device
Now that PciDevice trait has a dedicated function to remove the bars,
the DeviceManager can invoke this function whenever a PCI device is
unplugged from the VM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Sebastien Boeuf
f0dff8b58c vfio: pci: Remove KVM user memory region when cleaning up
Whenever a VfioPciDevice is dropped, the regions previously mapped are
being unmapped. But there's also a need for removing the region from a
KVM perspective.

This commit extends the existing unmap_mmio_regions() function to take
care of removing the KVM region at the same time the regions are being
unmapped.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Sebastien Boeuf
34d1f435f4 vfio: pci: Implement free_bars() from the PciDevice trait
In order to provide the tools for a complete cleanup whenever a VFIO PCI
device is removed from the VM, the VfioPciDevice implements free_bars()
method from PciDevice trait. This will take care of removing the IO and
MMIO ranges previously reserved through the vm-allocator.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Sebastien Boeuf
b8e1cf2d4e vm-allocator: Add new function to free 32 bits MMIO address space
The allocator already had functions to allocate and free both IO and 64
bits MMIO address spaces, but it only had an allocating function for 32
bits MMIO address space.

With this new function, it will be now possible to remove cleanly some
ranges from the 32 bits MMIO address space.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Sebastien Boeuf
f3dc245c4f pci: Extend PciDevice trait with new free_bars() method
The point of this new method is to let the caller decide when the
implementation of the PciDevice should free the BARs previously
allocated through the other method allocate_bars().

This provides a way to perform proper cleanup for any PCI device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-11 13:10:30 +00:00
Rob Bradford
911a2d61d7 tests: Use ch-remote to resize the VM
Remove manually constructed API request in the integration tests.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-11 08:22:09 +01:00
Rob Bradford
21160f7490 ch-remote: Add "resize" command
This command lets you change the number of vCPUs and RAM that the VM
has.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-11 08:22:09 +01:00
Rob Bradford
bb2d04b39d ch-remote: Add support for sending a request body
Support sending a request body this will usually be JSON encoded data
representing the details of the request.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-11 08:22:09 +01:00
Rob Bradford
bde4f735ab ch-remote: Refactor HTTP response handling
Extract HTTP response handling into its own function.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-11 08:22:09 +01:00
dependabot-preview[bot]
6ed23bb3ab build(deps): bump micro_http from 9bbde4f to 6b3e5f0
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `9bbde4f` to `6b3e5f0`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](9bbde4fb6a...6b3e5f0a18)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-11 07:15:40 +00:00
dependabot-preview[bot]
5edd812792 build(deps): bump backtrace-sys from 0.1.33 to 0.1.34
Bumps [backtrace-sys](https://github.com/alexcrichton/backtrace-rs) from 0.1.33 to 0.1.34.
- [Release notes](https://github.com/alexcrichton/backtrace-rs/releases)
- [Commits](https://github.com/alexcrichton/backtrace-rs/compare/backtrace-sys-0.1.33...backtrace-sys-0.1.34)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-11 07:15:28 +00:00
Sebastien Boeuf
f7277140bb ci: Add integration test for VFIO hot-unplug
Extend the existing test_vfio by unplugging the previously hotplugged
device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
b50cbe5064 pci: Give PCI device ID back when removing a device
Upon removal of a PCI device, make sure we don't hold onto the device ID
as it could be reused for another device later.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
df71aaee3f pci: Make the device ID allocation smarter
In order to handle the case where devices are very often plugged and
unplugged from a VM, we need to handle the PCI device ID allocation
better.

Any PCI device could be removed, which means we cannot simply rely on
the vector size to give the next available PCI device ID.

That's why this patch stores in memory the information about the 32
slots availability. Based on this information, whenever a new slot is
needed, the code can correctly provide an available ID, or simply return
an error because all slots are taken.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
e514b124ed vmm: Update VmConfig when removing VFIO device
This commit ensures that when a VFIO device is hot-unplugged from the
VM, it is also removed from the VmConfig. This prevents a potential
reboot from creating the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
81173bf4ab vmm: Add id field to DeviceConfig structure
Add a new field to the DeviceConfig, allowing the VMM to allocate a name
to the VFIO devices.

By identifying a VFIO device with a unique name, we can make sure a user
can properly unplug it at any time.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
6cbdb9aa47 vmm: api: Introduce new "remove-device" HTTP endpoint
This commit introduces the new command "remove-device" that will let a
user hot-unplug a VFIO PCI device from an already running VM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
991f3bb5da vmm: Remove VFIO device from everywhere it is referenced
This commit implements the eject function so that a VFIO device will be
removed from any bus it might sit on, and from any list it might be
stored in.

The idea is to reach a point where there is no reference of the device
anywhere in the code, so that the Drop implementation will be invoked
and so that the device will be fully removed from the VMM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
6adebbc6a0 vmm: Detect when guest notifies about ejecting PCI device
When the guest OS is done removing a PCI device, it will invoke the _EJ0
method from ACPI, associated with the device. This will trigger a port
IO write to a region known by the VMM. Upon this writing, the VMM will
trap the VM exit and retrieve the written value.

Based on the value, the VMM will invoke its eject_device() method to
finalize the removal of the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
0e21c32c0b devices: Add new method to remove all occurrences of a BusDevice
The same BusDevice can be inserted multiple times on the same bus at
different ranges. This is the case for a PCI device with multiple memory
BARs for example, as each BAR will be inserted at a specific MMIO range.

This new method allows to find and remove every occurence of the same
device so that we can make sure it is fully removed from the bus.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
f8e2008e0e pci: Add a function to remove a PciDevice from the bus
Simple function relying on the retain() method from std::Vec, allowing
to remove every occurence of the same device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
08604ac6a8 vmm: Store PCI devices as Any devices from DeviceManager
As we try to keep track of every PCI device related to the VM, we don't
want to have separate lists depending on the concrete type associated
with the PciDevice trait. Also, we want to be able to cast the actual
type into any trait or concrete type.

The most efficient way to solve all these issues is to store every
device as an Arc<dyn Any + Send + Sync>. This gives the ability to
downcast into the appropriate concrete type, and then to cast back into
any trait that we might need.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
Sebastien Boeuf
0f99d3f7cc vmm: Store VFIO device's name and its PCI b/d/f
Add a new list storing the device names across the entire codebase. VFIO
devices are added to the list whenever a new one is created. By default,
each VFIO device is given a name "vfioX" where X is the first available
integer.

Along with this new list of names, another list is created, grouping PCI
device's name with its associated b/d/f. This will be useful to keep
track of the created devices so that we can implement unplug
functionality.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-10 17:05:06 +00:00
dependabot-preview[bot]
13a61c4784 build(deps): bump rand_chacha from 0.2.1 to 0.2.2
Bumps [rand_chacha](https://github.com/rust-random/rand) from 0.2.1 to 0.2.2.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/rand_chacha-0.2.1...rand_chacha-0.2.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-10 11:20:29 +00:00
dependabot-preview[bot]
fcd605a227 build(deps): bump micro_http from 6d416af to 9bbde4f
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `6d416af` to `9bbde4f`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](6d416afe10...9bbde4fb6a)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-10 07:12:00 +00:00
Rob Bradford
30b69549e1 vm-virtio: Consume pause events to prevent infinite epoll_wait calls
When a virtio device is paused an event is written to the appropriate
"pause" EventFd for the device. This will be noticed by the the device's
epoll_wait(), an atomic bool checked an if true then the thread is
parked(). When resuming the bool is reset and the thread is unpark()ed.
However the event triggering the pause is still in the EventFd so the
epoll_wait() will continue to return but because the boolean is not set
the thread will not be park()ed but instead we will busy loop around an
event that is not being consumed.

The solution is to drain the "pause" EventFd when the event is first
received and thus the epoll_wait() will only return for the pause event
once. This resolves the infinite epoll_wait() wake-ups.

Fixes: #869

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-09 19:01:38 +01:00
Rob Bradford
16fd506bb8 tests: Use new ch-remote for pause/resume integration test
Replace the use of a manual curl command with the new ch-remote tool.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-09 15:03:01 +00:00
Rob Bradford
ba8cd4d55a bin: Introduce "ch-remote" for controlling VMM
This commit introduces a basic implementation of a remote control of a
running VMM implementing a subset of the API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-09 15:03:01 +00:00
dependabot-preview[bot]
06cd31cb2e build(deps): bump micro_http from 02def92 to 6d416af
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `02def92` to `6d416af`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](02def92b33...6d416afe10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-09 11:03:07 +00:00
dependabot-preview[bot]
7e941c9ecd build(deps): bump linux-loader from 8cb7c66 to 0c754f3
Bumps [linux-loader](https://github.com/rust-vmm/linux-loader) from `8cb7c66` to `0c754f3`.
- [Release notes](https://github.com/rust-vmm/linux-loader/releases)
- [Commits](8cb7c6621b...0c754f380a)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-09 07:52:31 +00:00
Jose Carlos Venegas Munoz
df794993f8 net: Do not check multiqueue for new interface
If tun_flags file does not exist, check should not be fatal.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2020-03-05 19:21:06 +00:00
dependabot-preview[bot]
7d75b1f938 build(deps): bump quote from 1.0.2 to 1.0.3
Bumps [quote](https://github.com/dtolnay/quote) from 1.0.2 to 1.0.3.
- [Release notes](https://github.com/dtolnay/quote/releases)
- [Commits](https://github.com/dtolnay/quote/compare/1.0.2...1.0.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-05 19:05:49 +00:00
dependabot-preview[bot]
841bf89639 build(deps): bump failure from 0.1.6 to 0.1.7
Bumps [failure](https://github.com/rust-lang-nursery/failure) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/rust-lang-nursery/failure/releases)
- [Changelog](https://github.com/rust-lang-nursery/failure/blob/master/RELEASES.md)
- [Commits](https://github.com/rust-lang-nursery/failure/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-05 18:30:35 +00:00
dependabot-preview[bot]
86acdb9a12 build(deps): bump failure_derive from 0.1.6 to 0.1.7
Bumps [failure_derive](https://github.com/rust-lang-nursery/failure) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/rust-lang-nursery/failure/releases)
- [Changelog](https://github.com/rust-lang-nursery/failure/blob/master/RELEASES.md)
- [Commits](https://github.com/rust-lang-nursery/failure/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-05 16:52:13 +00:00
Sebastien Boeuf
4b328631b9 docs: Update api.md for VFIO hotplug
Adding the missing entry for "add-device" in the API documentation.

Fixes #863

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-05 16:41:26 +00:00
Rob Bradford
e518098688 scripts: Make integration tests fail if some important commands fail
As it's not possible to use "set -e" explicitly mark the important
commands with "|| exit 1"

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-05 16:37:52 +01:00
Cathy Zhang
be6f91d0d1 tests: Refactoring vhost_user_net test cases
Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-03-05 15:09:20 +00:00
Cathy Zhang
6341736286 vhost_user_net: Provide tap option for vhost_user_net backend
Provide vhost_user_net backend with the tap option, it allows to
use the existing tap interface.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-03-05 15:09:20 +00:00
Rob Bradford
e0419e988b build: Don't cancel older master builds
If a new build request for master comes in don't cancel the older
builds. Cancelling older builds is very useful for PRs that are being
updated but less so for a build of the master branch that has been
triggered via a merge or a periodic build.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-05 12:08:33 +01:00
Rob Bradford
f0a3e7c4a1 build: Bump linux-loader and vm-memory dependencies
linux-loader now uses the released vm-memory so we must move to that
version at the same time.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-05 11:01:30 +01:00
Jose Carlos Venegas Munoz
6539d4a873 vfio: handle case for missing iommu_group
For cases where IOMMU is not supported, iommu_group will be no present.

This could happened because IOMMU is off at kernel level, bios level or
is not supported at all.

Instead of fail with a generic error handle it as different use case:

Before:
ReadLink(Os { code: 2, kind: NotFound, message: "No such file or directory"})

After:
VfioNoIommuGroup("/sys/bus/pci/devices/0000:03:00.0/iommu_group")

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2020-03-05 09:49:32 +00:00
dependabot-preview[bot]
cfbebd8852 build(deps): bump micro_http from 88011bd to 02def92
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `88011bd` to `02def92`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](88011bd64f...02def92b33)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-05 07:38:35 +00:00
Rob Bradford
42148063ec tests: Remove further use of sudo subshells
Replace sudo invocations of bash creating a subshell with simpler
solutions by running the program directly on the input or using tee.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 20:54:46 +01:00
Rob Bradford
2baf5ab80d tests: Simplfy the shm region check
There is no need to spawn a subshell in this case as grep can open the
file directly.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 20:54:46 +01:00
Rob Bradford
97affbebfe tests: Re-enable the virtio-fs tests and make them work with virtio-mmio
As part of bringing the tests up with virtio-mmio the virtio-fs were
wrongly disabled. Re-enable them and remove the cache size check as the
cache does not appear in /proc/iomem on virtio-mmio.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 20:54:46 +01:00
Rob Bradford
7b1d5c1ad9 tests: Remove entropy check from vhost-user-block test
When booting from vhost-user-block the entropy is sometimes lower
triggering a flaky test. We have already use other, more reliable
methods for checking that the VM has booted.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 20:54:46 +01:00
Rob Bradford
a4cca5f60a tests: sha1sums --check can take a list of hashes
There is no need to cat the file in as input and instead the the program
will load from disk.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 20:54:46 +01:00
dependabot-preview[bot]
689415e5ff build(deps): bump libssh2-sys from 0.2.15 to 0.2.16
Bumps [libssh2-sys](https://github.com/alexcrichton/ssh2-rs) from 0.2.15 to 0.2.16.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/libssh2-sys-0.2.15...libssh2-sys-0.2.16)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-04 18:42:47 +00:00
Sebastien Boeuf
09829c44b2 vmm: Remove IO bus strong reference from Vm
The Vm structure was used to store a strong reference to the IO bus.
This is not needed anymore since the AddressManager is logically the
one holding this strong reference. This has been made possible by the
introduction of Weak references on the Bus structure itself.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
2dbb376175 vmm: Remove all Weak references from DeviceManager
Now that the BusDevice devices are stored as Weak references by the
IO and MMIO buses, there's no need to use Weak references from the
DeviceManager anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
9e915a0284 vmm: Remove all Weak references from CpuManager
Now that the BusDevice devices are stored as Weak references by the
IO and MMIO buses, there's no need to use Weak references from the
CpuManager anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
49268bff3b pci: Remove all Weak references from PciBus
Now that the BusDevice devices are stored as Weak references by the IO
and MMIO buses, there's no need to use Weak references from the PciBus
anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
ca426cfdf4 devices: Make Bus hold a list of Weak BusDevice references
By storing a list of Weak references to BusDevice devices, the Bus
structure prevents potential cyclic dependencies from happening on
strong references.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
7773812f58 vmm: Store the list of BusDevice devices from DeviceManager
The point is to make sure the DeviceManager holds a strong reference of
each BusDevice inserted on the IO and MMIO buses. This will allow these
buses to hold Weak references onto the BusDevice devices.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
d0820cc026 vmm: Make add_vfio_device mutable
The method add_vfio_device() from the DeviceManager needs to be mutable
if we want later to be able to update some internal fields from the
DeviceManager from this same function.

This commit simply takes care of making the necessary changes to change
this function as mutable.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
Sebastien Boeuf
948f808da6 vm: Rename DeviceManager field in Vm structure
It's more logical to name the field referring to the DeviceManager as
"device_manager" instead of "devices".

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 18:46:44 +01:00
dependabot-preview[bot]
aa638ead42 build(deps): bump backtrace from 0.3.44 to 0.3.45
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.44 to 0.3.45.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.44...0.3.45)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-04 15:33:46 +00:00
Sebastien Boeuf
1152b1a147 ci: Add VFIO hotplug integration test
This commit extends the existing test_vfio by hotplugging an extra
virtio-net device to the L2 VM. The test for validating the hotplug
succeeded is the same as the one to verify the non-hotplugged devices.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
d47f733e51 vmm: Break the cyclic dependency between DeviceManager and IO bus
By inserting the DeviceManager on the IO bus, we introduced some cyclic
dependency:

  DeviceManager ---> AddressManager ---> Bus ---> BusDevice
        ^                                             |
        |                                             |
        +---------------------------------------------+

This cycle needs to be broken by inserting a Weak reference instead of
an Arc (considered as a strong reference).

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
c1af13efeb vmm: Update VmConfig when adding new device
Ensures the configuration is updated after a new device has been
hotplugged. In the event of a reboot, this means the new VM will be
started with the new device that had been previously hotplugged.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
a86f4369a7 vmm: Add VFIO PCI device hotplug support
This commit finalizes the VFIO PCI hotplug support, based on all the
previous commits preparing for it.

One thing to notice, this does not support vIOMMU yet. This means we can
hotplug VFIO PCI devices, but we cannot attach them to an existing or a
new virtio-iommu device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
320fea0eaf vmm: Factorize VFIO PCI device creation
This factorization is very important as it will allow both the standard
codepath and the VFIO PCI hotplug codepath to rely on the same function
to perform the addition of a new VFIO PCI device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
00716f90a0 vmm: Store virtio-iommu device from DeviceManager
Helps with future refactoring of VFIO device creation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
5902dfa403 vmm: Store VFIO KVM device from DeviceManager
Helps with future refactoring of VFIO device creation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
d9c1b4396e vmm: Store MSI InterruptManager from DeviceManager
Helps with future refactoring of VFIO device creation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
02adc4061a vmm: Store PciBus from DeviceManager
Helps with future refactoring of VFIO device creation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
3f396d87ef resources: Enable ACPI PCI hotplug in the kernel config
The PCI hotplug through ACPI was not enabled by default.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
d0218e94a3 vmm: Trigger hotplug notification to the guest
Whenever the user wants to hotplug a new VFIO PCI device, the VMM will
have to trigger a hotplug notification through the GED device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
0e58741a09 vmm: api: Introduce new "add-device" HTTP endpoint
This commit introduces the new command "add-device" that will let a user
hotplug a VFIO PCI device to an already running VM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
0f1396acef vmm: Insert PCI device hotplug operation region on IO bus
Through the BusDevice implementation from the DeviceManager, and by
inserting the DeviceManager on the IO bus for a specific IO port range,
the VMM now has the ability to handle PCI device hotplug.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
65774e8a78 vmm: Implement BusDevice for DeviceManager
In anticipation of inserting the DeviceManager on the IO/MMIO buses,
the DeviceManager must implement the BusDevice trait.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
2eb26d4de4 devices: acpi: Update GED to support PCI devices hotplug
Expands the existing GED device description in the DSDT table. A new
case of hotplug notification is being added to the already existing CPU
and memory hotplug. The third case of hotplug being the addition/removal
of a PCI device, it is identified through the flag 0x4.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
8dbc84318c vmm: acpi: Add PCNT method to invoke DVNT
Create a small method that will perform both hotplug of all the devices
identified by PCIU bitmap, and then perform the hotunplug of all the
devices identified by the PCID bitmap.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
c62db97a81 vmm: acpi: Add _EJ0 to each PCI device slot
The _EJ0 method provides the guest OS a way to notify the VMM that the
device has been properly ejected from the guest OS. Only after this
point, the VMM can fully remove the device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
4dc2a39f3a vmm: acpi: Create PHPR container
This new PHPR device in the DSDT table introduces some specific
operation regions and the associated fields.

PCIU stands for "PCI up", which identifies PCI devices that must be
added.
PCID stands for "PCI down", which identifies PCI devices that must be
removed.
B0EJ stands for "Bus 0 eject", which identifies which device on the bus
has been ejected by the guest OS.

Thanks to these fields, the VMM and the guest OS can communicate while
performing hotplug/hotunplug operations.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
c3a0685e2d vmm: acpi: Add notification method for PCI device slots
Adds the DVNT method to the PCI0 device in the DSDT table. This new
method is responsible for checking each slot and notify the guest OS if
one of the slots is supposed to be added or removed.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
Sebastien Boeuf
5a68d5b6a7 vmm: acpi: Create PCI device slots
This commit introduces the ACPI support for describing the 32 device
slots attached to the main PCI host bridge.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 12:06:02 +00:00
dependabot-preview[bot]
ead86bb1e4 build(deps): bump micro_http from 9945928 to 88011bd
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `9945928` to `88011bd`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](9945928e28...88011bd64f)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-04 08:46:55 +00:00
Rob Bradford
22dd49d0b5 tests: Test virtio-fs with virtio-mmio
Now that virtio-mmio transport has support for SHM regions we should be
able to test virtio-fs against it.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 09:40:25 +01:00
Rob Bradford
642b890b0f vm-virtio: mmio: Enable reporting of SHM regions via config fields
The details of the SHM regions or the lack of, which is used by
virtio-fs DAX, is communicated through configuration fields on the
virtio-mmio memory region. Implement the necessary fields to return the
SHM entries and in particular return a length of (u64)-1 which is used
by the kernel to indicate there are no SHM regions.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-03-04 09:40:25 +01:00
Sebastien Boeuf
0223cf8c2b ci: Update ClearLinux image
A new ClearLinux image has been uploaded to the Azure storage account.
It is based off of the ClearLinux cloudguest image 31310 version, with
three extra bundles added to it.

First bundle is curl, which adds the curl binary to the image, second
bundle is iperf, adding the iperf binary to the image, and third bundle
is sysadmin-basic to include utility like netcat.

The image is 2G in size.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-03-04 07:31:15 +00:00
dependabot-preview[bot]
ed396b4d58 build(deps): bump vm-memory from 2099f41 to a84a7b8
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `2099f41` to `a84a7b8`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](2099f4162f...a84a7b8f53)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-03 13:44:47 +00:00
Eryu Guan
81c2294c11 vhost_rs: remove unused crate
As we switched to external vhost_rs crate, delete this internal one.
All vhost changes should go to cloud-hypervisor/vhost.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-03 13:14:45 +00:00
Eryu Guan
5200bf3c59 Cargo: switch vhost_rs to external crate
As cloud-hypervisor/vhost crate (dragonball branch) is ready to be used,
switch vhost_rs from internal crate to the external one.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-03-03 13:14:45 +00:00
Arron Wang
65a38e6f70 vm-virtio: vhost_user: Fix blk device configuration space offset value
Current device configuration space offset value is 0, we need to
update that value to VHOST_USER_CONFIG_OFFSET(0x100) to follow the spec

Fixes #844

Signed-off-by: Arron Wang <arron.wang@intel.com>
2020-03-03 12:27:55 +00:00
Bin Liu
d6e6901957 vmm/api: Fix vm.info response definition
Update cloud-hypervisor.yaml with latest code.

Fixes: #841

Signed-off-by: liubin <liubin0329@gmail.com>
2020-03-03 09:34:25 +01:00
dependabot-preview[bot]
8f3720089f build(deps): bump micro_http from 3eb926c to 9945928
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `3eb926c` to `9945928`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](3eb926ccf4...9945928e28)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-03 07:15:28 +00:00
dependabot-preview[bot]
cc2d03d29f build(deps): bump regex-syntax from 0.6.15 to 0.6.16
Bumps [regex-syntax](https://github.com/rust-lang/regex) from 0.6.15 to 0.6.16.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/regex-syntax-0.6.15...regex-syntax-0.6.16)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-03 07:15:15 +00:00
dependabot-preview[bot]
f5b37e3444 build(deps): bump regex-syntax from 0.6.14 to 0.6.15
Bumps [regex-syntax](https://github.com/rust-lang/regex) from 0.6.14 to 0.6.15.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/commits/regex-syntax-0.6.15)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-03-02 12:59:16 +00:00
dependabot-preview[bot]
009f4d23d0 build(deps): bump micro_http from 8d48e73 to 3eb926c
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `8d48e73` to `3eb926c`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](8d48e730f2...3eb926ccf4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-28 07:51:33 +00:00
Rob Bradford
5ade9d4610 tests: Remove unnecessary sleeps and kill on clean shutdown tests
On tests that expect a clean shutdown there is no need to try and kill
the child after wait() has returned as the process has already exited.
Further there is no need to sleep before wait() as wait will block until
the VM and VMM shutdown is complete.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
c98949bdd3 tests: Wait for VMM to exit in test_serial_file/test_console_file
This should address any flakiness as the VMM process will have
completely terminated and all files closed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
2f58fb8307 tests: Test rebooting works for block self spawn test
Being able to reboot the VM is an important aspect of the self spawning
behaviour.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
e817aa6824 tests: Improve VM shutdown behaviour
Many of the tests attempted to SSH into the VM and then run "shutdown"
but don't actually check that the VM has shutdown correctly and proceed
to kill the child process. Remove the associated SSH commands and sleeps
from those tests that are not explicitly checking the shutdown
behaviour.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
559b70cf0a tests: Make output capture optional
Only some tests require the output for the tests to be captured so
default to not capturing the output to a pipe and instead make it
controllable.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
dae7608b1e tests: Remove duplicated network configuration
Many of the tests use an identical network configuration. Add a
GuestCommand::default_net() to generate this configuration and use it
wherever possible.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
6466ad2112 tests: Remove duplicated disk configuration
Many of the tests use an identical disk configuration. Add a
GuestCommand::default_disks() to generate this configuration and use it
wherever possible.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
9f1ac24bed tests: Make the GuestCommand take a reference to the guest
This will be used fill out default parts of the guest command.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
49e70c6203 tests: Port integration tests over to GuestCommand
Rather than creating the command itself delegate to the GuestCommand.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Rob Bradford
67a5882415 tests: Introduce new GuestCommand to handle launching the guest
This is a thin wrapper over std::process:Command which currently only
specifies the default binary but in future will handle more default
behaviour.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-27 17:08:49 +00:00
Sebastien Boeuf
8142c823ed vmm: Move DeviceManager into an Arc<Mutex<>>
In anticipation of the support for device hotplug, this commit moves the
DeviceManager object into an Arc<Mutex<>> when the DeviceManager is
being created. The reason is, we need the DeviceManager to implement the
BusDevice trait and then provide it to the IO bus, so that IO accesses
related to device hotplug can be handled correctly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-27 11:12:31 +01:00
Sergio Lopez
531f4ff6b0 vhost_user_fs: Remove an unneeded unwrap in handle_event
Remove an unneeded unwrap in handle_event.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-26 12:08:12 +01:00
Sergio Lopez
e52129efb4 vhost_user_fs: Process events from HIPRIO queue
We weren't processing events arriving at the HIPRIO queue, which
implied ignoring FUSE_INTERRUPT, FUSE_FORGET, and FUSE_BATCH_FORGET
requests.

One effect of this issue was that file descriptors weren't closed on
the server, so it eventually hits RLIMIT_NOFILE. Additionally, the
guest OS may hang while attempting to unmount the filesystem.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-26 12:08:12 +01:00
dependabot-preview[bot]
0c5c470247 build(deps): bump micro_http from b85757e to 8d48e73
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `b85757e` to `8d48e73`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](b85757ec00...8d48e730f2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-26 07:06:24 +00:00
Sebastien Boeuf
5b96dd5f70 ci: Don't give special capabilities to Rust vhost-user-fs backend
There is no reason to give some special capabilities to the Rust version
of virtiofsd since it behaves slightly differently and does not require
neither DAC_OVERRIDE nor SYS_ADMIN.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-25 15:05:05 +00:00
Sergio Lopez
d8d790bb7b vhost_rs: Don't check for SLAVE_SEND_FD on SET_SLAVE_REQ_FD
SLAVE_SEND_FD and SLAVE_REQ are different protocol features. Check for
SLAVE_REQ instead.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-25 11:12:50 +00:00
Sergio Lopez
1c5562b656 vhost_user_fs: Add support for EVENT_IDX
Now that Queue supports EVENT_IDX, expose the feature and add support
for it in vhost_user_fs.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-25 11:12:50 +00:00
Sergio Lopez
eae4f1d249 vhost_user_fs: Add support for indirect descriptors
Now that Queue supports indirect descriptors, expose the feature and
support them in vhost_user_fs too.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-25 11:12:50 +00:00
Sergio Lopez
ea0bc240fd vhost_user_fs: Be honest about protocol supported features
vhost_user_fs doesn't really support all vhost protocol features, just
MQ and SLAVE_REQ, so return that in protocol_features().

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-25 11:12:50 +00:00
Sergio Lopez
42937c9754 vm-virtio: Add support for indirect descriptors
Indirect descriptors is a virtio feature that allows the driver to
store a table of descriptors anywhere in memory, pointing to it from a
virtqueue ring's descriptor with a particular flag.

We can't seamlessly transition from an iterator over a conventional
descriptor chain to an indirect chain, so Queue users need to
explicitly support this feature by calling Queue::is_indirect() and
Queue::new_from_indirect().

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-25 11:12:50 +00:00
Rob Bradford
d7b0b9842d tests: Move integration tests to their own directory
Simplify main.rs by moving the integration tests to their own directory.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-25 10:42:54 +00:00
Eryu Guan
3cb4513077 vhost_rs: control SlaveFsCacheReq with vhost-user-slave feature
We import slave_fs_cache mod under vhost-user-slave feature control,
but not the self::slave_fs_cache::SlaveFsCacheReq import.

Signed-off-by: Eryu Guan <eguan@linux.alibaba.com>
2020-02-25 09:48:04 +00:00
Qiu Wenbo
9de3ace8c7 devices: implement Aml trait for GED device
Fixes: #657

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2020-02-25 08:32:16 +00:00
Sebastien Boeuf
b77fdeba2d msi/msi-x: Prevent from losing masked interrupts
We want to prevent from losing interrupts while they are masked. The
way they can be lost is due to the internals of how they are connected
through KVM. An eventfd is registered to a specific GSI, and then a
route is associated with this same GSI.

The current code adds/removes a route whenever a mask/unmask action
happens. Problem with this approach, KVM will consume the eventfd but
it won't be able to find an associated route and eventually it won't
be able to deliver the interrupt.

That's why this patch introduces a different way of masking/unmasking
the interrupts, simply by registering/unregistering the eventfd with the
GSI. This way, when the vector is masked, the eventfd is going to be
written but nothing will happen because KVM won't consume the event.
Whenever the unmask happens, the eventfd will be registered with a
specific GSI, and if there's some pending events, KVM will trigger them,
based on the route associated with the GSI.

Suggested-by: Liu Jiang <gerry@linux.alibaba.com>
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-25 08:31:14 +00:00
dependabot-preview[bot]
8423c0897a build(deps): bump proc-macro2 from 1.0.8 to 1.0.9
Bumps [proc-macro2](https://github.com/alexcrichton/proc-macro2) from 1.0.8 to 1.0.9.
- [Release notes](https://github.com/alexcrichton/proc-macro2/releases)
- [Commits](https://github.com/alexcrichton/proc-macro2/compare/1.0.8...1.0.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-25 07:51:48 +00:00
dependabot-preview[bot]
6315f16ca7 build(deps): bump syn from 1.0.15 to 1.0.16
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.15 to 1.0.16.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.15...1.0.16)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-25 07:19:05 +00:00
Qiu Wenbo
4cf89d373d pci: handle extended configuration space properly
This is critical to support extended capabilitiy list.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2020-02-24 17:05:09 +01:00
Qiu Wenbo
f6b9445be7 pci: fix pci MMCONFIG address parsing
We should not assume the offset produced by ECAM is identical to the
CONFIG_ADDRESS register of legacy PCI port io enumeration.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2020-02-24 17:05:09 +01:00
Rob Bradford
77ee331be0 resources: Enable KASLR in kernel config
This option improves the security of the guest by randomising the start
address of the kernel in physical memory. We should turn this on so as
to ensure all our functionality such as memory hotplug and kernel
loading works as this is an option used widely in production.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-24 15:56:37 +00:00
Rob Bradford
bba5ef3a59 vmm: Remove deprecated CPU syntax
Remove the old way of specifying the number of vCPUs to use.

Fixes: #678

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-24 07:26:31 +01:00
Rob Bradford
374ac77c63 main, vmm: Remove deprecated --vhost-user-net
This has been superseded by using --net with vhost_user=true and
socket=<socket>

Fixes: #678

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-24 07:26:31 +01:00
Rob Bradford
ffd816ebfa main, vmm: Remove deprecated --vhost-user-blk
This has been superseded by using --disk with vhost_user=true and
socket=<socket>

Fixes: #678

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-24 07:26:31 +01:00
dependabot-preview[bot]
d04e0dc9e1 build(deps): bump crossbeam-utils from 0.7.0 to 0.7.2
Bumps [crossbeam-utils](https://github.com/crossbeam-rs/crossbeam) from 0.7.0 to 0.7.2.
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-utils-0.7.0...crossbeam-0.7.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-24 06:25:32 +00:00
dependabot-preview[bot]
7da5b531a0 build(deps): bump ssh2 from 0.7.1 to 0.8.0
Bumps [ssh2](https://github.com/alexcrichton/ssh2-rs) from 0.7.1 to 0.8.0.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/0.7.1...0.8.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-24 06:24:52 +00:00
dependabot-preview[bot]
109c7f731d build(deps): bump hermit-abi from 0.1.7 to 0.1.8
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.7 to 0.1.8.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-24 06:24:31 +00:00
dependabot-preview[bot]
812a6b97d3 build(deps): bump syn from 1.0.14 to 1.0.15
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.14 to 1.0.15.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.14...1.0.15)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-22 09:52:59 +00:00
dependabot-preview[bot]
ad307912ab build(deps): bump memchr from 2.3.2 to 2.3.3
Bumps [memchr](https://github.com/BurntSushi/rust-memchr) from 2.3.2 to 2.3.3.
- [Release notes](https://github.com/BurntSushi/rust-memchr/releases)
- [Commits](https://github.com/BurntSushi/rust-memchr/compare/2.3.2...2.3.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-22 09:52:49 +00:00
Rob Bradford
94f2fc3308 release-notes: Update for v0.5.1 bug fix release
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-21 14:31:39 +01:00
dependabot-preview[bot]
f190cb05b5 build(deps): bump libc from 0.2.66 to 0.2.67
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.66 to 0.2.67.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.66...0.2.67)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-21 08:03:30 +00:00
dependabot-preview[bot]
299eb28453 build(deps): bump micro_http from 6fd1545 to b85757e
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `6fd1545` to `b85757e`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](6fd1545222...b85757ec00)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-20 17:12:23 +00:00
Sergio Lopez
d2f1749edb vmm: config: Add poll_queue property to DiskConfig
Recently, vhost_user_block gained the ability of actively polling the
queue, a feature that can be disabled with the poll_queue property.

This change adds this property to DiskConfig, so it can be used
through the "disk" argument.

For the moment, it can only be used when vhost_user=true, but this
will change once virtio-block gets the poll_queue feature too.

Fixes: #787

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-20 18:06:54 +01:00
Sergio Lopez
378dd81204 vmm: openapi: Add missing "direct" knob to DiskConfig
Add missing "direct" knob that should be exposed through the REST API.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-20 18:06:54 +01:00
Sergio Lopez
056f5481ac vmm: openapi: Fix "readonly" and "wce" defaults in DiskConfig
Fix "readonly" and "wce" defaults in cloud-hypervisor.yaml to match
their respective defaults in config.rs:DiskConfig.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-20 18:06:54 +01:00
Rob Bradford
4ebf01b344 vhost_user_backend: Don't report out socket broken errors
This is a perfectly acceptable situation as it causes the backend to
exit because the VMM has closed the connection. This addresses the
rather ugly reporting of errors from the backend that appears
interleaved with the output from the VMM.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-20 14:30:27 +00:00
Rob Bradford
b5755e9c33 vhost_rs: vhost_user: Return error when connection broken
Return an error wen recvmsg() returns without a message using the
libc::ECONNRESET error so that the upper levels will correctly
interpret this as the connection being broken.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-20 14:30:27 +00:00
Samuel Ortiz
c49e31a6d9 vmm: api: Return a resize error when resize fails
And not a VmCreate one.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-20 12:26:12 +01:00
Samuel Ortiz
ebc6391bea vmm: api: Fix resize command typos
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-20 12:26:12 +01:00
Samuel Ortiz
9de755334d vmm: openapi: Update DiskConfig
It's missing a few knobs (readonly, vhost, wce) that should be exposed
through the rest API.

Fixes: #790

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-20 12:17:50 +01:00
Rob Bradford
ed1e7817cc vmm: Workaround double reboot triggered by the kernel
The kernel does not adhere to the ACPI specification (probably to work
around broken hardware) and rather than busy looping after requesting an
ACPI reset it will attempt to reset by other mechanisms (such as i8042
reset.)

In order to trigger a reset the devices write to an EventFd (called
reset_evt.) This is used by the VMM to identify if a reset is requested
and make the VM reboot. As the reset_evt is part of the VMM and reused
for both the old and new VM it is possible for the newly booted VM to
immediately get reset as there is an old event sitting in the EventFd.

The simplest solution is to "drain" the reset_evt EventFd on reboot to
make sure that there is no spurious events in the EventFd.

Fixes: #783

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-19 18:51:14 +01:00
Sergio Lopez
5c06b7f862 vhost_user_block: Implement optional static polling
Actively polling the virtqueue significantly reduces the latency of
each I/O operation, at the expense of using more CPU time. This
features is specially useful when using low-latency devices (SSD,
NVMe) as the backend.

This change implements static polling. When a request arrives after
being idle, vhost_user_block will keep checking the virtqueue for new
requests, until POLL_QUEUE_US (50us) has passed without finding one.

POLL_QUEUE_US is defined to be 50us, based on the current latency of
enterprise SSDs (< 30us) and the overhead of the emulation.

This feature is enabled by default, and can be disabled by using the
"poll_queue" parameter of "block-backend".

This is a test using null_blk as a backend for the image, with the
following parameters:

 - null_blk gb=20 nr_devices=1 irqmode=2 completion_nsec=0 no_sched=1

With "poll_queue=false":

fio --ioengine=sync --bs=4k --rw randread --name randread --direct=1
--filename=/dev/vdb --time_based --runtime=10

randread: (g=0): rw=randread, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=sync, iodepth=1
fio-3.14
Starting 1 process
Jobs: 1 (f=1): [r(1)][100.0%][r=169MiB/s][r=43.2k IOPS][eta 00m:00s]
randread: (groupid=0, jobs=1): err= 0: pid=433: Tue Feb 18 11:12:59 2020
  read: IOPS=43.2k, BW=169MiB/s (177MB/s)(1688MiB/10001msec)
    clat (usec): min=17, max=836, avg=21.64, stdev= 3.81
     lat (usec): min=17, max=836, avg=21.77, stdev= 3.81
    clat percentiles (nsec):
     |  1.00th=[19328],  5.00th=[19840], 10.00th=[20352], 20.00th=[21120],
     | 30.00th=[21376], 40.00th=[21376], 50.00th=[21376], 60.00th=[21632],
     | 70.00th=[21632], 80.00th=[21888], 90.00th=[22144], 95.00th=[22912],
     | 99.00th=[28544], 99.50th=[30336], 99.90th=[39168], 99.95th=[42752],
     | 99.99th=[71168]
   bw (  KiB/s): min=168440, max=188496, per=100.00%, avg=172912.00, stdev=3975.63, samples=19
   iops        : min=42110, max=47124, avg=43228.00, stdev=993.91, samples=19
  lat (usec)   : 20=5.90%, 50=94.08%, 100=0.02%, 250=0.01%, 500=0.01%
  lat (usec)   : 750=0.01%, 1000=0.01%
  cpu          : usr=10.35%, sys=25.82%, ctx=432417, majf=0, minf=10
  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=432220,0,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=1

Run status group 0 (all jobs):
   READ: bw=169MiB/s (177MB/s), 169MiB/s-169MiB/s (177MB/s-177MB/s), io=1688MiB (1770MB), run=10001-10001msec

Disk stats (read/write):
  vdb: ios=427867/0, merge=0/0, ticks=7346/0, in_queue=0, util=99.04%

With "poll_queue=true" (default):

fio --ioengine=sync --bs=4k --rw randread --name randread --direct=1
--filename=/dev/vdb --time_based --runtime=10

randread: (g=0): rw=randread, bs=(R) 4096B-4096B, (W) 4096B-4096B, (T) 4096B-4096B, ioengine=sync, iodepth=1
fio-3.14
Starting 1 process
Jobs: 1 (f=1): [r(1)][100.0%][r=260MiB/s][r=66.7k IOPS][eta 00m:00s]
randread: (groupid=0, jobs=1): err= 0: pid=422: Tue Feb 18 11:14:47 2020
  read: IOPS=68.5k, BW=267MiB/s (280MB/s)(2674MiB/10001msec)
    clat (usec): min=10, max=966, avg=13.60, stdev= 3.49
     lat (usec): min=10, max=966, avg=13.70, stdev= 3.50
    clat percentiles (nsec):
     |  1.00th=[11200],  5.00th=[11968], 10.00th=[11968], 20.00th=[12224],
     | 30.00th=[12992], 40.00th=[13504], 50.00th=[13760], 60.00th=[13888],
     | 70.00th=[14016], 80.00th=[14144], 90.00th=[14272], 95.00th=[14656],
     | 99.00th=[20352], 99.50th=[23936], 99.90th=[35072], 99.95th=[36096],
     | 99.99th=[47872]
   bw (  KiB/s): min=265456, max=296456, per=100.00%, avg=274229.05, stdev=13048.14, samples=19
   iops        : min=66364, max=74114, avg=68557.26, stdev=3262.03, samples=19
  lat (usec)   : 20=98.84%, 50=1.15%, 100=0.01%, 250=0.01%, 500=0.01%
  lat (usec)   : 750=0.01%, 1000=0.01%
  cpu          : usr=8.24%, sys=21.15%, ctx=684669, majf=0, minf=10
  IO depths    : 1=100.0%, 2=0.0%, 4=0.0%, 8=0.0%, 16=0.0%, 32=0.0%, >=64=0.0%
     submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
     issued rwts: total=684611,0,0,0 short=0,0,0,0 dropped=0,0,0,0
     latency   : target=0, window=0, percentile=100.00%, depth=1

Run status group 0 (all jobs):
   READ: bw=267MiB/s (280MB/s), 267MiB/s-267MiB/s (280MB/s-280MB/s), io=2674MiB (2804MB), run=10001-10001msec

Disk stats (read/write):
  vdb: ios=677855/0, merge=0/0, ticks=7026/0, in_queue=0, util=99.04%

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-19 17:13:47 +00:00
Sergio Lopez
0e4e27ea9d vhost_user_block: Make use of the EVENT_IDX feature
Now that vhost_user_backend and vm-virtio do support EVENT_IDX, use it
in vhost_user_block to reduce the number of notifications sent between
the driver and the device.

This is specially useful when using active polling on the virtqueue,
as it'll be implemented by a future patch.

This is a snapshot of kvm_stat while generating ~60K IOPS with fio on
the guest without EVENT_IDX:

 Event                                         Total %Total CurAvg/s
 kvm_entry                                    393454   20.3    62494
 kvm_exit                                     393446   20.3    62494
 kvm_apic_accept_irq                          378146   19.5    60268
 kvm_msi_set_irq                              369720   19.0    58881
 kvm_fast_mmio                                370497   19.1    58817
 kvm_hv_timer_state                            10197    0.5     1715
 kvm_msr                                        8770    0.5     1443
 kvm_wait_lapic_expire                          7018    0.4     1118
 kvm_apic                                       2768    0.1      538
 kvm_pv_tlb_flush                               2028    0.1      360
 kvm_vcpu_wakeup                                1453    0.1      278
 kvm_apic_ipi                                   1384    0.1      269
 kvm_fpu                                        1148    0.1      164
 kvm_pio                                         574    0.0	  82
 kvm_userspace_exit                              574    0.0	  82
 kvm_halt_poll_ns                                 24    0.0	   3

And this is the snapshot while doing the same thing with EVENT_IDX:

 Event                                         Total %Total CurAvg/s
 kvm_entry                                     35506   26.0     3873
 kvm_exit                                      35499   26.0     3873
 kvm_hv_timer_state                            14740   10.8     1672
 kvm_apic_accept_irq                           13017    9.5     1438
 kvm_msr                                       12845    9.4     1421
 kvm_wait_lapic_expire                         10422    7.6     1118
 kvm_apic                                       3788    2.8      502
 kvm_pv_tlb_flush                               2708    2.0      340
 kvm_vcpu_wakeup                                1992    1.5      258
 kvm_apic_ipi                                   1894    1.4      251
 kvm_fpu                                        1476    1.1      164
 kvm_pio                                         738    0.5       82
 kvm_userspace_exit                              738    0.5	  82
 kvm_msi_set_irq                                 701    0.5	  69
 kvm_fast_mmio                                   238    0.2        4
 kvm_halt_poll_ns                                 50    0.0        1
 kvm_ple_window_update                            28    0.0        0
 kvm_page_fault                                    4    0.0        0

It can be clearly appreciated how the number of vm exits per second,
specially the ones related to notifications (kvm_fast_mmio and
kvm_msi_set_irq) is drastically lower.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-19 17:13:47 +00:00
Sergio Lopez
1ef6996207 vhost_user_backend: Add helpers for EVENT_IDX
Add helpers to Vring and VhostUserSlaveReqHandler for EVENT_IDX, so
consumers of this crate can make use of this feature.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-19 17:13:47 +00:00
Sergio Lopez
d17fa784bc vm-virtio: Implement support for EVENT_IDX
VIRTIO_RING_F_EVENT_IDX is a virtio feature that allows to avoid
device <-> driver notifications under some circunstances, most
notably when actively polling the queue.

This commit implements support for in in the vm-virtio
crate. Consumers of this crate will also need to add support for it by
exposing the feature and calling using update_avail_event() and
get_used_event() accordingly.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-02-19 17:13:47 +00:00
Sebastien Boeuf
793d4e7b8d vmm: Move codebase to GuestMemoryAtomic from vm-memory
Relying on the latest vm-memory version, including the freshly
introduced structure GuestMemoryAtomic, this patch replaces every
occurrence of Arc<ArcSwap<GuestMemoryMmap> with
GuestMemoryAtomic<GuestMemoryMmap>.

The point is to rely on the common RCU-like implementation from
vm-memory so that we don't have to do it from Cloud-Hypervisor.

Fixes #735

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-19 13:48:19 +00:00
Sebastien Boeuf
ddf6caf955 ci: Improve test_memory_mergeable_on stability
The integration test test_memory_mergeable_on has been fairly unstable
for quite some time now. Because it can take some time for the VM to be
spawned and to be able to perform a correct measure of the PSS, this
commit simply increases the time before such measure is done.
This should return more accurate PSS results, which should help
stabilize the test.

Fixes #781

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-19 12:36:28 +00:00
dependabot-preview[bot]
af621be509 build(deps): bump micro_http from 57ac9df to 6fd1545
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `57ac9df` to `6fd1545`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](57ac9df0ad...6fd1545222)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-19 07:53:09 +00:00
Liu Bo
4970e2f703 vhost-user-fs: add dax tests for vhost_user_fs rust daemon
Now that vhost_user_fs rust daemon supports virtiofs's dax mode, this adds
the two dax tests accordingly.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-02-19 07:52:50 +00:00
Liu Bo
59958f0a61 vhost_user_fs: add the ability to set slave req fd
This adds the missing part of supporting virtiofs dax on the slave end,
that is, receiving a socket pair fd from the master end to set up a
communication channel for sending setupmapping & removemapping messages.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-02-19 07:52:50 +00:00
Liu Bo
3f09eff6c5 vhost_user_fs: add fs cache request operations
This introduces setupmapping and removemapping methods to server.rs,
passthrough.rs and filesystem.rs in order to support virtiofs dax mode
inside guest.

Since we don't really want the server.rs to know that it is dealing with
vhost-user specifically, this is making it more generic by adding a new
trait which has three functions map()/unmap()/sync() corresponding to
fs_slave_{map, unmap, sync}, server.rs will take anything that implements
the trait.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-02-19 07:52:50 +00:00
Liu Bo
956a84f73a vhost_user_fs: add necessary structs for map/unmap requests
This is adding some structures with which we will talk with guest kernel on
map/unmap requests.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-02-19 07:52:50 +00:00
Liu Bo
269d660b0a vhost_user_fs: add SlaveFsCacheReq to handle map/unmap
This introduces SlaveFsCacheReq which implements
VhostUserMasterReqHandler to handle map/unmap requests.

Signed-off-by: Liu Bo <bo.liu@linux.alibaba.com>
2020-02-19 07:52:50 +00:00
Sebastien Boeuf
be78c6da49 vhost_rs: Fix unit test race condition
The unit tests are run from cargo test through multiple threads of the
same process. For this reason, all these threads share their file
descriptors (because that's how this works on Linux), which means that
any of them can close a file descriptor opened from another thread.

In the context of create_listener() and accept_connection() tests, they
can run concurrently and this generates some failure when the file
descriptor create_listener() is binding to is being closed from the
accept_connection() test.

In order to avoid such race condition, this patch simply removes the
part of the unit test performing an explicit and unsafe file descriptor
closure.

Fixes #759

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-18 16:59:13 +01:00
Rob Bradford
f7378bc092 tests: Add self spawning vhost-user-block test
Also rename the net self spawning test to differentiate it from the the
block one.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-18 08:43:47 +00:00
Rob Bradford
1f6cbad01a vmm: Add support for spawning vhost-user-block backend
If no socket is supplied when enabling "vhost_user=true" on "--disk"
follow the "exe" path in the /proc entry for this process and launch the
network backend (via the vmm_path field.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-18 08:43:47 +00:00
Rob Bradford
4d60ef59bc vm-virtio: vhost_user: block: On shutdown() drop the socket
This causes the vhost-user-block backend to shutdown.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-18 08:43:47 +00:00
Sebastien Boeuf
7fabca3548 ci: Don't run unit tests in a privileged container
The unit tests require some specific Linux capabilities and also to have
access to /dev/kvm device. This commit makes sure we enable only what's
necessary instead of blindly enable full priviliges with --privileged
option.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-18 08:53:03 +01:00
dependabot-preview[bot]
27247164b5 build(deps): bump micro_http from 4827569 to 57ac9df
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `4827569` to `57ac9df`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](482756925c...57ac9df0ad)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-18 06:42:39 +00:00
Rob Bradford
08a68f2f0f build: Run unit tests on worker node
The unit tests require higher privileges so for safety run on the worker
nodes.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-17 15:41:06 +00:00
Samuel Ortiz
f21cd31b94 scripts: dev_cli: Add more privileges for the integration tests
We need the host IPC for sharing eventfds with KVM, and the host network
for VFIO.

We also enforce the no-seccomp setting on the container, to overcome any
potential filtering set by our container's Ubuntu base.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-17 15:06:04 +00:00
Rob Bradford
a94887e051 build: Use dev container for integration tests
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-17 15:06:04 +00:00
Sebastien Boeuf
3edc2bd6ab vmm: Prevent memory overcommitment through virtio-fs shared regions
When a virtio-fs device is created with a dedicated shared region, by
default the region should be mapped as PROT_NONE so that no pages can be
faulted in.

It's only when the guest performs the mount of the virtiofs filesystem
that we can expect the VMM, on behalf of the backend, to perform some
new mappings in the reserved shared window, using PROT_READ and/or
PROT_WRITE.

Fixes #763

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-17 15:03:47 +01:00
dependabot-preview[bot]
968c90a6ce build(deps): bump hermit-abi from 0.1.6 to 0.1.7
Bumps [hermit-abi](https://github.com/hermitcore/rusty-hermit) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/hermitcore/rusty-hermit/releases)
- [Commits](https://github.com/hermitcore/rusty-hermit/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-17 11:17:39 +00:00
Rob Bradford
7485a0c1f7 Revert "build: Don't fail build on test_vfio failure"
This reverts commit 014844d0da.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-17 08:23:02 +00:00
dependabot-preview[bot]
cbc0ac3267 build(deps): bump micro_http from 7a23e54 to 4827569
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `7a23e54` to `4827569`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](7a23e54775...482756925c)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-17 07:41:05 +00:00
dependabot-preview[bot]
7fdb5ae4c4 build(deps): bump vm-memory from eb2fc0b to f615b19
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `eb2fc0b` to `f615b19`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](eb2fc0b6d9...f615b19469)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-17 07:40:49 +00:00
dependabot-preview[bot]
0d748c5c2b build(deps): bump scopeguard from 1.0.0 to 1.1.0
Bumps [scopeguard](https://github.com/bluss/scopeguard) from 1.0.0 to 1.1.0.
- [Release notes](https://github.com/bluss/scopeguard/releases)
- [Commits](https://github.com/bluss/scopeguard/compare/1.0.0...v1.1.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-17 07:40:24 +00:00
dependabot-preview[bot]
6692fa60e9 build(deps): bump thiserror from 1.0.10 to 1.0.11
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.10 to 1.0.11.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.10...1.0.11)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-15 11:05:06 +00:00
Rob Bradford
f03602a4c9 tests: Add self spawning vhost-user-net test
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
bc75c1b4e1 vmm: Add support for spawning vhost-user-net backend
If no socket is supplied when enabling "vhost_user=true" on "--net"
follow the "exe" path in the /proc entry for this process and launch the
network backend (via the vmm_path field.)

Currently this only supports creating a new tap interface as the network
backend also only supports that.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
d054dddcb3 vm-virtio: Retry connections to vhost-user backends
If the connection to the backend fails, sleep and retry up to a count.
This failure could happen because the backend is not yet ready to handle
the connection which is a common case when working with a spawned
backend.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
b04eb4770b vmm: Follow the "exe" symlink from the PID directory in /proc
It is necessary to do this at the start of the VMM execution rather than
later as it must be done in the main thread in order to satisfy the
checks required by PTRACE_MODE_READ_FSCREDS (see proc(5) and
ptrace(2))

The alternative is to run as CAP_SYS_PTRACE but that has its
disadvantages.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
503887843f vm-virtio: vhost_user: net: On shutdown() drop the socket
This causes the vhost-user-net backend to shutdown.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
7c9e8b103f vmm: device_manager: Shutdown all virtio devices
When the DeviceManager is dropped explicitly shutdown() all virtio
devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Rob Bradford
545ea9ea33 vm-virtio: Add shutdown method to VirtioDevice trait
This allows the VMM to explicitly shutdown devices as part of the VM
shutdown ahead of what Drop::drop() would do.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-14 17:32:49 +00:00
Bo Chen
ebd83699dc main: Display git commit hash with the '--version' option
Add a build-script to propagate the git commit hash to other crates at
compile time through environment variables, and display the hash along
with the '--version' option.

Fixes #729

Signed-off-by: Bo Chen <chen.bo@intel.com>
2020-02-14 10:00:14 +01:00
dependabot-preview[bot]
bdb92f9ace build(deps): bump micro_http from 7fb2e46 to 7a23e54
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `7fb2e46` to `7a23e54`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](7fb2e4658a...7a23e54775)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-14 07:27:28 +00:00
Rob Bradford
2061f0d8b4 tests: Always create shared VFIO directory from scratch
This ensures that any changes to the contents will not affect subsequent
tests runs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-13 17:55:21 +01:00
Rob Bradford
e8e4f43d52 tests: Use hugepages for test_vfio
Using hugepages with VFIO and virtiofs can improve the performance of
the test_vfio test.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-13 17:55:21 +01:00
Samuel Ortiz
296ada9441 scripts: dev_cli: Fix post build permissions for the whole tree
Fixes: #752

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-13 17:52:30 +01:00
Rob Bradford
287897d702 tests: Run test_vfio with PCI binary
The placement of the explicit run of "test_vfio" meant it was run with
MMIO rather than PCI which meant it always failed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-13 13:37:58 +00:00
dependabot-preview[bot]
16614447eb build(deps): bump serde_json from 1.0.47 to 1.0.48
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.47 to 1.0.48.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.47...v1.0.48)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-13 09:03:24 +00:00
dependabot-preview[bot]
96479dabe6 build(deps): bump vm-memory from f3d1c27 to eb2fc0b
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `f3d1c27` to `eb2fc0b`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](f3d1c2775c...eb2fc0b6d9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-13 07:20:51 +00:00
dependabot-preview[bot]
88c1683029 build(deps): bump memchr from 2.3.1 to 2.3.2
Bumps [memchr](https://github.com/BurntSushi/rust-memchr) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/BurntSushi/rust-memchr/releases)
- [Commits](https://github.com/BurntSushi/rust-memchr/compare/2.3.1...2.3.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-13 07:20:34 +00:00
dependabot-preview[bot]
8d3e4f989d build(deps): bump micro_http from c9e900c to 7fb2e46
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `c9e900c` to `7fb2e46`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](c9e900c181...7fb2e4658a)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-12 18:12:43 +00:00
Sebastien Boeuf
53481aabe5 docs: Update documentation related to multiqueue network
Just updating the documentation regarding the pre-creation of a tap
interface supporting multiqueue, by adding what the cloud-hypervisor
--net parameter should look like.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-12 18:05:42 +00:00
Sebastien Boeuf
4dd16c2686 vm-virtio: Detect if a tap interface supports multiqueue
By detecting if an existing tap interface supports multiqueue, we now
have the information to determine if the command line parameters
regarding the number of queues is correct.

Fixes #738

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-12 18:05:42 +00:00
Sebastien Boeuf
8627656f55 net_util: Provide more accurate error messages
In order to identify better the problem whenever an existing TAP is
provided, this patch enhances the error returned for an easier
diagnosis of the problem.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-12 18:05:42 +00:00
dependabot-preview[bot]
6e5338d28f build(deps): bump memchr from 2.3.0 to 2.3.1
Bumps [memchr](https://github.com/BurntSushi/rust-memchr) from 2.3.0 to 2.3.1.
- [Release notes](https://github.com/BurntSushi/rust-memchr/releases)
- [Commits](https://github.com/BurntSushi/rust-memchr/compare/2.3.0...2.3.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-12 17:29:03 +00:00
Rob Bradford
014844d0da build: Don't fail build on test_vfio failure
test_vfio has been failing consistently on the CI so mark it with
a "#[ignore]" and then forceably build it again but ignore the build
result.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-12 15:37:47 +00:00
dependabot-preview[bot]
779cbfe8bd build(deps): bump backtrace from 0.3.43 to 0.3.44
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.43 to 0.3.44.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.43...0.3.44)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-11 18:10:45 +00:00
Rob Bradford
700df9eb16 vhost_user_net: Port to new exit event strategy
Implement the exit_event() method on the VhostUserBackend trait. It is
necessary to specify a custom exit event id in this case as the loop is
also used for handling activity on the tap file descriptors.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-11 15:21:07 +01:00
Rob Bradford
c33c38bd96 vhost_user_block: Port to new exit event strategy
Implement the newly added exit_event() method on the VhostUserBackend
trait to allow the backend to provide an EventFD for triggering an exit
of the worker thread.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-11 15:21:07 +01:00
Rob Bradford
da7f31d4bc bin: vhost_user_fs: Port to new exit event strategy
Rather than handling the KILL_EVENT in the event handler itself use the
newly added support in VhostUserBackend for providing a kill event
framework.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-11 15:21:07 +01:00
Rob Bradford
759a0be6cd vhost_user_backend: Add support for handling exiting of worker thread
All backends currently provide their own implementation for triggering
the worker thread to exit via an EventFd. Modify the VhostUserBackend
trait to allow a common implementation strategy that backends can use to
provide an EventFd (and optional id) that can be used to trigger the
worker to exit.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-11 15:21:07 +01:00
dependabot-preview[bot]
b17bafb530 build(deps): bump micro_http from 1de6f32 to c9e900c
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `1de6f32` to `c9e900c`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](1de6f32610...c9e900c181)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-11 07:16:11 +00:00
Rob Bradford
7ca691fc2f vhost_user_block: Implement and use worker shutdown
Add a kill EventFD and use this to shutdown the worker thread when the
backend terminates.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
e619fe6b01 vhost_user_net: Remove "Clone" implementation
There is no need for this and it could lead to inadvertent issues in the
future.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
613f254908 vhost_user_backend: Wait on the worker thread
Check the return value from the worker thread by saving the thread
handle and waiting for it to return.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
97ab767a2f vhost_user_net: Shutdown worker thread on exit
This will ensure a clean shutdown of the backend

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
7f032c8bb3 bin: vhost_user_fs: Shutdown worker thread on exit
This will ensure a clean shutdown of the backend

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
99cb8dc0a4 bin: vhost_user_fs use error! macro logging for consistency
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
710394b872 vhost_user_block: Forward the error from unexpected event
This is consistent with vhost-user-net and vhost-user-fs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
4f4c3d3ebe vhost_user_block: Make Error behave like net and fs versions
Make the Error struct behave more like the net and fs equivalents.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
f1e19d6c96 vhost_user_backend: Forward the error from main thread
The main thread returns a Result with any errors from it. Although the
error from the join itself was being returned the real error from the
thread was being ignored so ensure that it is forwarded.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Rob Bradford
80c9dc2e0c Revert "vhost-user-backend: Correct error handling in run"
This reverts commit 4a1af7f63c.

This change erroneously ignored the return value for the result which
meant that requests to break out of the loop due to a kill event were
lost.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-10 09:16:49 +01:00
Samuel Ortiz
c706ca1522 scripts: dev_cli: Simplify the build command exit path
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-10 09:11:17 +01:00
Samuel Ortiz
0a1d6e1cb3 scripts: dev_cli: Fix build directory permisions
All our tests must be run as root and thus the build directory is owned
by root after we run any of them.

Start another container to fix all permissions whenever we're done with
our tests.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-10 09:11:17 +01:00
Samuel Ortiz
c8fa8092c5 scripts: dev_cli: Run unprivileged containers as the host user
By default we will run as root inside the container, which means all the
build artifacts will be owned by root. That prevents us from properly
cleaning our build from an unprivileged host user.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-10 09:11:17 +01:00
dependabot-preview[bot]
26d8caedb6 build(deps): bump micro_http from ae15e75 to 1de6f32
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `ae15e75` to `1de6f32`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](ae15e75eb7...1de6f32610)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-10 07:22:59 +00:00
dependabot-preview[bot]
572aaa7231 build(deps): bump serde_json from 1.0.46 to 1.0.47
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.46 to 1.0.47.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.46...v1.0.47)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-08 00:27:55 +00:00
Rob Bradford
04cb35e3f4 scripts: Make dev_cli.sh exit on test error
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-07 17:24:32 +00:00
Rob Bradford
9bf100c91c build: Run worker and master build in parallel
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-07 17:24:32 +00:00
Rob Bradford
bfbca596ea scripts: Don't use interactive & terminal mode for docker
When running the docker container there is no interactivity needed so
don't pass "-ti" to "docker run"

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-07 17:24:32 +00:00
Rob Bradford
6e6eb5b55e build: Do cargo tests, unit tests and OpenAPI check on master
Rather than on the CI nodes.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-07 17:24:32 +00:00
Samuel Ortiz
a5b053f81d scripts: dev_cli: Use a tmpfs mount for /tmp
To mitigate Azure slow disk IO, we mount /tmp on tmpfs.
This is a reproduction of our CI environment, as setup by the
Jenkinsfile.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-07 17:33:30 +01:00
Samuel Ortiz
2f395e60a0 release: v0.5.0
Expand the release notes and bump Cargo.toml.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-07 16:17:06 +01:00
dependabot-preview[bot]
d46c61c5d4 build(deps): bump byteorder from 1.3.2 to 1.3.4
Bumps [byteorder](https://github.com/BurntSushi/byteorder) from 1.3.2 to 1.3.4.
- [Release notes](https://github.com/BurntSushi/byteorder/releases)
- [Changelog](https://github.com/BurntSushi/byteorder/blob/master/CHANGELOG.md)
- [Commits](https://github.com/BurntSushi/byteorder/compare/1.3.2...1.3.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-07 14:18:07 +00:00
Samuel Ortiz
0cd3325a06 docs: Cloud Hypervisor API documentation
We document both the internal and external APIs, and how they relate to
each others.

Fixes: #318

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-07 11:26:41 +01:00
Cathy Zhang
14eddf72b4 vm-virtio: Simplify virtio feature handling
Remove duplicated code across the different devices by handling
the virtio feature pages in VirtioDevice itself rather than
in the backends. This works as no virtio devices use feature
bits beyond 64-bits.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-02-07 08:32:21 +00:00
dependabot-preview[bot]
411e2b43ba build(deps): bump micro_http from 10d1f4a to ae15e75
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `10d1f4a` to `ae15e75`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](10d1f4aa59...ae15e75eb7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-07 08:24:12 +00:00
Bo Chen
3bf46d4c80 README: Fix a typo for using cli_dev
Fix the typo for the instructions of using cli_dev to run unit tests.

Signed-off-by: Bo Chen <chen.bo@intel.com>
2020-02-06 18:02:21 +01:00
Sebastien Boeuf
3447e226d9 dependencies: bump vm-memory from 4237db3 to f3d1c27
This commit updates Cloud-Hypervisor to rely on the latest version of
the vm-memory crate.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-06 11:40:45 +01:00
dependabot-preview[bot]
ae87455242 build(deps): bump micro_http from ab44474 to 10d1f4a
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `ab44474` to `10d1f4a`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](ab44474a08...10d1f4aa59)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-06 06:35:35 +00:00
Sebastien Boeuf
62ccccc303 vmm: Make sure to retry creating the VM on EINTR
If the ioctl syscall KVM_CREATE_VM gets interrupted while creating the
VM, it is expected that we should retry since EINTR should not be
considered a standard error.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-05 12:06:21 +01:00
dependabot-preview[bot]
671b49ba23 build(deps): bump vm-memory from d6229fc to 4237db3
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `d6229fc` to `4237db3`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](d6229fc5bd...4237db35e8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-05 07:28:33 +00:00
dependabot-preview[bot]
e5b7fff990 build(deps): bump micro_http from 1eb80f8 to ab44474
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `1eb80f8` to `ab44474`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](1eb80f8d1b...ab44474a08)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-05 07:28:22 +00:00
Samuel Ortiz
da2b3c92d3 vm-device: interrupt: Remove InterruptType dependencies and definitions
Having the InterruptManager trait depend on an InterruptType forces
implementations into supporting potentially very different kind of
interrupts from the same code base. What we're defining through the
current, interrupt type based create_group() method is a need for having
different interrupt managers for different kind of interrupts.

By associating the InterruptManager trait to an interrupt group
configuration type, we create a cleaner design to support that need as
we're basically saying that one interrupt manager should have the single
responsibility of supporting one kind of interrupt (defined through its
configuration).

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-04 19:32:45 +01:00
Samuel Ortiz
84fc807bc6 interrupt: Interrupt manager split
We create 2 different interrupt managers for separately handling
creation of legacy and MSI interrupt groups.
Doing so allows us to have a cleaner interrupt manager and IOAPIC
initialization path. It also prepares for an InterruptManager trait
design improvement where we remove the interrupt source type dependency
by associating an interrupt configuration type to the trait.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-04 19:32:45 +01:00
Sebastien Boeuf
56d7c04226 vm-virtio: vsock: Don't return error when epoll_wait is interrupted
The existing code taking care of the epoll loop was too restrictive as
it was considering all errors the same. But in case the error is EINTR,
this means the syscall has been interrupted while waiting, and it should
be resumed to wait again.

This patch enforces the parsing of the returned error and prevent the
code from assuming EINTR should be handled as all other errors.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-02-04 18:16:37 +01:00
Rob Bradford
6e6b2b84fe scripts: Check the Rust formatting is valid
Check the rust formatting rather than just reformatting code on the CI
agent.

Also fix a formatting error that slipped in whilst the cargo fmt check
was not working correctly.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-04 16:47:05 +01:00
Samuel Ortiz
705f27151d scripts: dev_cli: Pass unit and integration test args to cargo test
In order, among other things, to use the development CLI to run specific
integration tests. For example, to run only the memory_overhead
integration test:

./scripts/dev_cli.sh tests --integration -- memory_overhead

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-04 15:31:58 +01:00
Rob Bradford
bc053f1b13 main: Ignore error on log writing
A previous version of this change attempted to avoid panicking by not
using .expect() when handling an error when attempting to write to the
log file. Unfortunately the macro eprintln!() that was used to replace
the .expect() also has the behaviour of panicking if stderr cannot be
used. Instead swallow the error completely as if writing to the log has
failed at logging time it is almost certainly the case that any message
about the log would also not be seen.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-04 12:22:23 +00:00
Yang Zhong
91739be120 main: Add help info for block-backend
Since the vhost-user-blk binary will be removed and the newer
release will integrate this block backend into cloud-hypervisor
binary. The block backend code has been added num_queues cmdline
support, we need update multiple queues help info for this
block-backend in the cloud-hypervisor.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-02-04 11:06:17 +00:00
Samuel Ortiz
ae6cf4c922 tests: integration: Add memory overhead test
We measure the memory overhead that the VMM process adds to the guest VM
and compare it with a maximum acceptable limit. The test is run against
a simple VM, running 1 vCPU and 512MB of RAM. Although this is not by
any mean a comprehensive VMM overhead measurement, it will allow us to
detect when and if any PR makes our code cross an arbitrary memory
overhead threshold.

Fixes: #64

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-02-04 09:23:56 +00:00
Rob Bradford
7cb61d3960 main: Don't panic (by calling .expect()) if writing to the log fails
As this can happen during the running of the VMM we should be very
careful not to panic() as that can lead to a thread being used by the VM
disappearing.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 19:08:08 +01:00
Rob Bradford
880a57c920 vmm: Remove VmInfo struct
After refactoring the VmInfo struct is no longer needed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
07bc292fa5 vmm: device_manager: Get VmFd from AddressManager
A reference to the VmFd is stored on the AddressManager so it is not
necessary to pass in the VmInfo into all methods that need it as it can
be obtained from the AddressManager.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
6411c3ae42 vmm: device_manager: Use MemoryManager to get guest memory
The DeviceManager has a reference to the MemoryManager so use that to
get the GuestMemoryMmap rather than the version stored in the VmInfo
struct.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
066fc6c0d1 vmm: device_manager: Get VM config from the struct member
Remove the use of vm_info in methods to get the config and instead use
the config stored on the DeviceManager itself.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
77ae3de4f3 vmm: device_manager: Make legacy device addition a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
599275b610 vmm: device_manager: Make ACPI device creation a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
b8c1b2e174 vmm: device_manager: Make console creation a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
b5440e2d0a vmm: device_manager: Make virtio device creation functions methods
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter. This prepares the way to more easily store state on
the DeviceManager.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
e90c6f3c44 vmm: device_manager: Make make_virtio_devices a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter. A follow-up commit will change the callee functions
that create the devices themselves.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
dbc09ad0ef vmm: device_manager: Make add_vfio_devices a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
d9e1c2cd22 vmm: device_manager: Make add_virtio_pci_device a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
aaa5e2e9ea vmm: device_manager: Make add_virtio_mmio_device a method
Remove some in/out parameters and instead rely on them as members of the
&mut self parameter.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
2987476e0a vmm: device_manager: Make add_pci_devices and add_mmio_devices methods
Modify these functions to take an &mut self and become methods on
DeviceManager. This allows the removal of some in/out parameters and
leads the way to further refactoring and simplification.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
3dbae423bb vmm: device_manager: Only add MemoryManager to I/O bus on ACPI builds
The MemoryManager should only be included on the I/O bus when doing ACPI
builds as that is the only time it will be interrogated.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Rob Bradford
68fa97eb0e vmm: device_manager: Always embed MemoryManager in the struct
Currently the MemoryManager is only used on the ACPI code paths after
the DeviceManager has been created. This will change in a future commit
as part of the refactoring so for now always include it but name it with
underscore prefix to indicate it might not always be used.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-02-03 12:28:30 +00:00
Yang Zhong
789a39a2d5 ci: Add MQ support in the test cases
The CI need to add MQ support, and the vcpu number should
be bigger than or equal to queue number.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-02-03 09:49:27 +01:00
Yang Zhong
99da1dff90 vhost-user-blk: Add MQ support in backend
Adding the num_queues parameter for vhost-user-blk backend, which
can enable MQ support in the backend.

This patch has enabled the MQ support from handle_event, and the
vhost-user-backend crate will enable multiple threads to call this
handle_event to handle read/write operations.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-02-03 09:49:27 +01:00
Yang Zhong
1038a07dd6 vhost-user-blk: Device support multiple queues
The previous code only support one queue, and we need
to support MQ in vhost user block device. This patch
can work with SPDK with MQ setting.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2020-02-03 09:49:27 +01:00
dependabot-preview[bot]
839f3a74ff build(deps): bump serde_json from 1.0.45 to 1.0.46
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.45 to 1.0.46.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.45...v1.0.46)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-02-03 07:07:34 +00:00
Samuel Ortiz
652b60320d vfio: Use the vfio-binding FAM wrappers
It's less unsafe and makes the code more readable.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-31 15:09:11 +01:00
Samuel Ortiz
275cb5c92f scripts: dev_cli: Add clean command support
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-31 11:42:20 +00:00
Samuel Ortiz
8676759c38 README: Basic dev_cli documentation
Document it as an alternative way of building the Cloud Hypervisor
binaries.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-31 11:42:20 +00:00
Samuel Ortiz
76087f1235 script: cargo: Improve the cargo tests
We don't need to force the cargo-audit install, we can check if it's
already available instead and install if it's not.

Also, since we now have workspaces properly setup, we can call directly
into cargo fmt and avoid calling into find magic incantation.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-31 11:42:20 +00:00
Samuel Ortiz
db6f894e5e scripts: Add container based development script
The script is a development tool that runs all commands in a dedicated
container. This allows for containerized, isolated and reproducible
builds and CI runs.

The script supports the following command:

* build: Build Cloud Hypervisor binaries (debug and release)
* build-container: Build the container used by the script
* tests: Run unit, cargo and integration tests

$ ./scripts/dev_cli.sh help

Cloud Hypervisor dev_cli.sh
Usage: dev_cli.sh <command> [<command args>]

Available commands:

    build [--debug|--release] [-- [<cargo args>]]
        Build the Cloud Hypervisor binaries.
        --debug               Build the debug binaries. This is the default.
        --release             Build the release binaries.

    tests [--unit|--cargo|--all]
        Run the Cloud Hypervisor tests.
        --unit               Run the unit tests.
        --cargo              Run the cargo tests.
	--integration        Run the integration tests.
        --all                Run all tests.

    build-container [--type]
        Build the Cloud Hypervisor container.
        --dev                Build dev container. This is the default.

    help
        Display this help message.

Fixes: #682
Fixes: #684

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-31 11:42:20 +00:00
dependabot-preview[bot]
31c3685117 build(deps): bump micro_http from e5ef374 to 1eb80f8
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `e5ef374` to `1eb80f8`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](e5ef374c8e...1eb80f8d1b)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-31 07:55:08 +00:00
dependabot-preview[bot]
8dfb79e077 build(deps): bump vm-memory from df6207f to d6229fc
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `df6207f` to `d6229fc`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](df6207f1c0...d6229fc5bd)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-31 07:54:31 +00:00
dependabot-preview[bot]
e99b64097a build(deps): bump regex-syntax from 0.6.13 to 0.6.14
Bumps [regex-syntax](https://github.com/rust-lang/regex) from 0.6.13 to 0.6.14.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-31 00:03:28 +00:00
dependabot-preview[bot]
92b3764553 build(deps): bump openssl-sys from 0.9.53 to 0.9.54
Bumps [openssl-sys](https://github.com/sfackler/rust-openssl) from 0.9.53 to 0.9.54.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-sys-v0.9.53...openssl-sys-v0.9.54)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-30 17:20:30 +00:00
dependabot-preview[bot]
de91c30cd3 build(deps): bump micro_http from 9e68aa4 to e5ef374
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `9e68aa4` to `e5ef374`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](9e68aa4d9d...e5ef374c8e)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-30 17:01:33 +00:00
Sebastien Boeuf
aa4efdd7ec ci: Update kernel related to virtio-iommu
Because of the new set of patches related to virtio-iommu allowing only
for the topology to be described through virtio configuration, this
patch updates the kernel branch and the kernel configuration our CI
relies on.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 10:37:40 +01:00
Sebastien Boeuf
ac01ceddbb vmm: Cleanup list of PCI IDs related to virtual IOMMU
Now that devices attached to the virtual IOMMU are described through
virtio configuration, there is no need for the DeviceManager to store
the list of IDs for all these devices. Instead, things are handled
locally when PCI devices are being added.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 10:37:40 +01:00
Sebastien Boeuf
097cff2d85 vmm: Use virtio topology for virtio-iommu
Instead of relying on the ACPI tables to describe the devices attached
to the virtual IOMMU, let's use the virtio topology, as the ACPI support
is getting deprecated.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 10:37:40 +01:00
Sebastien Boeuf
bac0d1e689 iommu: Implement virtio topology configuration
Based on the new structures previously introduced, the new topology
feature is being fully implemented through this commit. This allows
the description of the devices attached to the virtual IOMMU, which
is why a new function attach_devices() has been introduced. It gives
the virtual IOMMU device the full list of devices which must be attached
to it, letting the device share this information through its virtio
configuration.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 10:37:40 +01:00
Sebastien Boeuf
0c73ff8129 iommu: Add topology structures
The virtio-iommu device defines a new virtio feature allowing the
topology to be discovered fully through virtio configuration.

By topology, it means describing the devices attached to the virtual
IOMMU. This is currently managed through ACPI with IORT and VIOT table,
but this is another way of describing it.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 10:37:40 +01:00
Sebastien Boeuf
db42caef42 vm-virtio: Handle special virtio-pci capability CAP_PCI_CFG
The virtio capability VIRTIO_PCI_CAP_PCI_CFG is exposed through the
device's PCI config space the same way other virtio-pci capabilities
are exposed.

The main and important difference is that this specific capability is
designed as a way for the guest to access virtio capabilities without
mapping the PCI BAR. This is very rarely used, but it can be useful when
it is too early for the guest to be able to map the BARs.

One thing to note, this special feature MUST be implemented, based on
the virtio specification.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 09:25:52 +01:00
Sebastien Boeuf
db9f9b7820 pci: Make self mutable when reading from PCI config space
In order to anticipate the need to support more features related to the
access of a device's PCI config space, this commits changes the self
reference in the function read_config_register() to be mutable.

This also brings some more flexibility for any implementation of the
PciDevice trait.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-30 09:25:52 +01:00
dependabot-preview[bot]
655d9cdb0d build(deps): bump smallvec from 1.1.0 to 1.2.0
Bumps [smallvec](https://github.com/servo/rust-smallvec) from 1.1.0 to 1.2.0.
- [Release notes](https://github.com/servo/rust-smallvec/releases)
- [Commits](https://github.com/servo/rust-smallvec/compare/v1.1.0...v1.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-30 01:54:42 +00:00
dependabot-preview[bot]
74ab468bb4 build(deps): bump backtrace from 0.3.42 to 0.3.43
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.42 to 0.3.43.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.42...0.3.43)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-29 22:59:26 +00:00
dependabot-preview[bot]
1651cc3953 build(deps): bump kvm-ioctls from 0.4.0 to 0.5.0
Bumps [kvm-ioctls](https://github.com/rust-vmm/kvm-ioctls) from 0.4.0 to 0.5.0.
- [Release notes](https://github.com/rust-vmm/kvm-ioctls/releases)
- [Changelog](https://github.com/rust-vmm/kvm-ioctls/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-vmm/kvm-ioctls/compare/v0.4.0...v0.5.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-29 10:22:51 +00:00
Rob Bradford
b4d04bdff6 tests: Add CLI <-> API validation test for --disk changes
Check that the CLI generates the JSON data as expected.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
Rob Bradford
3c8cf0988d docs: Update device model to clarify how to enable vhost-user-block
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
Rob Bradford
75e6762897 vmm: Give deprecation warning for "--vhost-user-blk" syntax
This will be removed in a future release.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
Rob Bradford
969b5ee4e8 vmm: config: Add warning about specifying "wce" without "vhost-user"
Currently configuring WCE is only supported when using vhost-user.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
Rob Bradford
12f4cd951a tests: Use "--disks" for vhost-user-block testing
Use newly unified command line options for testing vhost-user based
block support.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
Rob Bradford
aeeae661fc vmm: Support vhost-user-block via "--disks"
Add a socket and vhost_user parameter to this option so that the same
configuration option can be used for both virtio-block and
vhost-user-block.  For now it is necessary to specify both vhost_user
and socket parameters as auto activation is not yet implemented. The wce
parameter for supporting "Write Cache Enabling" is also added to the
disk configuration.

The original command line parameter is still supported for now and will
be removed in a future release.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-29 08:06:37 +00:00
dependabot-preview[bot]
362942fa6e build(deps): bump micro_http from 53cf1ba to 9e68aa4
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `53cf1ba` to `9e68aa4`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](53cf1bacad...9e68aa4d9d)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-29 07:06:52 +00:00
dependabot-preview[bot]
b5992fe90b build(deps): bump thiserror from 1.0.9 to 1.0.10
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.9 to 1.0.10.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.9...1.0.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-28 20:42:12 +00:00
Rob Bradford
2c6f528c23 vmm: Give deprecation warning for "--vhost-user-net" syntax
This will be removed in a future release.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-28 12:39:26 +00:00
Rob Bradford
f322e924ad docs: Update device model to clarify how to enable vhost-user-net
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-28 12:39:26 +00:00
Rob Bradford
4888dd2e01 tests: Add CLI <-> API validation test for --net changes
Check that the CLI generates the JSON data as expected.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-28 12:39:26 +00:00
Rob Bradford
8f096b8be5 tests: Use "--net" parameter for vhost-user-net setup
Use the newly unified parameter for setting up vhost-user-net based
networking.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-28 12:39:26 +00:00
Rob Bradford
a831aa214c vmm: Support vhost-user-net via "--net"
Add a socket and vhost_user parameter to this option so that the same
configuration option can be used for both virtio-net and vhost-user-net.
For now it is necessary to specify both vhost_user and socket parameters
as auto activation is not yet implemented. The original command line
parameter is still supported for now.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-28 12:39:26 +00:00
Sebastien Boeuf
e155e3690c vm-virtio: Simplify virtio-fs configuration
This commit introduces a clear definition of the virtio-fs
configuration structure, allowing vhost-user-fs device to
rely on it.

This makes the code more readable for developers.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 10:28:14 +00:00
Sebastien Boeuf
8e48fc445f vm-virtio: Simplify virtio-blk configuration
This commit reuses the clear definition of the virtio-blk
configuration structure, allowing both vhost-user-blk and
virtio-blk devices to rely on it.

This makes the code more readable for developers.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 10:28:14 +00:00
Sebastien Boeuf
8946a09afd vm-virtio: Simplify virtio-net configuration
This commit introduces a clear definition of the virtio-net
configuration structure, allowing both vhost-user-net and
virtio-net devices to rely on it.

This makes the code more readable for developers.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 10:28:14 +00:00
Sebastien Boeuf
9efaff73fa ci: Consolidate virtio-blk integration tests
In order to reduce the amount of times VMs are being started through
integration tests, this commit consolidates very similar tests related
to virtio-blk into a single one.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 09:26:53 +01:00
Sebastien Boeuf
a33e8342ee ci: Add integration test for virtio-blk multiqueue support
Just add a new integration test to verify that multiqueue support is
correctly supported and that we can find the right amount of queues in
the guest.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 09:26:53 +01:00
Sebastien Boeuf
f5b53ae4be vm-virtio: Implement multiqueue/multithread support for virtio-blk
This commit improves the existing virtio-blk implementation, allowing
for better I/O performance. The cost for the end user is to accept
allocating more vCPUs to the virtual machine, so that multiple I/O
threads can run in parallel.

One thing to notice, the amount of vCPUs must be egal or superior to the
amount of queues dedicated to the virtio-blk device.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 09:26:53 +01:00
Sebastien Boeuf
08e47ebd4b vmm: Add num_queues and queue_size parameters to virtio-blk
The number of queues and the size of each queue were not configurable.
In anticipation for adding multiqueue support, this commit introduces
some new parameters to let the user decide about the number of queues
and the queue size.

Note that the default values for each of these parameters are identical
to the default values used for vhost-user-blk, that is 1 for the number
of queues and 128 for the queue size.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-28 09:26:53 +01:00
Samuel Ortiz
c4b3ed7223 vm-virtio: Further factorization
The trait bound and non trait bound virtio devices can use the same
inner implementation.
Also, the virtio pausable trait definiton can also be factorized.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
Samuel Ortiz
bce76271c5 vm-virtio: Define a separate macro alias for ctrl queue devices
Now that we have factorized the common virtio pausable implementation,
it's cleaner to have a dedicated macro for control queue devices rather
than overload the macro prototype.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
Samuel Ortiz
2e2b1e4230 vm-virtio: Remove the multiqueue argument from the pausable macro
We only need the ctrl queue one.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
Samuel Ortiz
2cb7ec04a4 vm-virtio: Pausable macro factorization improvements
By adding an internal layer of abstraction (the hidden VirtioPausable
trait), we can factorize the virtio common code.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
Samuel Ortiz
c06a827cbb vm-virtio: Rename epoll_thread to epoll_threads
Now that we unified epoll_thread to potentially be a vector of threads,
it makes sense to make it a plural field.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
Samuel Ortiz
f648f2856d vm-virtio: Make all virtio devices potentially multi-threaded
Although only the block and net virtio devices can actually be multi
threaded (for now), handling them as special cases makes the code more
complex.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-28 07:51:13 +01:00
dependabot-preview[bot]
ac8e4b9cb6 build(deps): bump vm-memory from 8a606cd to df6207f
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `8a606cd` to `df6207f`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](8a606cd838...df6207f1c0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-28 06:49:55 +00:00
dependabot-preview[bot]
45d43f9441 build(deps): bump micro_http from af25399 to 53cf1ba
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `af25399` to `53cf1ba`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](af25399667...53cf1bacad)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-28 06:49:37 +00:00
dependabot-preview[bot]
91747094ae build(deps): bump arrayref from 0.3.5 to 0.3.6
Bumps [arrayref](https://github.com/droundy/arrayref) from 0.3.5 to 0.3.6.
- [Release notes](https://github.com/droundy/arrayref/releases)
- [Commits](https://github.com/droundy/arrayref/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-27 08:56:17 +00:00
dependabot-preview[bot]
90810a9691 build(deps): bump micro_http from 1f931c6 to af25399
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `1f931c6` to `af25399`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](1f931c6649...af25399667)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-27 08:07:15 +00:00
dependabot-preview[bot]
16af54e583 build(deps): bump signal-hook from 0.1.12 to 0.1.13
Bumps [signal-hook](https://github.com/vorner/signal-hook) from 0.1.12 to 0.1.13.
- [Release notes](https://github.com/vorner/signal-hook/releases)
- [Changelog](https://github.com/vorner/signal-hook/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/signal-hook/compare/v0.1.12...v0.1.13)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-26 13:29:47 +00:00
dependabot-preview[bot]
4ff972c329 build(deps): bump ssh2 from 0.6.0 to 0.7.1
Bumps [ssh2](https://github.com/alexcrichton/ssh2-rs) from 0.6.0 to 0.7.1.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/0.6.0...0.7.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-26 01:55:04 +00:00
dependabot-preview[bot]
3508440684 build(deps): bump itoa from 0.4.4 to 0.4.5
Bumps [itoa](https://github.com/dtolnay/itoa) from 0.4.4 to 0.4.5.
- [Release notes](https://github.com/dtolnay/itoa/releases)
- [Commits](https://github.com/dtolnay/itoa/compare/0.4.4...0.4.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-25 00:14:23 +00:00
Sebastien Boeuf
0fa1e2c241 vmm: Handle mapping from devices regions through vm-memory
Devices like virtio-pmem and virtio-fs require some dedicated memory
region to be mapped. The memory mapping from the DeviceManager is being
replaced by the usage of MmapRegion from the vm-memory crate.

The unmap will happen automatically when the MmapRegion will be dropped,
which should happen when the DeviceManager gets dropped.

Fixes #240

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 17:56:49 +01:00
Sebastien Boeuf
694da82691 ci: Make the integration tests fail if images are not valid
When the CI runs in a brand new VM, there's no problem with the validity
of the images as they just got downloaded from the Azure bucket.

In case of a user who runs the CI locally, while doing some debug, he
might provision the images with cloudinit at some point, and later try
to run the CI based on these same images. What happens is that the CI
might randomly fail because the provisioning will not happen again as
it already happened.

This patch ensures the CI to fail early and show an error message to
notify the user about the validity of the images, based on their
sha1sum.

Fixes #112

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 14:02:35 +01:00
dependabot-preview[bot]
0ea6406d5b build(deps): bump vm-memory from beaf215 to 8a606cd
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `beaf215` to `8a606cd`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](beaf215905...8a606cd838)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-24 12:32:16 +00:00
Sebastien Boeuf
148a9ed5ce vmm: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
0a7bcc9a7d vm-virtio: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
4587cc7ffa vhost_user_net: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
f444ef6ccf vfio: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
aa5ae7616e src: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
cf25bd74b0 qcow: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
06396593c9 net_util: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Sebastien Boeuf
f5a52eda2b arch: Fix map_err losing the inner error
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-24 12:42:09 +01:00
Rob Bradford
a34893a402 Revert "vmm: Move MemoryManager from I/O ports to MMIO region"
This reverts commit 03108fb88b.
2020-01-24 12:08:31 +01:00
Rob Bradford
57ed006992 Revert "devices, vmm: Move GED device to MMIO region"
This reverts commit 5e3c62dc6a.
2020-01-24 12:08:31 +01:00
Rob Bradford
6120d0fb1b Revert "vmm: Move CpuManager device to MMIO region"
This reverts commit 980e03fa0a.
2020-01-24 12:08:31 +01:00
dependabot-preview[bot]
6475052692 build(deps): bump micro_http from 1db1bbd to 1f931c6
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `1db1bbd` to `1f931c6`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](1db1bbd40d...1f931c6649)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-24 06:47:58 +00:00
Rob Bradford
980e03fa0a vmm: Move CpuManager device to MMIO region
Move the CpuManager device from the I/O bus to living in an MMIO region.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 16:04:58 +00:00
Rob Bradford
5e3c62dc6a devices, vmm: Move GED device to MMIO region
Move GED device reporting of required device type to scan into an MMIO
region rather than an I/O port.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 16:04:58 +00:00
Rob Bradford
03108fb88b vmm: Move MemoryManager from I/O ports to MMIO region
Rather than have the MemoryManager device sit on the I/O bus allocate
space for MMIO and add it to the MMIO bus.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 16:04:58 +00:00
Sebastien Boeuf
3202e8ac7a vfio: Fix 64bits BAR size reading
The way to get the BAR size is by writing all 1's to the BAR register in
the PCI config space. The mechanism was in place but the parameters were
swapped. The data buffer was provided with the actual offset, while the
offset was provided with the actual all 1's dword. We were effectively
trying to write the real offset at the offset 0xffffffff, which was
failing and resulting in the size being wrong.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-23 13:07:43 +01:00
Rob Bradford
d5d4053795 README.md: Update kernel instructions to use branch
Update the kernel build instructions to use the configuration and branch
that we test and develop against.

Fixes: #521

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 12:56:52 +01:00
Sebastien Boeuf
0042f1de75 ioapic: Rely fully on the InterruptSourceGroup to manage interrupts
This commit relies on the interrupt manager and the resulting interrupt
source group to abstract the knowledge about KVM and how interrupts are
updated and delivered.

This allows the entire "devices" crate to be freed from kvm_ioctls and
kvm_bindings dependencies.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-23 11:20:08 +00:00
Sebastien Boeuf
2dca959084 ioapic: Create the InterruptSourceGroup from InterruptManager
The interrupt manager is passed to the IOAPIC creation, and the IOAPIC
now creates an InterruptSourceGroup for MSI interrupts based on it.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-23 11:20:08 +00:00
Sebastien Boeuf
52800a871a vmm: Create an InterruptManager dedicated to IOAPIC
By introducing a new InterruptManager dedicated to the IOAPIC, we don't
have to solve the chicken and eggs problem about which of the
InterruptManager or the Ioapic should be created first. It's also
totally fine to have two interrupt manager instances as they both share
the same list of GSI routes and the same allocator.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-23 11:20:08 +00:00
Sebastien Boeuf
29e668c302 cargo: Update Cargo.lock
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-23 11:20:08 +00:00
Rob Bradford
cafab9e981 main: Add some command line argument conflicts
Add explicit exclusions with --net-backend from --block-backend (and
vice-versa.) And also with "--kernel" as this is the option for "VM boot" that is never optional.

Ideally we would conflcit the backend arguments against the "vm-group"
however this does not work as it includes some arguments that have a
default value set and thus clap thinks those arguments are always
provided. Conflicting with "--kernel" is thus a reasonable compromise.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
611d13ed1b main: Move logging arguments to their own group
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
8aabb9012d main: Add "--vhost-user-blk" to the "vm-config" group
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
bdb0ad98c4 tests: Use cloud-hypervisor binary for "--{net,block}-backend"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
45fb9187c5 main: Allow main binary to be used as net or block backend
Use newly factorised out function to start the block or net
vhost-user-backend.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
7f73eebbdb vhost_user_block: Split launching backend into its own function
Split the basic launching functionality into its own function in the
newly added vhost_user_block crate.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
9fd187c9fe vhost_user_net: Split launching backend into its own function
Split the basic launching functionality into its own function in the
newly added vhost_user_net crate.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
b851887738 main: Split current VMM running code into it's own function
This prepaees the main binary to start running vhost-user backends.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
1dd2451895 vhost_user_block: Refactor vhost_user_block backend code into a new crate
Extract the majority of the code that provides the vhost-user-block
backend into its own crate and port the binary to use it.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
fb763c4043 vhost_user_net: Refactor vhost_user_net backend code into a new crate
Extract the majority of the code that provides the vhost-user-net
backend into its own crate and port the binary to use it.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
dd82064aba main: Delay converting command line to VM params
Generate the VM params until after the logging has been enabled. This
will make it possible to reuse the logging for vhost backends.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
e12179a3e6 bin: vhost_user_net: Rename "--backend" to "--net-backend"
This will prevent it from conflicting when it is aggregated into the
cloud-hypervisor binary.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
Rob Bradford
3ede2dc53a bin: vhost_user_blk: Rename "--backend" to "--block-backend"
This will prevent it from conflicting when it is aggregated into the
cloud-hypervisor binary.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-23 10:30:06 +00:00
dependabot-preview[bot]
032b8e4c1d build(deps): bump micro_http from ebc15f2 to 1db1bbd
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `ebc15f2` to `1db1bbd`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](ebc15f2eac...1db1bbd40d)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-23 06:44:46 +00:00
dependabot-preview[bot]
204f05fdf1 build(deps): bump serde_json from 1.0.44 to 1.0.45
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.44 to 1.0.45.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.44...v1.0.45)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-23 06:14:06 +00:00
dependabot-preview[bot]
7ee9ecaaf4 build(deps): bump vmm-sys-util from 0.3.1 to 0.4.0
Bumps [vmm-sys-util](https://github.com/rust-vmm/vmm-sys-util) from 0.3.1 to 0.4.0.
- [Release notes](https://github.com/rust-vmm/vmm-sys-util/releases)
- [Changelog](https://github.com/rust-vmm/vmm-sys-util/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-vmm/vmm-sys-util/compare/v0.3.1...v0.4.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-22 14:10:19 +00:00
Qiu Wenbo
2034fc2d84 vmm: Fix LENGTH_OFFSET_HIGH of MemoryManager
Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2020-01-22 12:33:38 +00:00
dependabot-preview[bot]
503e047c3a build(deps): bump redox_users from 0.3.3 to 0.3.4
Bumps redox_users from 0.3.3 to 0.3.4.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-22 07:39:39 +00:00
Sergio Lopez
605fa8307b ci: Add integration test for virtio-blk with 'direct=on'
Previous commit added 'direct' support for virtio-blk to be able to
open files backing disk images with O_DIRECT, so add an integration
test for this new feature.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-21 13:39:45 +00:00
Sergio Lopez
925c862f98 vmm: device_manager: Add 'direct' support for virtio-blk
vhost_user_blk already has it, so it's only fair to give it to
virtio-blk too. Extend DiskConfig with a 'direct' property, honor
it while opening the file backing the disk image, and pass it to
vm_virtio::RawFile.

Fixes #631

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-21 13:39:45 +00:00
Sergio Lopez
2bd90d9263 ci: Add integration test for virtio-blk with 'readonly=on'
Previous commit added 'readonly' support for virtio-blk to be able to
configure read-only devices, so add an integration test for this new
feature.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-21 13:39:45 +00:00
Sergio Lopez
fb79e75afc vmm: device_manager: Add read-only support for virtio-blk
vhost_user_blk already has it, so it's only fair to give it to
virtio-blk too. Extend DiskConfig with a 'readonly' properly, and pass
it to vm_virtio::Block.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-21 13:39:45 +00:00
Sebastien Boeuf
9ac06bf613 ci: Run clippy for each specific feature
The build is run against "--all-features", "pci,acpi", "pci" and "mmio"
separately. The clippy validation must be run against the same set of
features in order to validate the code is correct.

Because of these new checks, this commit includes multiple fixes
related to the errors generated when manually running the checks.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 11:44:40 +01:00
Sebastien Boeuf
e91638e6c5 pci: Cleanup the crate from unneeded types
Both InterruptDelivery and InterruptParameters can be removed from the
pci crate as they are not used anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
99f39291fd pci: Simplify PciDevice trait
There's no need for assign_irq() or assign_msix() functions from the
PciDevice trait, as we can see it's never used anywhere in the codebase.
That's why it's better to remove these methods from the trait, and
slightly adapt the existing code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
a20b383be8 vmm: Always use a reference for InterruptManager
Since the InterruptManager is never stored into any structure, it should
be passed as a reference instead of being cloned.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
bb8cd9eb24 vmm: Use LegacyUserspaceInterruptGroup for acpi device
This commit replaces the way legacy interrupts were handled with the
brand new implementation of the legacy InterruptSourceGroup for KVM.

Additionally, since it removes the last bit relying on the Interrupt
trait, the trait and its implementation can be removed from the
codebase.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
75e22ff34e vmm: Use LegacyUserspaceInterruptGroup for serial device
This commit replaces the way legacy interrupts were handled with the
brand new implementation of the legacy InterruptSourceGroup for KVM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
8d7c4ea334 vmm: Use LegacyUserspaceInterruptGroup for mmio devices
This commit replaces the way legacy interrupts were handled with the
brand new implementation of the legacy InterruptSourceGroup for KVM.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
12657ef59f vmm: Fully implement LegacyUserspaceInterruptGroup
Relying on the previous commits, the legacy interrupt implementation can
be completed. The IOAPIC handler is used to deliver the interrupt that
will be triggered through the trigger() method.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
f70c9937fb vmm: Add ioapic to KvmInterruptManager
By having a reference to the IOAPIC, the KvmInterruptManager is going
to be able to initialize properly the legacy interrupt source group.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
c9ea235a0e vmm: Add LegacyUserspaceInterruptGroup skeleton for legacy interrupts
In order to be able to use the InterruptManager abstraction with
virtio-mmio devices, this commit introduces InterruptSourceGroup's
skeleton for legacy interrupts.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
2aabf58bf5 vmm: Move irq_routes creation to specific MSI use case
When KvmInterruptManager initializes a new InterruptSourceGroup, it's
only for PCI_MSI_IRQ case that it needs to allocate the GSI and create a
new InterruptRoute. That's why this commit moves the general code into
the specific use case.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
d34f31fe7b vmm: Fix KvmInterruptManager when base is different from 0
When the base InterruptIndex is different from 0, the loop allocating
GSI and HashMap entries won't work as expected. The for loop needs to
start from base, but the limit must be base+count so that we allocate
a number of "count" entries.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
Sebastien Boeuf
e73cb1ff80 vmm: Initialize InterruptManager sooner
In order to let the InterruptManager be shared across both PCI and MMIO
devices, this commit moves the initialization earlier in the code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-21 10:44:48 +01:00
dependabot-preview[bot]
9fab9bc645 build(deps): bump micro_http from f77960b to ebc15f2
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `f77960b` to `ebc15f2`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](f77960b81e...ebc15f2eac)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-21 06:54:50 +00:00
dependabot-preview[bot]
9fe6ece262 build(deps): bump redox_users from 0.3.1 to 0.3.3
Bumps redox_users from 0.3.1 to 0.3.3.

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-20 21:47:15 +00:00
dependabot-preview[bot]
c27be842e4 build(deps): bump syn from 1.0.13 to 1.0.14
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.13 to 1.0.14.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.13...1.0.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-20 10:21:53 +00:00
dependabot-preview[bot]
9731be1126 build(deps): bump remain from 0.2.0 to 0.2.1
Bumps [remain](https://github.com/dtolnay/remain) from 0.2.0 to 0.2.1.
- [Release notes](https://github.com/dtolnay/remain/releases)
- [Commits](https://github.com/dtolnay/remain/compare/0.2.0...0.2.1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-20 08:52:00 +00:00
dependabot-preview[bot]
eedfb36c66 build(deps): bump micro_http from 6327290 to f77960b
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `6327290` to `f77960b`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](6327290424...f77960b81e)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-20 07:10:42 +00:00
Rob Bradford
3901a1dd7d vmm: Log an error if VM resize fails
As well as returing an error to the API caller.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-17 23:44:21 +01:00
Rob Bradford
76d9bf2792 vmm: Start memory slots at zero
After refactoring a common function is used to setup these slots and
that function takes care of allocating a new slot so it is not necessary
to reserve the initial region slots.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-17 23:44:21 +01:00
Rob Bradford
0ab22fea2c vmm: Only generate GED event when new DIMM added
Avoid the ACPI scan in the guest OS when no new DIMM is hotplugged.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-17 23:44:21 +01:00
Rob Bradford
211786ab42 vmm: Only generate GED interrupt when the number of vCPUs has changed
Avoid activity in the the guest OS if the number of vCPUs has not
changed.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-17 23:44:21 +01:00
Sebastien Boeuf
8049666eff vm-virtio: Cleanup from kvm_iotcls and kvm_bindings dependencies
Now that KVM specific interrupts are handled through InterruptManager
trait implementation, the vm-virtio crate does not need to rely on
kvm_ioctls and kvm_bindings crates.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
50a4c16d34 pci: Cleanup the crate from kvm_iotcls and kvm_bindings dependencies
Now that KVM specific interrupts are handled through InterruptManager
trait implementation, the pci crate does not need to rely on kvm_ioctls
and kvm_bindings crates.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
4bb12a2d8d interrupt: Reorganize all interrupt management with InterruptManager
Based on all the previous changes, we can at this point replace the
entire interrupt management with the implementation of InterruptManager
and InterruptSourceGroup traits.

By using KvmInterruptManager from the DeviceManager, we can provide both
VirtioPciDevice and VfioPciDevice a way to pick the kind of
InterruptSourceGroup they want to create. Because they choose the type
of interrupt to be MSI/MSI-X, they will be given a MsiInterruptGroup.

Both MsixConfig and MsiConfig are responsible for the update of the GSI
routes, which is why, by passing the MsiInterruptGroup to them, they can
still perform the GSI route management without knowing implementation
details. That's where the InterruptSourceGroup is powerful, as it
provides a generic way to manage interrupt, no matter the type of
interrupt and no matter which hypervisor might be in use.

Once the full replacement has been achieved, both SystemAllocator and
KVM specific dependencies can be removed.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
92082ad439 vmm: Fully implement interrupt traits
After the skeleton of InterruptManager and InterruptSourceGroup traits
have been implemented, this new commit takes care of fully implementing
the content of KvmInterruptManager (InterruptManager trait) and
MsiInterruptGroup (InterruptSourceGroup).

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
0f727127d5 vmm: Implement InterruptSourceGroup and InterruptManager skeleton
This commit introduces an empty implementation of both InterruptManager
and InterruptSourceGroup traits, as a proper basis for further
implementation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
11d4d57c06 vm-device: Introduce InterruptManager and InterruptSourceGroup traits
These new traits are meant to abstract the knowledge about the
hypervisor and the type of interrupt being used from the perspective
of the devices.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
be421dccea vm-virtio: Optimize vhost-user interrupt notification
Thanks to the recently introduced function notifier() in the
VirtioInterrupt trait, all vhost-user devices can now bypass
listening onto an intermediate event fd as they can provide the
actual fd responsible for triggering the interrupt directly to
the vhost-user backend.

In case the notifier does not provide the event fd, the code falls
back onto the creation of an intermediate event fd it needs to listen
to, so that it can trigger the interrupt on behalf of the backend.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
1f029dd2dc vm-virtio: Add notifier to VirtioInterrupt trait
The point is to be able to retrieve directly the event fd related to
the interrupt, as this might optimize the way VirtioDevice devices are
implemented.

For instance, this can be used by vhost-user devices to provide
vhost-user backends directly with the event fd triggering the
interrupt related to a virtqueue.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
c396baca46 vm-virtio: Modify VirtioInterrupt callback into a trait
Callbacks are not the most Rust idiomatic way of programming. The right
way is to use a Trait to provide multiple implementation of the same
interface.

Additionally, a Trait will allow for multiple functions to be defined
while using callbacks means that a new callback must be introduced for
each new function we want to add.

For these two reasons, the current commit modifies the existing
VirtioInterrupt callback into a Trait of the same name.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
ef7d889a79 vfio: Remove unused GSI routing functions
At this point, both MSI and MSI-X handle the KVM GSI routing update,
which means the vfio crate does not have to deal with it anymore.
Therefore, several functions can be removed from the vfio-pci code, as
they are not needed anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
1a4b5ecc75 msi: Set KVM routes from MsiConfig instead of VFIO
Now that MsiConfig has access to both KVM VmFd and the list of GSI
routes, the update of the KVM GSI routes can be directly done from
MsiConfig instead of specifically from the vfio-pci implementation.

By moving the KVM GSI routes update at the MsiConfig level, any PCI
device such as vfio-pci, virtio-pci, or any other emulated PCI device
can benefit from it, without having to implement it on their own.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
f3c3870159 msi: Create MsiConfig to embed MsiCap
The same way we have MsixConfig in charge of managing whatever relates
to MSI-X vectors, we need a MsiConfig structure to manage MSI vectors.
The MsiCap structure is still needed as a low level API, but it is now
part of the MsiConfig which oversees anything related to MSI.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
1e5e02801f msix: Perform interrupt enabling/disabling
In order to factorize one step further, we let MsixConfig perform the
interrupt enabling/disabling. This is done by registering/unregistering
the KVM irq_fds of all GSI routes related to this device.

And now that MsixConfig is in charge of the irq_fds, vfio-pci must rely
on it to retrieve them and provide them to the vfio driver.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
19aeac40c9 msix: Remove the need for interrupt callback
Now that MsixConfig has access to the irq_fd descriptors associated with
each vector, it can directly write to it anytime it needs to trigger an
interrupt.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
3fe362e3bd msix: Set KVM routes from MsixConfig instead of VFIO
Now that MsixConfig has access to both KVM VmFd and the list of GSI
routes, the update of the KVM GSI routes can be directly done from
MsixConfig instead of specifically from the vfio-pci implementation.

By moving the KVM GSI routes update at the MsixConfig level, both
vfio-pci and virtio-pci (or any other emulated PCI device) can benefit
from it, without having to implement it on their own.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
2381f32ae0 msix: Add gsi_msi_routes to MsixConfig
Because MsixConfig will be responsible for updating KVM GSI routes at
some point, it is necessary that it can access the list of routes
contained by gsi_msi_routes.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
9b60fcdc39 msix: Add VmFd to MsixConfig
Because MsixConfig will be responsible for updating the KVM GSI routes
at some point, it must have access to the VmFd to invoke the KVM ioctl
KVM_SET_GSI_ROUTING.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
86c760a0d9 msix: Add SystemAllocator to MsixConfig
The point here is to let MsixConfig take care of the GSI allocation,
which means the SystemAllocator must be passed from the vmm crate all
the way down to the pci crate.

Once this is done, the GSI allocation and irq_fd creation is performed
by MsixConfig directly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
f77d2c2d16 pci: Add some KVM and interrupt utilities to the crate
In order to anticipate the need for both msi.rs and msix.rs to rely on
some KVM utils and InterruptRoute structure to handle the update of the
KVM GSI routes, this commit adds these utilities directly to the pci
crate. So far, these were exclusively used by the vfio crate, which is
why there were located there.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sebastien Boeuf
f5704d32b3 vmm: Move gsi_msi_routes creation to be shared across all PCI devices
Because we will need to share the same list of GSI routes across
multiple PCI devices (virtio-pci, VFIO), this commit moves the creation
of such list to a higher level location in the code.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-17 23:43:45 +01:00
Sergio Lopez
ed5459f268 ci: Add integration test for vhost_user_blk with 'direct'
This test is a variant of test_boot_vhost_user_blk(), named
test_boot_vhost_user_blk_direct(), that instances the vhost-user-blk
daemon with 'direct=true', to test this recently introduced feature
for opening files with O_DIRECT.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-17 17:28:44 +00:00
Sergio Lopez
e0a8da2f46 vhost_user_blk: Add missing WCE property support
Add missing WCE (write-cache enable) property support. This not only
an enhancement, but also a fix for a bug.

Right now, when vhost_user_blk uses a qcow2 image, it doesn't write
the QCOW2 metadata until the guest explicitly requests a flush. In
practice, this is equivalent to the write back semantic.

Without WCE, the guest assumes write through for the virtio_blk
device, and doesn't send those flush requests. Adding support for WCE,
and enabling it by default, we ensure the guest does send said
requests.

Supporting "WCE = false" would require updating our qcow2
implementation to ensure that, when required, it honors the write
through semantics by not deferring the updates to QCOW2 metadata.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-17 17:28:44 +00:00
Sergio Lopez
c7e9056c1e vhost_user_blk: implement support for direct (O_DIRECT) mode
Add support for opening the disk images with O_DIRECT. This allows
bypassing the host's file system cache, which is useful to avoid
polluting its cache and for better data integrity.

This mode of operation can be enabled by adding the "direct=<bool>"
parameter to the "backend" argument:

./target/debug/vhost_user_blk --backend image=test.raw,sock=/tmp/vhostblk,direct=true

The "direct" parameter defaults to "false", to preserve the original
behavior.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-17 17:28:44 +00:00
Sergio Lopez
a14aee9213 qcow: Use RawFile as backend instead of File
Use RawFile as backend instead of File. This allows us to abstract
the access to the actual image with a specialized layer, so we have a
place where we can deal with the low-level peculiarities.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-17 17:28:44 +00:00
Sergio Lopez
c5a656c9dc vm-virtio: block: Add support for alignment restrictions
Doing I/O on an image opened with O_DIRECT requires to adhere to
certain restrictions, requiring the following elements to be aligned:

 - Address of the source/destination memory buffer.
 - File offset.
 - Length of the data to be read/written.

The actual alignment value depends on various elements, and according
to open(2) "(...) there is currently no filesystem-independent
interface for an application to discover these restrictions (...)".

To discover such value, we iterate through a list of alignments
(currently, 512 and 4096) calling pread() with each one and checking
if the operation succeeded.

We also extend RawFile so it can be used as a backend for QcowFile,
so the later can be easily adapted to support O_DIRECT too.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2020-01-17 17:28:44 +00:00
Cathy Zhang
e483cde1bb docs: Update networking.md with multiple queue support
Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
973eb16ae9 src: Add multiple queue checking in vhost-user-net integration test
Update queue number with 4 to verify if vhost-user-net device
and backend could work well with multiple queue.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
4885dc0ed4 src: Update test_valid_vm_config_net with new option for virtio-net
There are two new options num_queues and queue_size defined for
virtio-net, add them in test_valid_vm_config_net which is used
to validate that both the CLI and the OpenAPI will generate the
same configuration.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
652e7b9b8a vm-virtio: Implement multiple queue support for net devices
Update the common part in net_util.rs under vm-virtio to add mq
support, meanwhile enable mq for virtio-net device, vhost-user-net
device and vhost-user-net backend. Multiple threads will be created,
one thread will be responsible to handle one queue pair separately.
To gain the better performance, it requires to have the same amount
of vcpus as queue pair numbers defined for the net device, due to
the cpu affinity.

Multiple thread support is not added for vhost-user-net backend
currently, it will be added in future.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
404316eea1 vmm: Add multiple queue option and update config for virtio-net device
Add num_queues and queue_size for virtio-net device to make them configurable,
while add the associated options in command line.

Update cloud-hypervisor.yaml with the new options for NetConfig.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
4ab88a8173 net_util: Add multiple queue support for tap
Add support to allow VMMs to open the same tap device many times, it will
create multiple file descriptors meanwhile.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
cf7e0cdf95 vm-virtio: Add multiple queue handling with control queue
Current guest kernel will check the oneline cpu count, in principle,
if the online cpu count is not smaller than the number of queue pairs
VMM reported, the net packets could be put/get to all the virtqueues,
otherwise, only the number of queue pairs that match the oneline cpu
count will have packets work with. guest kernel will send command
through control queue to tell VMMs the actual queue pair numbers which
it could currently play with. Add mq process in control queue handling
to get the queue pair number, VMM will verify if it is in a valid range,
nothing else but this.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
709f7fe607 vm-virtio: Implement control queue support for net devices
While feature VIRTIO_NET_F_CTRL_VQ is negotiated, control queue
will exits besides the Tx/Rx virtqueues, an epoll handler should
be started to monitor and handle the control queue event.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
d38787c578 vm-virtio: Add control queue support in net_util.rs
As virtio spec 1.1 said, the driver uses the control queue
to send commands to manipulate various features of the devices,
such as VIRTIO_NET_F_MQ which is required by multiple queue
support. Here add the control queue handling process.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
1ae7deb393 vm-virtio: Implement refactor for net devices and backend
Since the common parts are put into net_util.rs under vm-virtio,
refactoring code for virtio-net device, vhost-user-net device
and backend to shrink the code size and improve readability
meanwhile.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
6ae2597d19 vm-virtio: Create new module to abstract common parts for net devices
There are some common logic shared among virtio-net device, vhost-user-net
device and vhost-user-net backend, abstract those parts into net_util.rs
to improve code maintainability and readability.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
Cathy Zhang
3485e89080 vm-virtio: Stop delivering interrupt while NO_VECTOR
According to virtio spec, for used buffer notifications, if
MSI-X capability is enabled, and queue msix vector is
VIRTIO_MSI_NO_VECTOR 0xffff, the device must not deliver an
interrupt for that virtqueue.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2020-01-17 12:06:19 +01:00
dependabot-preview[bot]
1324aa451f build(deps): bump proc-macro2 from 1.0.7 to 1.0.8
Bumps [proc-macro2](https://github.com/alexcrichton/proc-macro2) from 1.0.7 to 1.0.8.
- [Release notes](https://github.com/alexcrichton/proc-macro2/releases)
- [Commits](https://github.com/alexcrichton/proc-macro2/compare/1.0.7...1.0.8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-17 06:58:27 +00:00
dependabot-preview[bot]
dcb6d02b98 build(deps): bump micro_http from db75e88 to 6327290
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `db75e88` to `6327290`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](db75e88e9e...6327290424)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-17 06:58:10 +00:00
dependabot-preview[bot]
cde2c4449b build(deps): bump backtrace from 0.3.41 to 0.3.42
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.41 to 0.3.42.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.41...0.3.42)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-16 10:59:19 +00:00
dependabot-preview[bot]
d8adf6a6d7 build(deps): bump micro_http from 52e21d0 to db75e88
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `52e21d0` to `db75e88`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](52e21d0f9e...db75e88e9e)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-16 06:38:18 +00:00
Rob Bradford
14041e97e7 docs: Add memory resizing documentation
Add documentation for memory resizing.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
32506dadfc docs: Document CPU unplug
This newly added feature wasn't yet documented.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
8b500d7873 deps: Bump vm-memory and linux-loader version
The function GuestMemory::end_addr() has been renamed to last_addr()

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
7310ab6fa7 devices, vmm: Use a bit field for ACPI GED interrupt type
Use independent bits for storing whether there is a CPU or memory device
changed when reporting changes via ACPI GED interrupt. This prevents a
later notification squashing an earlier one and ensure that hotplugging
both CPU and memory at the same time succeeds.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
d2d1248342 tests: Add test combining memory and vCPU hotplug
Test resizing with both optional parameters set in the VmResize API
works.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
2073007214 tests: Add integration test for RAM hotplug
Reuse the existing infrastructure for CPU hotplug and add a new test for
memory hotplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
351058ab0f resources: Add memory hotplug support to the kernel configuration
Add the config option for enabling memory hotplug to our recommended
kenrel configuration.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
28c6652e57 vmm: Upon VmResize attempt to hotplug the memory
If a new amount of RAM is requested in the VmResize command try and
hotplug if it an increase (MemoryManager::Resize() silently ignores
decreases.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
4e414f0d84 vmm: device_manager: Scan memory devices upon GED interrupt
If there is a GED interrupt and the field indicates that the memory
device has changed triggers a scan of the memory devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
284d5e011a vmm: Add memory hotplug ACPI entries to DSDT
Generate and expose the DSDT table entries required to support memory
hotplug. The AML methods call into the MemoryManager via I/O ports
exposed as fields.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
8ecf736982 vmm: device_manager: Add the MemoryManager to the I/O bus
Now that the MemoryManager has I/O port functionality it needs to be
exposed on the I/O bus.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
1218765df2 vmm: memory_manager: Expose the slots details via an I/O port
Expose the details of hotplug RAM slots via an I/O port. This will be
consumed by the ACPI DSDT tables to report the hotplug memory details to
the guest.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
9880a2aba9 vmm: memory_manger: Add support for adding new memory to the VM
Add a "resize()" method on MemoryManager which will create a new memory
allocation based on the difference between the desired RAM amount and
the amount already in use. After allocating the added RAM using the same
backing method as the boot RAM store the details in a vector and update
the KVM map and create a new GuestMemoryMmap and replace all the users.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
82fce5a4e2 vmm: Add support for resizing the memory used by the VM
For now the new memory size is only used after a reboot but support for
hotplugging memory will be added in a later commit.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
78dcb1862c vmm: device_manager: Store the type of notification in a local value
When the value is read from the I/O port via the ACPI AML functions to
determine what has been triggered the notifiction value is reset
preventing a second read from exposing the value. If we need support
multiple types of GED notification (such as memory hotplug) then we
should avoid reading the value multiple times.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
5da7c63127 acpi_tables: aml: Add support for creating fields
These fields allow you to expose the component part of an existing
buffer, such as a resource template as a new field which is required to
expose the memory CRS details.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
f5137e84bb vmm, main: Add optional "hotplug_size" to --mem
This specifies how much address space should be reserved for hotplugging
of RAM. This space is reserved by adding move the start of the device
area by the desired amount.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
f1b6657833 vmm: Make desired vCPUs optional in resize command
In order to be able to support resizing either vCPUs or memory or both
make the fields in the resize command optional.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
72b9e920a3 vmm: memory_manager: Further refactor memory region allocation
This allows the memory regions to be allocated later which is necessary
for hotplug memory.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
Rob Bradford
1af11a7c92 vmm: memory_manager: Refactor GuestMemoryMmap construction
Make the GuestMemoryMmap from a Vec<Arc<GuestRegionMmap>> by using this
method we can persist a set of regions in the MemoryManager and then
extend this set with a newly created region. Ultimately that will allow
the hotplug of memory.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-15 20:21:22 +01:00
dependabot-preview[bot]
281b99af0a build(deps): bump micro_http from 803c8fa to 52e21d0
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `803c8fa` to `52e21d0`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](803c8fae14...52e21d0f9e)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-15 07:26:59 +00:00
dependabot-preview[bot]
0acabcdd27 build(deps): bump libssh2-sys from 0.2.13 to 0.2.14
Bumps [libssh2-sys](https://github.com/alexcrichton/ssh2-rs) from 0.2.13 to 0.2.14.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/libssh2-sys-0.2.13...libssh2-sys-0.2.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-15 07:26:40 +00:00
dependabot-preview[bot]
85f43c7026 build(deps): bump micro_http from edbff4c to 803c8fa
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `edbff4c` to `803c8fa`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](edbff4ce62...803c8fae14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-14 06:42:28 +00:00
Samuel Ortiz
5788d36583 vmm: Do not create virtio devices when missing a transport
If neither PCI or MMIO are built in, we should not bother creating any
virtio devices at all.
When building a minimal VMM made of a kernel with an initramfs and a
serial console, the RNG virtio device is still created even though there
is no way it can ever get probed.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-14 07:42:09 +01:00
dependabot-preview[bot]
41895d7df1 build(deps): bump rand from 0.7.2 to 0.7.3
Bumps [rand](https://github.com/rust-random/rand) from 0.7.2 to 0.7.3.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-13 16:24:25 +00:00
dependabot-preview[bot]
85d155543e build(deps): bump micro_http from 0987cdc to edbff4c
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `0987cdc` to `edbff4c`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](0987cdc52b...edbff4ce62)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-13 16:24:25 +00:00
dependabot-preview[bot]
3430e20f64 build(deps): bump memchr from 2.2.1 to 2.3.0
Bumps [memchr](https://github.com/BurntSushi/rust-memchr) from 2.2.1 to 2.3.0.
- [Release notes](https://github.com/BurntSushi/rust-memchr/releases)
- [Commits](https://github.com/BurntSushi/rust-memchr/compare/2.2.1...2.3.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-13 16:24:25 +00:00
dependabot-preview[bot]
7d853241ad build(deps): bump constant_time_eq from 0.1.4 to 0.1.5
Bumps [constant_time_eq](https://github.com/cesarb/constant_time_eq) from 0.1.4 to 0.1.5.
- [Release notes](https://github.com/cesarb/constant_time_eq/releases)
- [Commits](https://github.com/cesarb/constant_time_eq/compare/0.1.4...0.1.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-13 16:24:25 +00:00
dependabot-preview[bot]
fc8bfe07f3 build(deps): bump backtrace from 0.3.40 to 0.3.41
Bumps [backtrace](https://github.com/rust-lang/backtrace-rs) from 0.3.40 to 0.3.41.
- [Release notes](https://github.com/rust-lang/backtrace-rs/releases)
- [Commits](https://github.com/rust-lang/backtrace-rs/compare/0.3.40...0.3.41)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-13 16:24:25 +00:00
Sebastien Boeuf
fa34fae55f ci: Move to personal branch for virtiofsd
The current virtio-fs-dev branch from the official repo is breaking the
build on our Azure VMs because the glibc wrapper for renameat2() syscall
does not exist. This branch fixes the problem while the maintainers are
fixing the issue upstream.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-13 15:55:34 +00:00
Sebastien Boeuf
f427d94422 virtio-fs: Update virtiofs daemon parameters
With the latest version of virtiofsd, some changes have been made
to the socket path parameter. This needs to be updated in the cloud
hypervisor codebase, so that our CI keeps running correctly.

Fixes #611

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-13 15:55:34 +00:00
dependabot-preview[bot]
345c922cb9 build(deps): bump micro_http from 0bfaf39 to 0987cdc
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `0bfaf39` to `0987cdc`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](0bfaf39af1...0987cdc52b)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-10 07:18:48 +00:00
dependabot-preview[bot]
b38beb606f build(deps): bump regex-syntax from 0.6.12 to 0.6.13
Bumps [regex-syntax](https://github.com/rust-lang/regex) from 0.6.12 to 0.6.13.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/regex-syntax-0.6.12...regex-syntax-0.6.13)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 20:55:02 +00:00
Samuel Ortiz
c2f6dfce88 vm-virtio: Fix VirtioDeviceType traits
The From and Display traits were not handling some of the enum
definitions. We no longer have a default case for Display so any future
misses will fail at build time.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2020-01-09 15:29:09 +01:00
dependabot-preview[bot]
9d775a140f build(deps): bump pnet from 0.23.0 to 0.25.0
Bumps [pnet](https://github.com/libpnet/libpnet) from 0.23.0 to 0.25.0.
- [Release notes](https://github.com/libpnet/libpnet/releases)
- [Commits](https://github.com/libpnet/libpnet/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 08:07:19 +00:00
dependabot-preview[bot]
70d80cc064 build(deps): bump pnet_sys from 0.23.0 to 0.23.1
Bumps [pnet_sys](https://github.com/libpnet/libpnet) from 0.23.0 to 0.23.1.
- [Release notes](https://github.com/libpnet/libpnet/releases)
- [Commits](https://github.com/libpnet/libpnet/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 07:33:18 +00:00
dependabot-preview[bot]
f493d434ba build(deps): bump vm-memory from 467eda6 to 218afdd
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `467eda6` to `218afdd`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](467eda62ae...218afddd4f)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 07:08:08 +00:00
dependabot-preview[bot]
2500d0aaac build(deps): bump micro_http from 2953365 to 0bfaf39
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `2953365` to `0bfaf39`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](29533658e5...0bfaf39af1)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 07:07:55 +00:00
dependabot-preview[bot]
279c4f91a3 build(deps): bump pnet_macros from 0.23.0 to 0.25.0
Bumps [pnet_macros](https://github.com/libpnet/libpnet) from 0.23.0 to 0.25.0.
- [Release notes](https://github.com/libpnet/libpnet/releases)
- [Commits](https://github.com/libpnet/libpnet/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-09 07:05:53 +00:00
Sebastien Boeuf
24cf15d2b2 vfio: Don't throw an error if a region cannot be found
Everytime we use VFIO with cloud-hypervisor, we get the following error:

ERROR:vfio/src/vfio_device.rs:440 -- Could not get region #8 info

But this is not an error per se, and should be considered as a simple
warning.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-09 08:05:35 +01:00
Sebastien Boeuf
c2ae380503 pci: Refine detection of BAR reprogramming
The current code was always considering 0xffffffff being written to the
register as a sign it was expecting to get the size, hence the BAR
reprogramming detection was stating this case was not a reprogramming
case.

Problem is, if the value 0xffffffff is directed at a 64bits BAR, this
might be the high or low part of a 64bits address which is meant to be
the new address of the BAR, which means we would miss the detection of
the BAR being reprogrammed here.

This commit improves the code using finer granularity checks in order to
detect this corner case correctly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-09 08:05:35 +01:00
Sebastien Boeuf
07bad79fd7 pci: Fix detection of expansion ROM BAR reprogramming
The expansion ROM BAR reprogramming was being triggered for the wrong
reason and was causing the following error to be reported:

ERROR:pci/src/bus.rs:207 -- Failed moving device BAR: failed allocating
new 32 bits MMIO range

Following the PCI specification, here is what is defined:

Device independent configuration software can determine how much address
space the device requires by writing a value of all 1's to the address
portion of the register and then reading the value back.

This means we cannot expect 0xffffffff to be written, as the address
portion corresponds to the bits 31-11. That's why whenever the size of
this special BAR is being asked for, the value being written is
0xfffff800.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-09 08:05:35 +01:00
dependabot-preview[bot]
0d2e38db25 build(deps): bump cc from 1.0.49 to 1.0.50
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.49 to 1.0.50.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.49...1.0.50)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-08 17:00:07 +00:00
Sebastien Boeuf
38468d3d9b vm-virtio: Improve virtio-console input processing
The way the code is currently implemented, only by writing to STDIN a
user can trigger some input to reach the VM through virtio-console. But
in case, there were not enough virtio descriptors to process what was
retrieved from STDIN, the remaining bits would be transferred only if
STDIN was triggered again. The missing part is that when some
descriptors are made available from the guest, the virtio-console device
should try to send any possible remaining bits.

By triggering the function process_input_queue() whenever the guest
notifies the host that some new descriptors are ready for the receive
queue, this patch allows to fill the implementation void that was left.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 15:37:02 +01:00
Sebastien Boeuf
e4c3401a33 vm-virtio: Don't waste a descriptor if not filled
In case the virtio descriptor is pulled out of the Queue iterator, it
is important to fill it and tag it as used. This is already done from
the successful code path, but in case there's an error during the
filling, we should make sure to put the descriptor back in the list of
available descriptors. This way, when the error occurs, we don't loose
a descriptor, and it could be used later.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 15:37:02 +01:00
Sebastien Boeuf
7a3e6caca4 vm-virtio: Simplify virtio-console input processing
The existing code was a bit too complex and it was introducing a bug
when trying to paste long lines directly to the console. By simplifying
the code, and by doing proper usage of the drain() function, the bug is
fixed by this commit.

Here is the similar output one could have gotten from time to time, when
pasting important amounts of bytes:

ERROR:vm-virtio/src/console.rs:104 -- Failed to write slice:
InvalidGuestAddress(GuestAddress(1040617472))

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 15:37:02 +01:00
Sebastien Boeuf
ad223f2b50 fs: Use cache=none by default
The cache= option from the virtiofsd backend is meant to be used
depending on how the user wants to use the guest page cache. For most
use cases, we want to bypass the guest page cache to reduce the guest
memory footprint, which is why "cache=none" should be the default.

"cache=always" is the other option when the user wants to do something
specific by using the guest page cache, but should not be the default
anymore.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
84445aae93 vm-virtio: Implement multi-mapping for virtio-fs
The virtio-fs messages coming from the slave can contain multiple
mappings (up to 8) through one single request. By implementing such
feature, the virtio-fs implementation of cloud-hypervisor is optimal and
fully functional as it resolves a bug that was seen when running fio
testing without this patch.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
143471b739 fs: Update mount command to mount virtiofs filesystem
With latest kernel, virtio-fs mount command has been simplified, and
this needs to be applied everywhere in our tests and documentation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
e1822cfdad vm-virtio: Implement VIRTIO_IOMMU_F_PROBE feature
By implementing this virtio feature, we let the virtio-iommu driver call
the device backend so that it can probe each device that gets attached.

Through this probing, the device provides a range of reserved memory
related to MSI. This is mandatory for x86 architecture as we want to
avoid the default MSI range assigned by the virtio-iommu driver if no
range is provided at all. The default range is 0x8000000-0x80FFFFF but
it only makes sense for ARM architectures.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
ae6f27277b acpi: Introduce VIOT to support latest virtio-iommu implementation
Because virtio-iommu is still evolving (as it's only partly upstream),
some pieces like the ACPI declaration of the different nodes and devices
attached to the virtual IOMMU are changing.

This patch introduces a new ACPI table called VIOT, standing as the high
level table overseeing the IORT table and associated subtables.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
4dbb33a1fa resources: Update kernel config
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
Sebastien Boeuf
c56af8daeb ci: Use a temporary kernel branch before we override the current one
In order to validate the newly created virtio-fs-virtio-iommu-5.5-rc1
branch is not breaking anything in our CI, we must try it as a temporary
branch before we can override virtio-fs-virtio-iommu.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2020-01-08 09:27:07 +01:00
dependabot-preview[bot]
d756844096 build(deps): bump getrandom from 0.1.13 to 0.1.14
Bumps [getrandom](https://github.com/rust-random/getrandom) from 0.1.13 to 0.1.14.
- [Release notes](https://github.com/rust-random/getrandom/releases)
- [Changelog](https://github.com/rust-random/getrandom/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/getrandom/compare/v0.1.13...v0.1.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-07 13:54:27 +00:00
dependabot-preview[bot]
9d3f656572 build(deps): bump cc from 1.0.48 to 1.0.49
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.48 to 1.0.49.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.48...1.0.49)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-07 08:14:13 +00:00
dependabot-preview[bot]
f59665e8aa build(deps): bump epoll from 4.0.1 to 4.1.0
Bumps [epoll](https://github.com/nathansizemore/epoll) from 4.0.1 to 4.1.0.
- [Release notes](https://github.com/nathansizemore/epoll/releases)
- [Commits](https://github.com/nathansizemore/epoll/compare/4.0.1...4.1.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-07 07:39:59 +00:00
dependabot-preview[bot]
9482ded365 build(deps): bump micro_http from aec25f9 to 2953365
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `aec25f9` to `2953365`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](aec25f9e5a...29533658e5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-07 07:08:03 +00:00
dependabot-preview[bot]
e4ea60dd96 build(deps): bump rand from 0.7.0 to 0.7.2
Bumps [rand](https://github.com/rust-random/rand) from 0.7.0 to 0.7.2.
- [Release notes](https://github.com/rust-random/rand/releases)
- [Changelog](https://github.com/rust-random/rand/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/rand/compare/0.7.0...0.7.2)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 08:32:44 +00:00
dependabot-preview[bot]
44dd056647 build(deps): bump remain from 0.1.5 to 0.2.0
Bumps [remain](https://github.com/dtolnay/remain) from 0.1.5 to 0.2.0.
- [Release notes](https://github.com/dtolnay/remain/releases)
- [Commits](https://github.com/dtolnay/remain/compare/0.1.5...0.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 08:26:02 +00:00
dependabot-preview[bot]
091c9d9f93 build(deps): bump pnet from 0.22.0 to 0.23.0
Bumps [pnet](https://github.com/libpnet/libpnet) from 0.22.0 to 0.23.0.
- [Release notes](https://github.com/libpnet/libpnet/releases)
- [Commits](https://github.com/libpnet/libpnet/commits/v0.23.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 07:53:56 +00:00
dependabot-preview[bot]
d8c3912a18 build(deps): bump micro_http from be97831 to aec25f9
Bumps [micro_http](https://github.com/firecracker-microvm/firecracker) from `be97831` to `aec25f9`.
- [Release notes](https://github.com/firecracker-microvm/firecracker/releases)
- [Commits](be978312ea...aec25f9e5a)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 07:26:24 +00:00
dependabot-preview[bot]
1a28f64d5d build(deps): bump atty from 0.2.13 to 0.2.14
Bumps [atty](https://github.com/softprops/atty) from 0.2.13 to 0.2.14.
- [Release notes](https://github.com/softprops/atty/releases)
- [Changelog](https://github.com/softprops/atty/blob/master/CHANGELOG.md)
- [Commits](https://github.com/softprops/atty/compare/0.2.13...0.2.14)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 07:26:09 +00:00
dependabot-preview[bot]
8f6cbf849a build(deps): bump vm-memory from 291dc2e to 467eda6
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `291dc2e` to `467eda6`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](291dc2e236...467eda62ae)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-06 07:25:53 +00:00
dependabot-preview[bot]
5a0d01ca13 build(deps): bump blake2b_simd from 0.5.9 to 0.5.10
Bumps [blake2b_simd](https://github.com/oconnor663/blake2_simd) from 0.5.9 to 0.5.10.
- [Release notes](https://github.com/oconnor663/blake2_simd/releases)
- [Commits](https://github.com/oconnor663/blake2_simd/compare/0.5.9...0.5.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-05 09:03:50 +00:00
dependabot-preview[bot]
38c0d328c2 build(deps): bump syn from 1.0.12 to 1.0.13
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.12 to 1.0.13.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.12...1.0.13)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-03 17:50:44 +00:00
Rob Bradford
134bcd84e6 tests: Use the workspace to unit test all the crates
Make all the crates members of the workspace so that "cargo test
--workspace" will find them all and test them with the features enabled
that we use.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-03 10:20:53 +01:00
Rob Bradford
b6f6772df4 vhost_rs: Fix compile failure in tests
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-03 10:20:53 +01:00
Rob Bradford
cf1983c70e vhost_rs: Mark some broken tests ignored
If we use the workspace based testing methodology then we start testing
some code inside vhost_rs that is broken.

See #576

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-03 10:20:53 +01:00
Rob Bradford
32a39f9b95 vm-virtio: Fix broken write_base_regs() unit test
The following commit broke this unit test:

"""
vmm: Convert virtio devices to Arc<Mutex<T>>

Migratable devices can be virtio or legacy devices.
In any case, they can potentially be tracked through one of the IO bus
as an Arc<Mutex<dyn BusDevice>>. In order for the DeviceManager to also
keep track of such devices as Migratable trait objects, they must be
shared as mutable atomic references, i.e. Arc<Mutex<T>>. That forces all
Migratable objects to be tracked as Arc<Mutex<dyn Migratable>>.

Virtio devices are typically migratable, and thus for them to be
referenced by the DeviceManager, they now should be built as
Arc<Mutex<VirtioDevice>>.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
"""

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-03 10:20:53 +01:00
Rob Bradford
b2589d4f3f vm-virtio, vmm, vfio: Store GuestMemoryMmap in an Arc<ArcSwap<T>>
This allows us to change the memory map that is being used by the
devices via an atomic swap (by replacing the map with another one). The
ArcSwap provides the mechanism for atomically swapping from to another
whilst still giving good read performace. It is inside an Arc so that we
can use a single ArcSwap for all users.

Not covered by this change is replacing the GuestMemoryMmap itself.

This change also removes some vertical whitespace from use blocks in the
files that this commit also changed. Vertical whitespace was being used
inconsistently and broke rustfmt's behaviour of ordering the imports as
it would only do it within the block.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2020-01-02 13:20:11 +00:00
dependabot-preview[bot]
5c0bb38a65 build(deps): bump vm-memory from 09c119f to 291dc2e
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `09c119f` to `291dc2e`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](09c119f742...291dc2e236)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-02 08:03:05 +00:00
dependabot-preview[bot]
b9971302be build(deps): bump syn from 1.0.11 to 1.0.12
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.11 to 1.0.12.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.11...1.0.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2020-01-02 08:02:34 +00:00
dependabot-preview[bot]
fda8a04ec2 build(deps): bump vm-memory from 3ef06be to 09c119f
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `3ef06be` to `09c119f`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](3ef06beaea...09c119f742)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-26 07:07:41 +00:00
dependabot-preview[bot]
34e35c9ae0 build(deps): bump anyhow from 1.0.25 to 1.0.26
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.25 to 1.0.26.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.25...1.0.26)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-24 07:00:35 +00:00
dependabot-preview[bot]
95352db1e5 build(deps): bump vm-memory from ec69de9 to 3ef06be
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `ec69de9` to `3ef06be`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](ec69de9c07...3ef06beaea)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-24 07:00:00 +00:00
Rob Bradford
a551398135 vmm: device_manager: Use MemoryManager to create KVM mapping
Use the newly exported funtionality to reduce the amount of duplicated
code.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-23 10:25:40 +00:00
Rob Bradford
962dec2913 vmm: memory_manager: Refactor KVM userspace mapping creation
This function will be useful for other parts of the VMM that also
estabilish their own mappings.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-23 10:25:40 +00:00
Rob Bradford
7df88793a0 vmm: device_manager: Get device range from MemoryManager
This removes the duplication of these values.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-23 10:25:40 +00:00
Rob Bradford
61cfe3e72d vmm: Obtain sequential KVM memory slot numbers from MemoryManager
This removes the need to handle a mutable integer and also centralises
the allocation of these slot numbers.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-23 10:25:40 +00:00
Rob Bradford
260cebb8cf vmm: Introduce MemoryManager
The memory manager is responsible for setting up the guest memory and in
the long term will also handle addition of guest memory.

In this commit move code for creating the backing memory and populating
the allocator into the new implementation trying to make as minimal
changes to other code as possible.

Follow on commits will further reduce some of the duplicated code.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-23 10:25:40 +00:00
dependabot-preview[bot]
bcfe546ea2 build(deps): bump vm-memory from bb29ec8 to ec69de9
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `bb29ec8` to `ec69de9`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](bb29ec8713...ec69de9c07)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-23 07:11:13 +00:00
Sebastien Boeuf
f668603694 ci: Fix flaky test_memory_mergeable_on test
Because we don't always reach the expected footprint improvements with
KSM, let's review the numbers. By reducing the expectations and
increasing the amount of pages to scan, this should stabilize the CI.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-20 13:44:22 +00:00
Rob Bradford
1e3fd2f6a5 tests: Remove many redundant clones
As found by updated clippy:

e.g:

error: redundant clone
    --> src/main.rs:1590:57
     |
1590 |             let mut osdisk_raw_base_path = workload_path.clone();
     |                                                         ^^^^^^^^ help: remove this
     |
     = note: `-D clippy::redundant-clone` implied by `-D warnings`

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Rob Bradford
d5682cd306 vmm: device_manager: Rewrite if chain using match
To reflect updated clippy rules:

error: `if` chain can be rewritten with `match`
    --> vmm/src/device_manager.rs:1508:25
     |
1508 | /                         if ret > 0 {
1509 | |                             debug!("MSI message successfully delivered");
1510 | |                         } else if ret == 0 {
1511 | |                             warn!("failed to deliver MSI message, blocked by guest");
1512 | |                         }
     | |_________________________^
     |
     = note: `-D clippy::comparison-chain` implied by `-D warnings`
     = help: Consider rewriting the `if` chain to use `cmp` and `match`.
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Rob Bradford
21b88c3ea0 vmm: cpu: Rewrite if chain using match
Address updated clippy error:

error: `if` chain can be rewritten with `match`
   --> vmm/src/cpu.rs:668:9
    |
668 | /         if desired_vcpus > self.present_vcpus() {
669 | |             self.activate_vcpus(desired_vcpus, None)?;
670 | |         } else if desired_vcpus < self.present_vcpus() {
671 | |             self.mark_vcpus_for_removal(desired_vcpus)?;
672 | |         }
    | |_________^
    |
    = note: `-D clippy::comparison-chain` implied by `-D warnings`
    = help: Consider rewriting the `if` chain to use `cmp` and `match`.
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#comparison_chain

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Rob Bradford
e25a47b32c vmm: device_manager: Remove redundant clones
Address updated clippy errors:

error: redundant clone
   --> vmm/src/device_manager.rs:699:32
    |
699 |             .insert(acpi_device.clone(), 0x3c0, 0x4)
    |                                ^^^^^^^^ help: remove this
    |
    = note: `-D clippy::redundant-clone` implied by `-D warnings`
note: this value is dropped without further use
   --> vmm/src/device_manager.rs:699:21
    |
699 |             .insert(acpi_device.clone(), 0x3c0, 0x4)
    |                     ^^^^^^^^^^^
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

error: redundant clone
   --> vmm/src/device_manager.rs:737:26
    |
737 |             .insert(i8042.clone(), 0x61, 0x4)
    |                          ^^^^^^^^ help: remove this
    |
note: this value is dropped without further use
   --> vmm/src/device_manager.rs:737:21
    |
737 |             .insert(i8042.clone(), 0x61, 0x4)
    |                     ^^^^^
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

error: redundant clone
   --> vmm/src/device_manager.rs:754:29
    |
754 |                 .insert(cmos.clone(), 0x70, 0x2)
    |                             ^^^^^^^^ help: remove this
    |
note: this value is dropped without further use
   --> vmm/src/device_manager.rs:754:25
    |
754 |                 .insert(cmos.clone(), 0x70, 0x2)
    |                         ^^^^
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Rob Bradford
9fb1c46cd1 vm-virtio: Remove unnecessary cloning
Found by updated clippy:

error: redundant clone
   --> vm-virtio/src/block.rs:182:5
    |
182 |     .to_owned();
    |     ^^^^^^^^^^^ help: remove this
    |
    = note: `-D clippy::redundant-clone` implied by `-D warnings`
note: this value is dropped without further use
   --> vm-virtio/src/block.rs:176:21
    |
176 |       let device_id = format!(
    |  _____________________^
177 | |         "{}{}{}",
178 | |         blk_metadata.st_dev(),
179 | |         blk_metadata.st_rdev(),
180 | |         blk_metadata.st_ino()
181 | |     )
182 | |     .to_owned();
    | |____^
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Rob Bradford
deb3cbd501 arch_gen: Remove unused bootparam module
We use the version that's included in the linux-loader crate. This old
version was also generating build errors after updating to the new
clippy:

e.g.:

error: unsafe function's docs miss `# Safety` section
  --> arch_gen/src/x86/bootparam.rs:23:5
   |
23 | /     pub unsafe fn as_ptr(&self) -> *const T {
24 | |         ::std::mem::transmute(self)
25 | |     }
   | |_____^
   |
   = note: `-D clippy::missing-safety-doc` implied by `-D warnings`
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#missing_safety_doc

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-20 00:52:03 +01:00
Sebastien Boeuf
9701fde209 vm-virtio: Add connection handshake to vsock
This patch has been cherry-picked from the Firecracker tree. The
reference commit is 1db04ccc69862f30b7814f30024d112d1b86b80e.

Changed the host-initiated vsock connection protocol to include a
trivial handshake.

The new protocol looks like this:
- [host] CONNECT <port><LF>
- [guest/success] OK <assigned_host_port><LF>

On connection failure, the host host connection is reset without any
accompanying message, as before.

This allows host software to more easily detect connection failures, for
instance when attempting to connect to a guest server that may have not
yet started listening for client connections.

Signed-off-by: Dan Horobeanu <dhr@amazon.com>
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-19 09:48:17 +01:00
Yang Zhong
5c4e1726f8 ci: test the vhost-user-blk readonly function
This patch is to check if block device is readonly
when backend set readonly=true.

The lsblk command can show the RO value in the guest.

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2019-12-18 09:45:11 +01:00
Yang Zhong
cee01edb97 vhost-user-blk backend: add readonly support
The current backend only support rw, and we also need
add readonly support.

The new command:
vhost_user_blk \
  --backend "image=/home/test.img, \
            sock=/home/path/vhost.socket, \
            readonly=true"

Signed-off-by: Yang Zhong <yang.zhong@intel.com>
2019-12-18 09:45:11 +01:00
Rob Bradford
91549ddd71 tests: Add integration test for CPU unplug
Enhance the CPU hotplug test to also unplug the CPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-18 08:23:53 +00:00
Rob Bradford
a6878accd5 vmm: cpu: Implement CPU removal
When the running OS has been told that a CPU should be removed it will
shutdown the CPU and then signal to the hypervisor via the "_EJ0" method
on the device that ultimately writes into an I/O port than the vCPU
should be shutdown. Upon notification the hypervisor signals to the
individual thread that it should shutdown and waits for that thread to
end.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-18 08:23:53 +00:00
Rob Bradford
7b3fc72aea vmm: cpu: Notify guest OS that it should offline vCPUs
Allow the resizing of the number of vCPUs to less than the current
active vCPUs. This does not currently remove them from the system but
the kernel will take them offline.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-18 08:23:53 +00:00
Rob Bradford
7e81b0ded7 vmm: cpu: Create vCPU state for all possible vCPUs
This will make it more straightforward when we attempt to remove vCPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-18 08:23:53 +00:00
Rob Bradford
156ea392a2 vmm: cpu: Only do ACPI notify on newly added vCPUs
When we add a vCPU set an "inserting" boolean that is exposed as an ACPI
field that will be checked for and reset when the ACPI GED notification
for CPU devices happens.

This change is a precursor for CPU unplug.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-16 23:57:14 +01:00
Rob Bradford
e8313e3e69 vmm: acpi: Refactor ACPI CPU notification
Continue to notify on all vCPUs but instead separate the notification
functionality into two methods, CSCN that walks through all the CPUs
and CTFY which notifies based on the numerical CPU id. This is an
interim step towards only notifying on changed CPUs and ultimately CPU
removal.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-16 23:57:14 +01:00
Sebastien Boeuf
43d2e09e1f ci: Add unit tests to compare CLI and OpenAPI
The goal here is to ensure that CLI and OpenAPI both behave as closely
as possible, and also that they behave as expected.

Leveraging the reorganization of the code, we can now compare two
VmConfig structures generated from one CLI entry on one side, and from
an OpenAPI entry (JSON payload) on the other side.

Fixes #535

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
Sebastien Boeuf
d1390906c8 vmm: config: Derive Debug and PartialEq for configuration structures
In anticipation for the writing of unit tests comparing two VmConfig
structures, this commit derives the PartialEq trait for VmConfig and
all embedded structures.

This patch also derives the Debug trait for the same set of structures
so that we can print them to facilitate debugging.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
Sebastien Boeuf
93f5f6ed45 vmm: config: Provide a default empty command line through OpenAPI
The OpenAPI should not have to provide a command line since the CLI
considers the command line as an empty string if nothing is provided.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
Sebastien Boeuf
43bd0e53c4 main: Move VmParams creation into a dedicated function
This brings more modularity to the code, which will be helpful when we
will later test the CLI and OpenAPI generate the same VmConfig output.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
Sebastien Boeuf
17a167dbb6 main: Move default values preparation into a dedicated function
This brings more modularity to the code, which will be helpful when we
will later test the CLI and OpenAPI generate the same VmConfig output.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
Sebastien Boeuf
9c3a7ddcc9 main: Move clap::App creation into a dedicated function
This brings more modularity to the code, which will be helpful when we
will later test the CLI and OpenAPI generate the same VmConfig output.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-16 16:48:59 +01:00
dependabot-preview[bot]
11750efb78 build(deps): bump log from 0.4.8 to 0.4.10
Bumps [log](https://github.com/rust-lang/log) from 0.4.8 to 0.4.10.
- [Release notes](https://github.com/rust-lang/log/releases)
- [Changelog](https://github.com/rust-lang/log/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/log/compare/0.4.8...0.4.10)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-16 14:46:05 +00:00
dependabot-preview[bot]
dea5776fb9 build(deps): bump serde from 1.0.103 to 1.0.104
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.103 to 1.0.104.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.103...v1.0.104)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-16 08:15:47 +00:00
dependabot-preview[bot]
7909f7a8c9 build(deps): bump serde_derive from 1.0.103 to 1.0.104
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.103 to 1.0.104.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.103...v1.0.104)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-16 07:05:03 +00:00
Rob Bradford
23150f8647 tests: Throttle tests based on disk space
On our CI the /tmp filesystem is mounted as tmpfs and this is the
location where the test disk images are located. When the CI worker
nodes have less memory and fewer CPUs the tmpfs fills up as the tests
run in parallel.

Introduce a mechanism to reduce the parallelism of the tests based on
starvation of the tmpfs disk availability.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-13 16:42:59 +01:00
Rob Bradford
d59fe4eee7 ci: Add some time measurements to CI scripts
Add some use of "time" to measure the wallclock time for various items
within our CI scripts.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-13 13:42:52 +00:00
Samuel Ortiz
fa0fdc6500 cargo: Update Cargo.lock for the 0.4.0 release
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-13 12:21:13 +01:00
Samuel Ortiz
cec884e863 release: v0.4.0
Expand release notes and bump Cargo.toml.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-13 11:42:59 +01:00
Rob Bradford
6444e29b04 docs: Add CPU hot plug documentation
Add details of how to add vCPUs to the running VM.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-13 10:34:41 +00:00
dependabot-preview[bot]
a002093a55 build(deps): bump anyhow from 1.0.23 to 1.0.25
Bumps [anyhow](https://github.com/dtolnay/anyhow) from 1.0.23 to 1.0.25.
- [Release notes](https://github.com/dtolnay/anyhow/releases)
- [Commits](https://github.com/dtolnay/anyhow/compare/1.0.23...1.0.25)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-13 08:29:30 +01:00
dependabot-preview[bot]
43f0478fa8 build(deps): bump thiserror from 1.0.6 to 1.0.9
Bumps [thiserror](https://github.com/dtolnay/thiserror) from 1.0.6 to 1.0.9.
- [Release notes](https://github.com/dtolnay/thiserror/releases)
- [Commits](https://github.com/dtolnay/thiserror/compare/1.0.6...1.0.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-13 06:38:08 +00:00
Samuel Ortiz
664431ff14 vsock: vhost_user: vfio: Fix potential host memory overflow
The vsock packets that we're building are resolving guest addresses to
host ones and use the latter as raw pointers.
If the corresponding guest mapped buffer spans across several regions in
the guest, they will do so in the host as well. Since we have no
guarantees that host regions are contiguous, it may lead the VMM into
trying to access memory outside of its memory space.

For now we fix that by ensuring that the guest buffers do not span
across several regions. If they do, we error out.
Ideally, we should enhance the rust-vmm memory model to support safe
acces across host regions.

Fixes CVE-2019-18960

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 22:15:50 +01:00
Rob Bradford
1e97d1413e README: Update for newer distribution support
Highlight that we support Ubuntu Bionic and Eoan as well as Clear Linux
and update the Clear Linux versions referenced.

Also update the firmware URL to point to the latest version.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-12 13:36:28 +01:00
Samuel Ortiz
e8e21aeb7e README: Update the --cpus command line examples
We recommend to specify the boot cpus, even though the old syntax is still
supported.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 11:55:37 +00:00
Sebastien Boeuf
a40a70ad86 ci: Rely on latest virtiofsd version
Virtio-fs maintainers recently updated the virtiofsd daemon through
their official branch on Gitlab. It includes fixes that were needed for
cloud-hypervisor to work correctly with it.

Jenkinsfile needs to be updated since the virtiofsd build requires both
libseccomp and libcap-ng to be present on the system.

One thing to notice, because the latest branch introduced a change
regarding libfuse behavior, the counterpart patch has been added to the
custom kernel branch "virtio-fs-virtio-iommu".

Fixes #536

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-12 11:09:36 +01:00
Samuel Ortiz
f0b7412495 vmm: device_manager: Add all virtio devices to the migratable list
We want to track all migratable devices through the DeviceManager.

Fixes: #341

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
37557c8b35 vmm: vm: Implement the Pausable trait
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
9756fc2dd0 vmm: cpu_manager: Implement the Pausable trait
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
35dd1523c9 vmm: device_manager: Implement the Pausable trait
Since the Snapshotable placeholder and Migratable traits are provided as
well, the DeviceManager object and all its objects are now Migratable.

All Migratable devices are tracked as Arc<Mutex<dyn Migratable>>
references.

Keeping track of all migratable devices allows for implementing the
Migratable trait for the DeviceManager structure, making the whole
device model potentially migratable.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
a122da4bef vm-virtio: vhost: Implement the Pausable trait for all vhost-user devices
Due to the amount of code currently duplicated across vhost-user devices,
the stats for this commit is on the large side but it's mostly more
duplicated code, unfortunately.

Migratable and Snapshotable placeholder implementations are provided as
well, making all vhost-user devices Migratable.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
dae0b2ef72 vm-virtio: Implement the Pausable trait for all virtio devices
Due to the amount of code currently duplicated across virtio devices,
the stats for this commit is on the large side but it's mostly more
duplicated code, unfortunately.

Migratable and Snapshotable placeholder implementations are provided as
well, making all virtio devices Migratable.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
35d7721683 vmm: Convert virtio devices to Arc<Mutex<T>>
Migratable devices can be virtio or legacy devices.
In any case, they can potentially be tracked through one of the IO bus
as an Arc<Mutex<dyn BusDevice>>. In order for the DeviceManager to also
keep track of such devices as Migratable trait objects, they must be
shared as mutable atomic references, i.e. Arc<Mutex<T>>. That forces all
Migratable objects to be tracked as Arc<Mutex<dyn Migratable>>.

Virtio devices are typically migratable, and thus for them to be
referenced by the DeviceManager, they now should be built as
Arc<Mutex<VirtioDevice>>.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
5450de0f5e cargo: Do not run fmt on anyhow's build code
The anyhow crate generates some incorrectly indented code from its
build.rs code. We don't want to run cargo fmt on this code.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Samuel Ortiz
0361df4ae0 vm-device: Initial Migratable trait
The Migratable trait groups all expected capabilities of devices and
components that can be migrated.

For a component to be migrated, it must be able to pause and resume.
Once paused, it should be able to provide a snapshot of itself. It
should also be able to restore itself from a snaphot.

As a consequence, the Migratable trait will be split between the
Pausable and the Snapshotable traits. This commit only adds the
Pausable one.

All migratable devices will be tracked from the DeviceManager.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-12-12 08:50:36 +01:00
Rob Bradford
36daf9c0b0 ci: Skip testing RFC or WIP PRs
To alleviate load on the CI only test PRs that are not marked as RFC or
WIP.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-11 18:22:12 +01:00
Sebastien Boeuf
64c5e3d8cb vmm: api: Adjust FsConfig for OpenAPI
The FsConfig structure has been recently adjusted so that the default
value matches between OpenAPI and CLI. Unfortunately, with the current
description, there is no way from the OpenAPI to describe a cache_size
value "None", so that DAX does not get enabled. Usually, using a Rust
"Option" works because the default value is None. But in this case, the
default value is Some(8G), which means we cannot describe a None.

This commit tackles the problem, introducing an explicit parameter
"dax", and leaving "cache_size" as a simple u64 integer.

This way, the default value is dax=true and cache_size=8G, but it lets
the opportunity to disable DAX entirely with dax=false, which will
simply ignore the cache_size value.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
4bfd51cc42 vmm: api: Match VhostUserBlkConfig defaults between CLI and HTTP API
In order to let the CLI and the HTTP API behave the same regarding the
VhostUserBlkConfig structure, this patch defines some default values
for num_queues, queue_size and wce.

num_queues is 1, queue_size is 128 and wce is true.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
1c2587f8cb vmm: api: Match VhostUserNetConfig defaults between CLI and HTTP API
In order to let the CLI and the HTTP API behave the same regarding the
VhostUserNetConfig structure, this patch defines some default values
for num_queues, queue_size and mac.

num_queues is 2 since that's a pair of TX/RX queues, queue_size is 256
and mac is a randomly generated value.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
5e0bbf9c3b vmm: Don't factorize vhost-user configurations
We want to set different default configurations for vhost-user-net and
vhost-user-blk, which is the reason why the common part corresponding to
the number of queues and the queue size cannot be embedded.

This prepares for the following commit, matching API and CLI behaviors.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
793327cff8 vmm: api: Make ConsoleConfig default match between CLI and HTTP API
A simple patch making sure the field "file" is provisioned with the same
default value through CLI and OpenAPI.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
cc08c44cb9 vmm: api: Make MemoryConfig default match between CLI and HTTP API
Just making sure we have a serde default for the field "file" since it
is not a required field in the OpenAPI definition.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
5a72225856 vmm: api: Update CpuConfig name to match the internal name
All structures match between the OpenAPI definition and the internal
configuration code, that's why CpuConfig is being renamed into
CpusConfig.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Sebastien Boeuf
f7c215d92d cli: Fix default CPU argument
By default, and in order to avoid falling into the legacy CLI usage, the
CPU argument should at least include "boot=" to define the number of
CPUs.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 15:50:24 +00:00
Rob Bradford
59ae01ff71 ci: Cancel older builders on Jenkins
When a new build is triggered cancel any older builds to conserve
resources.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-11 15:50:01 +00:00
Rob Bradford
c61104df47 vmm: Port to latest vmm-sys-util
The signal handling for vCPU signals has changed in the latest release
so switch to the new API.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-11 14:11:11 +00:00
Sebastien Boeuf
4c92f89f0f ci: Add OpenAPI validation
We need to validate that OpenAPI YAML definition is not broken by each
and every pull request. The easiest way is to rely on the Docker image
provided by OpenAPITools, as it allows us to validate the definition
with one simple command.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 12:53:31 +00:00
Sebastien Boeuf
93bd88e681 ci: Simplify travis.yml
Now that Cargo tests are being run on the worker node directly, we can
leave the bare minimum in Travis, which is taking care of the release
deployment.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 12:53:31 +00:00
Sebastien Boeuf
d42ef186a1 ci: Offload cargo tests to the worker node VM
Because the resources on the amount of worker nodes we can have access
to through Travis is limited, we offload the burden of running all tests
related to Cargo inside the Azure VM directly.

This will have the positive effect of stopping the build very early in
case something goes wrong during the Cargo testing.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-11 12:53:31 +00:00
Sebastien Boeuf
ee528ae808 vmm: api: Make FsConfig defaults match between CLI and HTTP API
In order to let the CLI and the HTTP API behave the same regarding the
FsConfig structure, this patch defines some default values for
num_queues, queue_size and the cache_size.

num_queues is set to 1, queue_size is set to 1024, and cache_size is set
to Some(8G) which means that DAX is enabled by default with a shared
region of 8GiB.

Fixes #508

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-09 23:42:23 -08:00
Sebastien Boeuf
befd342da4 vmm: api: Make NetConfig defaults match between CLI and HTTP API
In order to let the CLI and the HTTP API behave the same regarding the
NetConfig structure, this patch defines some default values for tap, ip,
mask, mac and iommu.

tap is None, ip is 192.168.249.1, mask is 255.255.255.0, mac is a
randomly generated value, and iommu is false.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-09 23:19:24 -08:00
Sebastien Boeuf
eff78f746a resources: Prevent kernel config interactive shell from showing up
Following the recent addition of CONFIG_EXPERT=y, the kernel config now
asks for several options through interactive shell. This is not
convenient when locally running the integration tests script as the
shell asks for input.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-10 06:24:11 +01:00
Jose Carlos Venegas Munoz
99e608c240 openapi: Fix schema
Fix openapi schema to be a valid yaml.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-12-09 14:30:15 -08:00
Rob Bradford
f994665610 vmm: Reduce the minimum IRQ constant
Now that the GED device does not use a hardcoded IRQ number the starting
IRQ number can be restored (needed for the hardcoded serial port IRQ.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-09 16:58:00 +00:00
Rob Bradford
ba59c62044 vmm, devices: Remove hardcoded IRQ number for GED device
Remove the previously hardcoded IRQ number used for the GED device.
Instead allocate the IRQ using the allocator and use that value in the
definition in the ACPI device.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-09 16:58:00 +00:00
Qiu Wenbo
ce1bd9c7ff resources: turn on CONFIG_ACPI_REDUCED_HARDWARE_ONLY
We need turn on CONFIG_ACPI_REDUCED_HARDWARE_ONLY to support cpu hotplug
feature.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2019-12-09 10:49:17 +01:00
dependabot-preview[bot]
0374c3dc71 build(deps): bump ssh2 from 0.5.0 to 0.6.0
Bumps [ssh2](https://github.com/alexcrichton/ssh2-rs) from 0.5.0 to 0.6.0.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/0.5.0...0.6.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-09 05:53:30 +00:00
Sebastien Boeuf
aa94e9b8f3 Revert "vmm: api: Modify FsConfig to be OpenAPI friendly"
This reverts commit defc5dcd9c.
2019-12-06 18:08:10 +00:00
Rob Bradford
9b1ba14f2d vmm: Delegate device related ACPI DSDT table work to DeviceManager
Move the code for handling the creation of the DSDT entries for devices
into the DeviceManager.

This will make it easier to handle device hotplug and also in the future
remove some hardcoded ACPI constants.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 17:44:00 +00:00
Rob Bradford
60e6609011 vmm: Delegate CPU related ACPI tables to CpuManager
Move the code for generating the MADT (APIC) table and the DSDT
generation for CPU related functionality into the CpuManager.

There is no functional change just code rearrangement.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 17:44:00 +00:00
Sebastien Boeuf
defc5dcd9c vmm: api: Modify FsConfig to be OpenAPI friendly
When consumer of the HTTP API try to interact with cloud-hypervisor,
they have to provide the equivalent of the config structure related to
each component they need. Problem is, the Rust enum type "Option" cannot
be obtained from the OpenAPI YAML definition.

This patch intends to fix this inconsistency between what is possible
through the CLI and what's possible through the HTTP API by using simple
types bool and int64 instead of Option<u64>.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-06 06:38:48 -08:00
Sebastien Boeuf
66e00ce710 ci: Extend VFIO integration test
In order to validate that multiple devices can be passed through and
they are still fully functional, this patch extends the existing VFIO
test to pass a second virtio-net device, and verifies that both
interfaces are functional by ssh'ing into each network interface.

Fixes #503

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-06 12:53:09 +01:00
Rob Bradford
59d01712ad vmm: Remove kernel based IOAPIC handling from the device manager
Previously the device setup code assumed that if no IOAPIC was passed in
then the device should be added to the kernel irqchip. As an earlier
change meant that there was always a userspace IOAPIC this kernel based
code can be removed.

The accessor still returns an Option type to leave scope for
implementing a situation without an IOAPIC (no serial or GED device).
This change does not add support no-IOAPIC mode as the original code did
not either.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 12:34:06 +01:00
Rob Bradford
afea6a10a2 vmm: Stop initialising kernel based IOAPIC/PIC
Now that we require the modern capabilities we can stop creating a
kernel base irqchip.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 12:34:06 +01:00
Rob Bradford
9b1cb9621f vmm: Remove pin based interrupt setup for virtio devices
With MSI now required remove pin based interrupt support from all the
virtio PCI device setup.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 12:34:06 +01:00
Rob Bradford
72fb687e3f vmm: Check for required capabilities
We now require CAP_SIGNAL_MSI, CAP_TSC_DEADLINE_TIMER and
CAP_SPLIT_IRQCHIP.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-06 12:34:06 +01:00
dependabot-preview[bot]
904b1ea599 build(deps): bump unicode-width from 0.1.6 to 0.1.7
Bumps [unicode-width](https://github.com/unicode-rs/unicode-width) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/unicode-rs/unicode-width/releases)
- [Commits](https://github.com/unicode-rs/unicode-width/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-05 23:19:28 +00:00
Rob Bradford
fcf92d86b5 tests: Add rebooting to the CPU hotplug test
Check that the added vCPUs are still there after a reboot.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-05 16:39:19 +00:00
Rob Bradford
f98b16f308 vmm: Update the configuration to preserve hot-plug CPUs after reboot
Update the configuration after a resize to ensure that after a reboot
the added vCPUs are preserved.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-05 16:39:19 +00:00
Rob Bradford
1722708612 vmm: Switch to storing VmConfig inside an Arc<Mutex<>>
This permits the runtime reconfiguration of the VM.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-05 16:39:19 +00:00
Rob Bradford
c063bb8d30 vmm: acpi: Make GED interrupt edge triggered
This was causing issues when the kernel was trying to reset the
interrupt and making the reboot fail.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-05 16:39:19 +00:00
Qiu Wenbo
e1af17d93a vmm: Restore tty to canonical mode when SIGTERM or SIGINT received
The tty mode remains raw mode when cloud-hypervisor is terminted by
SIGTERM or SIGINT. The terminal is unusable due to echoing is
disabled which is really annoying.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2019-12-05 01:29:26 -08:00
dependabot-preview[bot]
44d026bfb1 build(deps): bump serde_json from 1.0.43 to 1.0.44
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.43 to 1.0.44.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.43...v1.0.44)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-04 22:53:40 +00:00
dependabot-preview[bot]
a1285ea57d build(deps): bump cc from 1.0.47 to 1.0.48
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.47 to 1.0.48.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.47...1.0.48)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-04 16:57:32 +00:00
Sebastien Boeuf
23929f41a7 vfio: Don't override MSI Enable bit through VFIO ioctl
This commit ensures device's PCI config space is being written after
MSI/MSI-X interrupts have been enabled/disabled. In case of MSI, when
the interrupts are enabled through VFIO (using VFIO_DEVICE_SET_IRQS),
the MSI Enable bit in the MSI capability structure found in the PCI
config space is disabled by default. That's why when the guest is
enabling this bit, we first need to enable the MSI interrupts with
VFIO through VFIO_DEVICE_SET_IRQS ioctl, and only after we can write
to the device region to update the MSI Enable bit.

Fixes #460

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-04 14:47:06 +00:00
Wu Zongyong
1dfd60b609 vfio: use correct flags to disable interrupts
The comments of vfio kernel module said that individual subindex
interrupts can be disabled using the -1 value for DATA_EVENTFD or
the index can be disabled as a whole with:
    flags = (DATA_NONE|ACTION_TRIGGER), count = 0.

Signed-off-by: Wu Zongyong <wuzongyong@linux.alibaba.com>
CC: Liu Jiang <gerry@linux.alibaba.com>
2019-12-04 14:47:06 +00:00
Qiu Wenbo
5208ff86c8 vmm: Detect and handle AMD SME (Secure Memory Encryption)
Some physical address bits may become reserved in page table when SME
is enabled on AMD platform. Guest will trigger a reserved bit
violation page fault in this case due to write these reserved bits to 1
in page table. We need reduce the reserved bits to get the right
physical address range.

Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2019-12-04 14:46:44 +00:00
dependabot-preview[bot]
dcfd6ffd4b build(deps): bump serde_json from 1.0.42 to 1.0.43
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.42 to 1.0.43.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.42...v1.0.43)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-04 11:31:05 +00:00
Sebastien Boeuf
08258d5dad vfio: pci: Allow multiple devices to be passed through
The KVM_SET_GSI_ROUTING ioctl is very simple, it overrides the previous
routes configuration with the new ones being applied. This means the
caller, in this case cloud-hypervisor, needs to maintain the list of all
interrupts which needs to be active at all times. This allows to
correctly support multiple devices to be passed through the VM and being
functional at the same time.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-04 08:48:17 +01:00
Sebastien Boeuf
4115fa8a87 vfio: pci: Update irqfd registration
In order to improve the existing VFIO code, this patch registers the
eventfds used to trigger KVM interrupts only when the interrupts are
enabled, and unregisters them when interrupts are disabled.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-04 08:48:17 +01:00
Sebastien Boeuf
1379abb94b pci: msi: Fix MSG_CTL update through 32 bits write
If the MSG_CTL is being written from a 32 bits write access, the offset
won't be 0x2, but 0x0 instead. That's simply because 32 bits access have
to be aligned on each double word.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-04 08:48:17 +01:00
Sebastien Boeuf
c81e808e98 docs: Update instructions regarding virtiofsd
The documentation was out of date since the URL to download virtiofsd
binary was not valid anymore. Instead, the updated documentation now
describe how to build virtiofsd from source.

Fixes #491

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-12-03 12:16:43 +00:00
Rob Bradford
17badfbff5 vmm: cpu: Call vcpu configure() on the vCPU thread
The function that programs the vCPUs is expected to be run from within
each vCPU thread.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-03 03:22:15 -08:00
Rob Bradford
13503061e6 api: Fix OpenAPI specification entries
Some renames from "cpu_count" were missing.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-03 03:28:06 +01:00
Rob Bradford
e1ff142392 tests: Remove MSI only test from test_serial_off
Now we have a GED device we are not MSI only when the serial port is
turned off.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
e0830640b7 tests: Add integration test for hotplugging vCPUs
Resize the VM to increase the number of vCPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
66a31c19e8 vmm: acpi: Upon GED interrupt notify on all vCPUs
Call the "CTFY" method that will itself call Notify() on the CPU objects
in the ACPI namespace.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
48bf141364 vmm: Trigger a hotplug device notification when resizing
When adjusting the number of vCPUs generate a hotplug notification.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
b629727901 vmm: acpi: Add a CTFY method to notify on all CPU objects
This method calls Notify() on all the vCPU objects in the ACPI
namespace.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
ae9359c859 vmm: acpi: Create the CPU entries in the DSDT for all vCPUs
CPU entries need to be created for every potential vCPU in the system.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
791ca3388f vmm: device_manager: Add ability to notify via GED device
Add ability to notify via the GED device that there is some new hotplug
activity. This will be used by the CpuManager (and later DeviceManager
itself) to notify of new hotplug activity.

Currently it has a hardcoded IRQ of 5 as the ACPI tables also need to
refer to this IRQ and the IRQ allocation does not permit the allocation
of specific IRQs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
623755cc70 devices: Add ACPI GED device
This device provides the ability to notify the kernel via interrupt that
there is some new hotplug activity. The type is determined by reading
from the I/O port.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
7ad68d499a vmm: device_manager: Allocate I/O port for ACPI shutdown device
The refactoring in ce1765c8af dropped the
code to allocate the I/O port.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
86339b4cb4 vmm: Add HTTP API to resize the VM
Currently only increasing the number of vCPUs is supported but in the
future it will be extended.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
e7d4eae527 vmm: cpu: Add support for starting more vCPU threads
Add support for starting vCPU threads after the initial boot ones.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
0ef999978c vmm: cpu: Support only partially configuring the vCPU
When configuring a processor after boot as a hotplug CPU we only
configure a subset of the CPU state. In particular we should not
configure the FPU, segment registers (or reconfigure the paging which is
a side-effect of that) nor the main registers. Achieve this by making
the function take an Option type for the start address.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
c8b3041e62 vmm: openapi: Update OpenAPI for CpuConfig struct
This struct has changed in order to support differentiating between boot
and max vCPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
b6801e355e vmm: cpu: Refactor vCPU thread starting
Refactor the vCPU thread starting so that there is the possibility to
bring on extra vCPU threads.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
66d5163ee7 vmm: cpu: Encapsulate vCPU state into its own struct
Currently this just holds the thread handle but will be enlarged to
encompass details such as whether the vCPU is currently being inserted
or ejected.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
ea19bb026f tests: Add a test to check that the boot vs max cpus work
The easiest way to detect if the kernel is willing to accept hotplug
vCPUs is to check the dmesg output.

Switch the test to bionic as the Clear Cloud image lacks "dmesg."

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
1bbe48b24c vmm: acpi: Mark non-boot vCPUs as disabled in the MADT table
The MADT table contains the details of all the potential vCPUs and
whether they are present at boot (as indicated by the flags field.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
4bc8635c59 tests: Use new "--cpus" syntax for integration tests
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
82bc07cce4 vmm: Add boot and max vCPU handling to command line parser
Also retain support (with a warning for the old behaviour.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
7543e00a07 vmm: Use new CpuManager accessor to get boot vCPUs
When initialising the ACPI tables and configuring the VM use the new
accessor on the CpuManager to get the number of boot vCPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Rob Bradford
df0907845a vmm: cpu: Introduce concept of maximum vs boot vCPUs in CpuManager
For now the max vCPUs is the same as the boot vCPUs.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-12-02 13:49:04 +00:00
Sergio Lopez
669d9a8ae8 vhost_user_backend: fix memory region offsetting
The way in which offsets are currently use in memory regions is
derived from QEMU's contrib/libvhost-user, but while this one works
mainly by translating vmm va's to local va's, vm-memory expects us to
use proper guest addresses and thus, define memory regions that
actually match the guest's memory disposition.

With this change, we create the memory regions with the proper length
and offsets, extend AddrMapping to store the guest physical address,
and use the latter instead of offset in vmm_va_to_gpa().

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-12-02 01:57:25 -08:00
dependabot-preview[bot]
d378da64ee build(deps): bump vcpkg from 0.2.7 to 0.2.8
Bumps [vcpkg](https://github.com/mcgoo/vcpkg-rs) from 0.2.7 to 0.2.8.
- [Release notes](https://github.com/mcgoo/vcpkg-rs/releases)
- [Changelog](https://github.com/mcgoo/vcpkg-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mcgoo/vcpkg-rs/compare/vcpkg-rs-0.2.7...vcpkg-rs-0.2.8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-02 07:50:00 +00:00
dependabot-preview[bot]
b1cfdc761a build(deps): bump syn from 1.0.9 to 1.0.11
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.9 to 1.0.11.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.9...1.0.11)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-12-01 11:33:30 +00:00
Samuel Ortiz
0f21781fbe cargo: Bump the kvm and vmm-sys-util crates
Since the kvm crates now depend on vmm-sys-util, the bump must be
atomic.
The kvm-bindings and ioctls 0.2.0 and 0.4.0 crates come with a few API
changes, one of them being the use of a kvm_ioctls specific error type.
Porting our code to that type makes for a fairly large diff stat.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-29 17:48:02 +00:00
dependabot-preview[bot]
ca97385da5 build(deps): bump libc from 0.2.65 to 0.2.66
Bumps [libc](https://github.com/rust-lang/libc) from 0.2.65 to 0.2.66.
- [Release notes](https://github.com/rust-lang/libc/releases)
- [Commits](https://github.com/rust-lang/libc/compare/0.2.65...0.2.66)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-29 13:00:02 +00:00
dependabot-preview[bot]
f7dace151c build(deps): bump syn from 1.0.8 to 1.0.9
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.8 to 1.0.9.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.8...1.0.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-29 08:48:13 +00:00
Qiu Wenbo
861d902c21 acpi_tables: aml: Add support for binary operators
Signed-off-by: Qiu Wenbo <qiuwenbo@phytium.com.cn>
2019-11-29 08:47:58 +00:00
Rob Bradford
f787139805 build: Reorder travis build commands to reuse build assets
Reorder the build commands so that more build assets in the target/
build directory can be reused. This will reduce the build time.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-28 14:29:38 +01:00
Rob Bradford
338beebc83 misc: Update locations to point to new kernel fork
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-28 14:28:12 +01:00
Wu Zongyong
4de04e84b5 vfio-pci: unmap regions when dropping VfioGroup
Introduce method unmap_mmio_regions to unmap all regions mapped to host.
This patch eliminate the error message "Could not unset container".

Signed-off-by: Wu Zongyong <wuzongyong@linux.alibaba.com>
2019-11-27 07:44:02 -08:00
Jose Carlos Venegas Munoz
62fa595ac6 cargo: set cloud-hypervisor as default crate
cloud-hypervisor is the main crate, useful to do cargo run.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-26 10:33:48 +01:00
Jose Carlos Venegas Munoz
ab16af2941 openapi: make context ID vsock int64
context ID on vsock man defines a 32-bits value, openapi default integer
is a signed 32-bits value.

This could lead to miss one bit during castings for typed client
implmentations. Lets increase the range of valid values by requesting an
int64.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-26 08:38:59 +01:00
dependabot-preview[bot]
9fd5ea4951 build(deps): bump signal-hook from 0.1.11 to 0.1.12
Bumps [signal-hook](https://github.com/vorner/signal-hook) from 0.1.11 to 0.1.12.
- [Release notes](https://github.com/vorner/signal-hook/releases)
- [Changelog](https://github.com/vorner/signal-hook/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/signal-hook/compare/v0.1.11...v0.1.12)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 21:09:19 +00:00
dependabot-preview[bot]
d6d1074ca3 build(deps): bump serde_derive from 1.0.102 to 1.0.103
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.102 to 1.0.103.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.102...v1.0.103)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 20:32:53 +00:00
dependabot-preview[bot]
4cff045cc6 build(deps): bump serde_json from 1.0.41 to 1.0.42
Bumps [serde_json](https://github.com/serde-rs/json) from 1.0.41 to 1.0.42.
- [Release notes](https://github.com/serde-rs/json/releases)
- [Commits](https://github.com/serde-rs/json/compare/v1.0.41...v1.0.42)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 19:54:16 +00:00
dependabot-preview[bot]
0ae9610e09 build(deps): bump serde from 1.0.102 to 1.0.103
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.102 to 1.0.103.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.102...v1.0.103)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 18:52:45 +00:00
dependabot-preview[bot]
0274b7923b build(deps): bump signal-hook-registry from 1.1.1 to 1.2.0
Bumps [signal-hook-registry](https://github.com/vorner/signal-hook) from 1.1.1 to 1.2.0.
- [Release notes](https://github.com/vorner/signal-hook/releases)
- [Changelog](https://github.com/vorner/signal-hook/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/signal-hook/compare/registry-v1.1.1...registry-v1.2.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 17:15:16 +00:00
dependabot-preview[bot]
edd59a0f97 build(deps): bump remain from 0.1.4 to 0.1.5
Bumps [remain](https://github.com/dtolnay/remain) from 0.1.4 to 0.1.5.
- [Release notes](https://github.com/dtolnay/remain/releases)
- [Commits](https://github.com/dtolnay/remain/compare/0.1.4...0.1.5)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 17:11:41 +00:00
dependabot-preview[bot]
c718225c5f build(deps): bump openssl-sys from 0.9.52 to 0.9.53
Bumps [openssl-sys](https://github.com/sfackler/rust-openssl) from 0.9.52 to 0.9.53.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-sys-v0.9.52...openssl-sys-v0.9.53)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-25 17:06:23 +00:00
Sebastien Boeuf
360f0639f4 Revert "vfio: use correct flags to disable interrupts"
This reverts commit 66fde245b3.

The commit broke the VFIO support for MSI. Issue needs to be
investigated but in the meantime, it is safer to fix the codebase.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-24 12:43:06 +01:00
Rob Bradford
8fe5a43d9d tests: Only setcap on test binary
The setcap tool is unusual in its behaviour in that it will process each
parameter separately and abort if one of the parameters is invalid (e.g.
after a symlink.) But any previous parameters will be correctly
processed. This means that depending on the generated test binary name
an invalid entry might occur before it and thus abort the setcap.

Fix to only setcap on the test binary by excluding the other files.
Because the binary name is based on a hash the PR that introduced this
version worked but once merged the hash changed and broke the build.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-23 21:15:56 +00:00
Sebastien Boeuf
f1c7f0c0b8 ci: Add integration test for vhost_user_fs daemon
In order to validate the new virtio-fs daemon written in Rust is
behaving correctly, a new integration test has been added. Important to
note that for now, only a test with cache=none and dax=off can be added
since the daemon does not support shared memory region yet.

The long term goal being to replace virtiofsd with vhost_user_daemon
once it will reach parity regarding the supported features.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
50b0e58c88 vhost_user_fs: Allow specific shared directory to be specified
Because the vhost_user_backend crate needs some changes to support
moving the process to a different mount namespace and perform a pivot
root, it is not possible to change '/' to the given shared directory.

This commit, as a temporary measure, let the code point at the given
shared directory.

The long term solution is to perform the mount namespace change and the
pivot root as this will provide greater security.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
ba17758ac0 src: Add vhost-user-fs daemon
This patch implements a vhost-user-fs daemon based on Rust. It only
supports communicating through the virtqueues. The support for the
shared memory region associated with DAX will be added later.

It relies on all the code copied over from the crosvm repository, based
on the commit 961461350c0b6824e5f20655031bf6c6bf6b7c30.

It also relies on the vhost_user_backend crate, limiting the amount of
code needed to get this daemon up and running.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
5c128023da vhost_user_fs: Add Server structure to consume FileSystem implementation
Add a Server type that links the FUSE protocol with the virtio
transport. It parses messages sent on the virtio queue and then
calls the appropriate method of the Filesystem trait.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

One small modification has been applied to the original code. Because
cloud-hypervisor didn't have the macro used by crosvm, the match
statement in the function handle_message() has been updated.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
e1fccc3615 vhost_user_fs: Add virtio descriptor helper traits
Introduce helpers to split a virtio descriptor into its readable part on
one side, and into its writable part on the other side. This is useful
to separate the request from the reply.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Two important modifications have been applied to the original code:
- GuestMemory is replaced by GuestMemoryMmap from the vm-memory crate,
  which comes with different ways of accessing the memory regions.
- VolatileSlice has different methods, which means the code has been
  updated accordingly.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
5f7935f8e0 vhost_user_fs: Add file traits to handle writing volatile memory
The vm_memory implementation for VolatileSlice is able to read and write
to a source or destination which implements a Read or Write trait.

Unfortunately, this is not enough for this specific use case as we need
to be able to write to a file at a specific offset, which is not
provided by the Read or Write trait.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
e33ccb0c95 vhost_user_fs: Implement FileSystem trait for Passthrough
Add a "passthrough" file system implementation that just forwards its
requests to the appropriate system call.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
1b76c0a183 vhost_user_fs: Add FileSystem trait
Add the `Filesystem` trait, which is the main interface between the
transport and the actual file system implementation.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
1e65bda0a7 vhost_user_fs: Add multikey module
The multikey module provides a BTreeMap implementation that can use one
of 2 different kinds of keys to look up a value. This is needed by the
virtio-fs server since it needs to be able to look up keys either by
u64 or by a (ino_t, dev_t) pair.

This code has been ported over from crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
cd1684bd2e vhost_user_fs: Add FUSE definitions
To be able to deal with FUSE requests, this commit introduces FUSE
definitions, copied over from the crosvm commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
03361a6c29 vhost_user_fs: Add new crate
This new crate will be dedicated to vhost_user_fs specific code that can
be used as a library from the vhost-user-fs daemon.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Sebastien Boeuf
8845326aa2 vm-virtio: Introduce DescriptorChain iterator
In order to iterate over a chain of descriptor chains, this code has
been ported over from crosvm, based on the commit
961461350c0b6824e5f20655031bf6c6bf6b7c30.

The main modification compared to the original code is the way the
sorting between readable and writable descriptors happens.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 22:17:47 +01:00
Rob Bradford
3d6b5459ef ci: Make the integration test binary run with same caps
By giving the same caps to both cloud-hypervisor and the test binary, we
can access information under /proc related to the VM PID.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-22 15:28:10 +00:00
Rob Bradford
ac118c9924 ci: Parse the smaps file with Rust
Instead of using bash and awk, using Rust allows us to retrieve
information about a VM process with the right permissions as we are not
forced to spawn a new child process.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-22 15:28:10 +00:00
Sebastien Boeuf
bdb7bcdbe3 ci: Add integration test for mergeable memory
The test validates that when the mergeable option is enabled, the
resulting PSS for two instances of cloud-hypervisor is lower than two
instances not using the mergeable flag.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 15:28:10 +00:00
Sebastien Boeuf
f979380620 vmm: Mark guest persistent memory pages as mergeable
In case the VM is started with the flag "--pmem mergeable=on", it means
the user expects the guest persistent memory pages to be marked as
mergeable. This commit relies on the madvise(MADV_MERGEABLE) system call
to inform the host kernel about these pages.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 15:28:10 +00:00
Sebastien Boeuf
0f9afc3017 vmm: Add mergeable=on|off option to --pmem flag
In order to let the user indicate if the persistent memory pages should
be marked as mergeable or not, a new option is being introduced.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 15:28:10 +00:00
Sebastien Boeuf
e4e8062dda vmm: Mark guest RAM pages as mergeable
In case the VM is started with the flag "--memory mergeable=on", it
means the user expects the guest RAM pages to be marked as mergeable.
This commit relies on the madvise(MADV_MERGEABLE) system call to inform
the host kernel about these pages.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 15:28:10 +00:00
Sebastien Boeuf
880f62bab8 vmm: Add mergeable=on|off option to --memory flag
In order to let the user indicate if the guest RAM pages should be
marked as mergeable or not, a new option is being introduced.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-22 15:28:10 +00:00
Rob Bradford
0213177027 Jenkinsfile: Add timeout for build
In order to conserve CI resources limit build execution to one hour.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-22 06:52:21 -08:00
Rob Bradford
d642060378 Jenkinsfile: Switch to pipeline (declarative format)
Switch the Jenkinsfile from the scripted format over to the declarative
format.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-22 06:52:21 -08:00
Jose Carlos Venegas Munoz
1d852e9ce5 vmm: Provide vmm version to start_vmm_thread
When vmm.ping give a response, we expect get the version from
the VMM not the vmm create

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-21 15:04:11 -08:00
Jose Carlos Venegas Munoz
a518651402 http: api: implement vmm.ping
vmm.ping will help to check if http API server is up and
running.

This also removes the vmm.info endpoint.

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-21 15:04:11 -08:00
Rob Bradford
348a1bc30e vmm: cpu: Allocate I/O port for the CPU manager
The CPU manager uses an I/O port and to prevent potential clashes with
assignment for PCI devices ensure that it is allocated by the allocator.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
07cdb37dda vmm: cpu & acpi: Query CPU manager for CPU status
Rather than hardcode the CPU status for all the CPUs instead query from
the CPU manager via the I/O port that is is on via the ACPI tables.

Each CPU device has a _STA method that calls into the CSTA method which
reads and writes the I/O ports via the PRST field which exposes the I/O
port through and OpRegion.

As we only support boot CPUS report that all the CPUs are enabled for
now.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
5faf8b756c vmm: acpi: Add an _MAT for the CPU devices containing a LAPIC
The Linux kernel expects all CPUs, whether they be enabled or disabled
to have an _MAT entry containing the LAPIC details for this CPU with the
enabled bit set to 1 (in the flags.)

In the MADT table the same bit is used to determine if the CPU is
present at boot vs available later.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
e51ebe045f acpi_tables: Add support for Buffer objects
These are necessary to populate "_MAT" entries for CPU devices.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
1da0ff395d vmm: cpu: Add the CpuManager onto the IO bus
This allows the kernel (via ACPI based controls) to query and control
the CPU state.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
39a1b8f4db acpi_tables: aml: Add support for calling methods
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
d5bb0781e4 acpi_tables: aml: Add support for while loops
Which also requires adding support for addition.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
89f0db2173 acpi_tables: aml: Add support for device notification
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
d6696e1bdd acpi_tables: aml: Add support for mutexes
And add support for operations on them.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
3d70ce9ad1 acpi_tables: aml: Add "if" with local variables and arguments
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
d06623fb97 acpi_tables: aml: Add support for OpRegion
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
93ee6f5e62 acpi_tables: aml: Add support for field definitions
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
4b5ce23d97 acpi_tables: Add PkgLength variant that does not include itself
This is necessary as adding support for NamedFields requires a PkgLength
calculation that does not include the length itself.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
50c8335d3d vmm: device_manager: Expose the SystemAllocator
This allows other code to allocate I/O ports for use on the (already)
exposed IO bus.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Rob Bradford
1ac1231292 vmm: Encase CpuManager within an Arc<Mutex<>>
This is necessary to be able to add the CpuManager onto the IO bus.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 09:17:15 -08:00
Wu Zongyong
d7dc1a9226 pci: don't cleanup msi/msix interrupts repeatedly
We disabled msi/msix twice inside Drop trait for VfioPciDevice,
which resulted in error message "Could not disable MSI-X". Eliminating
this error by check whether the msi/msix capability is enabled.

Signed-off-by: Wu Zongyong <wuzongyong@linux.alibaba.com>
CC: Liu Jiang <gerry@linux.alibaba.com>
2019-11-21 06:38:36 -08:00
Wu Zongyong
66fde245b3 vfio: use correct flags to disable interrupts
The comments of vfio kernel module said that individual subindex
interrupts can be disabled using the -1 value for DATA_EVENTFD or
the index can be disabled as a whole with:
    flags = (DATA_NONE|ACTION_TRIGGER), count = 0.

Signed-off-by: Wu Zongyong <wuzongyong@linux.alibaba.com>
CC: Liu Jiang <gerry@linux.alibaba.com>
2019-11-21 06:38:36 -08:00
Rob Bradford
8ec89bc884 misc: Update to new repository locations
Update all references to the new repository locations. Many of these will
redirect however the one used for the hypervisor-fw binary does not so
this is required to allow the builds to pass.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-21 11:39:11 +00:00
Sebastien Boeuf
64305dab16 docs: device_model: Fix formatting error
Fix the summary table format.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-19 15:45:52 -08:00
Sebastien Boeuf
b55d75ea62 docs: Add device model
This commit introduces a dedicated document describing the device model
supported by cloud-hypervisor VMM.

It needs to be updated anytime a new device will be added in the future.

Fixes #437

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-19 14:10:36 -08:00
Samuel Ortiz
f0e618431d vmm: device_manager: Use consistent naming when adding devices
When adding devices to the guest, and populating the device model, we
should prefix the routines with add_. When we're just creating the
device objects but not yet adding them we use make_.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
a2ee681665 vmm: device_manager: Add an MMIO devices creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
MMIO devices creation code into its own routine.

Fixes: #441

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
79b8f8e477 vmm: device_manager: Add a PCI devices creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
PCI devices creation code into its own routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
5087f633f6 vmm: device_manager: Add an IOAPIC creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
ACPI device creation code into its own routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
ce1765c8af vmm: device_manager: Add an ACPI device creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
ACPI device creation code into its own routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
cfca2759fc vmm: device_manager: Add a legacy devices creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
legacy devices creation code into its own routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
Samuel Ortiz
4b469b98cf vmm: device_manager: Add a console creation routine
In order to reduce the DeviceManager's new() complexity, we can move the
console creation code into its own routine.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-19 13:36:21 -08:00
dependabot-preview[bot]
e1281b5488 build(deps): bump cast from 0.2.2 to 0.2.3
Bumps [cast](https://github.com/japaric/cast.rs) from 0.2.2 to 0.2.3.
- [Release notes](https://github.com/japaric/cast.rs/releases)
- [Changelog](https://github.com/japaric/cast.rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/japaric/cast.rs/compare/v0.2.2...v0.2.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-18 08:43:57 +00:00
dependabot-preview[bot]
fa0d573fef build(deps): bump arc-swap from 0.4.3 to 0.4.4
Bumps [arc-swap](https://github.com/vorner/arc-swap) from 0.4.3 to 0.4.4.
- [Release notes](https://github.com/vorner/arc-swap/releases)
- [Changelog](https://github.com/vorner/arc-swap/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/arc-swap/compare/v0.4.3...v0.4.4)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-18 08:43:17 +00:00
Sebastien Boeuf
d9695a0fd9 docs: fs: Update virtio-fs documentation
The cloud-hypervisor supports the DAX shared region for better virtio-fs
performances, but it was not updated in the documentation. This commit
takes care of this and also update the mount command since it changed
with virtio-fs v0.3.

Fixes #433

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-11-15 10:51:31 -08:00
dependabot-preview[bot]
4d0872df5f build(deps): bump vm-memory from 8d6ca35 to bb29ec8
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `8d6ca35` to `bb29ec8`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](8d6ca3553c...bb29ec8713)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-15 06:35:41 +00:00
Emin Ghuliev
c204d5404b docs: networking: Fix typo in hyperlink
An extra double quote was introduced by mistake in one of the hyperlink.

Signed-off-by: Emin Ghuliev drmint80@gmail.com
2019-11-13 13:18:26 +01:00
Samuel Ortiz
b930b3fb41 vmm: api: Specify which integers are 64 bit wide
By default, client will assume 32-bits for OpenAPI interger types.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-12 08:39:05 -08:00
Samuel Ortiz
6af2f57644 vmm: api: Fix the vm.info response payload
We are returning a state and a config.

Fixes: #431

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-12 08:39:05 -08:00
dependabot-preview[bot]
2dcd36f2f0 build(deps): bump synstructure from 0.12.2 to 0.12.3
Bumps [synstructure](https://github.com/mystor/synstructure) from 0.12.2 to 0.12.3.
- [Release notes](https://github.com/mystor/synstructure/releases)
- [Commits](https://github.com/mystor/synstructure/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-11 19:29:20 +00:00
Rob Bradford
6958ec4922 vmm: Move CPU management code to its own module
Move CpuManager, Vcpu and related functionality to its own module (and
file) inside the VMM crate

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-11 15:46:24 +00:00
dependabot-preview[bot]
7b77189c80 build(deps): bump vm-memory from 366a907 to 8d6ca35
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `366a907` to `8d6ca35`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](366a907660...8d6ca3553c)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-11 12:43:48 +00:00
Samuel Ortiz
3dde848c8f vmm: api: Update our OpenAPI document
In most cases we return a 204 (No Content) and not a 201.
In those cases, we do not send any HTTP body back at all.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-10 14:51:55 +01:00
Samuel Ortiz
96aa2441ad vmm: http: Convert to micro_http HttpServer
The new micro_http package provides a built-in HttpServer wrapper for
running a more robust HTTP server based on the package HTTP API.

Switching to this implementation allows us to, among other things,
handle HTTP requests that are larger than 1024 bytes.

Fixes: #423

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-10 14:51:55 +01:00
Samuel Ortiz
f34ace7673 vmm: http_endpoint: Do not sent 200 status code when our body is empty
Otherwise HTTP client will not close the connection and wait for a
pending body.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-11-10 14:51:55 +01:00
Jose Carlos Venegas Munoz
ede262684d API: HTTP: change response content type to JSON
The HTTP API responses are encoded in json

Suggested-by:  Samuel Ortiz <sameo@linux.intel.com>
Tested-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-08 22:49:08 +01:00
Jose Carlos Venegas Munoz
7498647e3f cargo: Update micro_http
Update micro_http create to allow set content type.

Suggested-by:  Samuel Ortiz <sameo@linux.intel.com>
Tested-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>

Signed-off-by: Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
2019-11-08 22:49:08 +01:00
dependabot-preview[bot]
fa94635282 build(deps): bump syn from 1.0.7 to 1.0.8
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.7 to 1.0.8.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.7...1.0.8)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-08 21:18:37 +00:00
Rob Bradford
ff36fa99e6 vm-virtio: Replace use of deprecated std::mem::uninitialized
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-08 20:43:52 +00:00
Rob Bradford
3c715daa9d vmm: Fix rustfmt failure by removing extra ";"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-08 20:43:52 +00:00
Rob Bradford
73b4668bd9 acpi_tables: Fix rustfmt failure by removing extra ";"
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-08 20:43:52 +00:00
Rob Bradford
a1a5fe0c93 vmm: Split CPU management into it's own struct
Pull details of vCPU management (booting, pausing, resuming, shutdown)
into it's own structure. This will ultimately enable this to be moved to
its own file and encapsulate all the vCPU handling for the VMM.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-08 11:59:21 +01:00
Rob Bradford
0319a4a09a arch: vmm: Move ACPI tables creation to vmm crate
Remove ACPI table creation from arch crate to the vmm crate simplifying
arch::configure_system()

GuestAddress(0) is used to mean no RSDP table rather than adding
complexity with a conditional argument or an Option type as it will
evaluate to a zero value which would be the default anyway.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-07 14:02:27 +00:00
Sergio Lopez
c3eaa41b77 ci: use the new vhost-user-blk backend for integration tests
Use the new vhost-user-blk backend for the integration tests,
eliminating the need for building vubd using the implementation in
QEMU.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
Sergio Lopez
ceafd4cee7 vhost_user_backend: remove ownership check in set_features()
set_features() fails with InvalidOperation if !self.owned. I don't see
this as a requirement in the specification and, in fact, vm-virtio
implementation for resetting the device calls SET_FEATURES just after
RESET_OWNER.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
Sergio Lopez
5870452d25 src: add vhost-user-blk backend
Create a vhost-user-blk backend using vhost-user-backend and following
the conventions established by the existing vhost-user-net
implementation.

This backend is based on https://github.com/slp/vhost-user-backend,
but a bit simplified, making it closer to the original implementation
in Firecracker. The main features missing are EVENT_IDX, support for
asynchronous I/O and multiqueue, but it's still fully functional and
provides a good starting point for evolving it into a more complete
implementation.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
Sergio Lopez
3a3dd0096c vm-virtio: export block::Request and related funcs/structs
Export block::Request and related functions and structs so the code
can be shared with vhost-user-blk.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
Sergio Lopez
08bebaae4f vhost_user_backend: move protocol_features to the backend
Extend VhostUserBackend trait with protocol_features(), so device
backend implementations can freely define which protocol features they
want to support.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
Sergio Lopez
85e936d4bd vhost_rs: fix VhostUserConfig payload management
The VhostUserConfig carries a message with a payload, the contents of
which depend on the kind of device being emulated.

With this change, we calculate the offset of the payload within the
message, check its size corresponds to the expected one, and pass it
to the backend as a reference to a slice adjusted to the payload
dimensions.

The backend will be responsible of validating the payload, as it's the
one aware of its expected contents.

Signed-off-by: Sergio Lopez <slp@redhat.com>
2019-11-07 10:36:30 +00:00
dependabot-preview[bot]
2cc723f77b build(deps): bump blake2b_simd from 0.5.8 to 0.5.9
Bumps [blake2b_simd](https://github.com/oconnor663/blake2_simd) from 0.5.8 to 0.5.9.
- [Release notes](https://github.com/oconnor663/blake2_simd/releases)
- [Commits](https://github.com/oconnor663/blake2_simd/compare/0.5.8...0.5.9)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-07 07:40:51 +00:00
dependabot-preview[bot]
d1f03bae84 build(deps): bump pnet_macros from 0.22.0 to 0.23.0
Bumps [pnet_macros](https://github.com/libpnet/libpnet) from 0.22.0 to 0.23.0.
- [Release notes](https://github.com/libpnet/libpnet/releases)
- [Commits](https://github.com/libpnet/libpnet/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-06 14:35:29 +00:00
dependabot-preview[bot]
ae5e8c47ae build(deps): bump cc from 1.0.46 to 1.0.47
Bumps [cc](https://github.com/alexcrichton/cc-rs) from 1.0.46 to 1.0.47.
- [Release notes](https://github.com/alexcrichton/cc-rs/releases)
- [Commits](https://github.com/alexcrichton/cc-rs/compare/1.0.46...1.0.47)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-05 23:58:36 +00:00
dependabot-preview[bot]
8cd45e4ade build(deps): bump synstructure from 0.12.1 to 0.12.2
Bumps [synstructure](https://github.com/mystor/synstructure) from 0.12.1 to 0.12.2.
- [Release notes](https://github.com/mystor/synstructure/releases)
- [Commits](https://github.com/mystor/synstructure/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-05 23:58:17 +00:00
Rob Bradford
c999ea6471 arch: x86_64: acpi: Add basic processor details
Add basic processor details to the DSDT table. The code has to be
slightly convoluted (with the second pass over the cpu_devices vector)
in order to keep the objects alive long enough in order to be able to
take their reference.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-05 14:45:21 +01:00
Rob Bradford
64368a195a acpi_tables: aml: Add support for Method and Return
This allows the implementation of simple methods that return a constant
value.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-05 14:45:21 +01:00
Rob Bradford
08d6386482 acpi_tables: aml: Add support for strings
Support strings from both static strings (&'static str) and String.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-05 14:45:21 +01:00
Cathy Zhang
5cd4f5daeb vmm: Release the old vm before build a new one
In vm_reboot, while build the new vm, the old one pointed by self.vm
is not released, that is, the tap opened by self.vm is not closed
either. As a result, the associated dev name slot in host kernel is
still in use state, which prevents the new build from picking it up as
the new opened tap's name, but to use the name in next slot finally.
Call self.vm_shutdown instead here since it has call take() on vm reference,
which could ensure the old vm is destructed before the new vm build.

Signed-off-by: Cathy Zhang <cathy.zhang@intel.com>
2019-11-05 14:40:43 +01:00
Rob Bradford
b3388c343d vmm: device_manager: Ensure I/O ports are allocated
Ensure that we tell the allocator about all the I/O ports that we are
using for I/O bus attached devices (serial, i8042, ACPI device.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-11-05 10:13:01 +00:00
dependabot-preview[bot]
2d25862477 build(deps): bump pkg-config from 0.3.16 to 0.3.17
Bumps [pkg-config](https://github.com/rust-lang/pkg-config-rs) from 0.3.16 to 0.3.17.
- [Release notes](https://github.com/rust-lang/pkg-config-rs/releases)
- [Changelog](https://github.com/rust-lang/pkg-config-rs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/pkg-config-rs/compare/0.3.16...0.3.17)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-11-02 16:10:00 +00:00
Rob Bradford
ce386ba4c6 tests: Use release build for integration tests
Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-31 10:07:37 -07:00
dependabot-preview[bot]
87e9ce6960 build(deps): bump num_cpus from 1.10.1 to 1.11.0
Bumps [num_cpus](https://github.com/seanmonstar/num_cpus) from 1.10.1 to 1.11.0.
- [Release notes](https://github.com/seanmonstar/num_cpus/releases)
- [Changelog](https://github.com/seanmonstar/num_cpus/blob/master/CHANGELOG.md)
- [Commits](https://github.com/seanmonstar/num_cpus/compare/v1.10.1...v1.11.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-31 14:03:37 +00:00
Sebastien Boeuf
5694ac2b1e vm-virtio: Create new VirtioTransport trait to abstract ioeventfds
In order to group together some functions that can be shared across
virtio transport layers, this commit introduces a new trait called
VirtioTransport.

The first function of this trait being ioeventfds() as it is needed from
both virtio-mmio and virtio-pci devices, represented by MmioDevice and
VirtioPciDevice structures respectively.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-31 09:30:59 +01:00
Sebastien Boeuf
3fa5df4161 vmm: Unregister old ioeventfds when reprogramming PCI BAR
Now that kvm-ioctls has been updated, the function unregister_ioevent()
can be used to remove eventfd previously associated with some specific
PIO or MMIO guest address. Particularly, it is useful for the PCI BAR
reprogramming case, as we want to ensure the eventfd will only get
triggered by the new BAR address, and not the old one.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-31 09:30:59 +01:00
Sebastien Boeuf
587a420429 cargo: Update to the latest kvm-ioctls version
We need to rely on the latest kvm-ioctls version to benefit from the
recent addition of unregister_ioevent(), allowing us to detach a
previously registered eventfd to a PIO or MMIO guest address.

Because of this update, we had to modify the current constraint we had
on the vmm-sys-util crate, using ">= 0.1.1" instead of being strictly
tied to "0.2.0".

Once the dependency conflict resolved, this commit took care of fixing
build issues caused by recent modification of kvm-ioctls relying on
EventFd reference instead of RawFd.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-31 09:30:59 +01:00
Sebastien Boeuf
c7cabc88b4 vmm: Conditionally update ioeventfds for virtio PCI device
The specific part of PCI BAR reprogramming that happens for a virtio PCI
device is the update of the ioeventfds addresses KVM should listen to.
This should not be triggered for every BAR reprogramming associated with
the virtio device since a virtio PCI device might have multiple BARs.

The update of the ioeventfds addresses should only happen when the BAR
related to those addresses is being moved.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-31 09:30:59 +01:00
Sebastien Boeuf
de21c9ba4f pci: Remove ioeventfds() from PciDevice trait
The PciDevice trait is supposed to describe only functions related to
PCI. The specific method ioeventfds() has nothing to do with PCI, but
instead would be more specific to virtio transport devices.

This commit removes the ioeventfds() method from the PciDevice trait,
adding some convenient helper as_any() to retrieve the Any trait from
the structure behing the PciDevice trait. This is the only way to keep
calling into ioeventfds() function from VirtioPciDevice, so that we can
still properly reprogram the PCI BAR.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-31 09:30:59 +01:00
Samuel Ortiz
3be95dbf93 pci: Remove KVM dependency
The PCI crate should not depend on the KVM crates.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-10-29 20:09:04 -07:00
Sebastien Boeuf
296f2e1182 ci: Add integration test for PCI BAR reprogramming
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
d6c68e4738 pci: Add error propagation to PCI BAR reprogramming
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
3e819ac797 pci: Use a weak reference to the AddressManager
Storing a strong reference to the AddressManager behind the
DeviceRelocation trait results in a cyclic reference count.
Use a weak reference to break that dependency.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
149b61b213 pci: Detect BAR reprogramming
Based on the value being written to the BAR, the implementation can
now detect if the BAR is being moved to another address. If that is the
case, it invokes move_bar() function from the DeviceRelocation trait.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
04a449d3f3 pci: Pass DeviceRelocation to PciBus
In order to trigger the PCI BAR reprogramming from PciConfigIo and
PciConfigMmmio, we need the PciBus to have a hold onto the trait
implementation of DeviceRelocation.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
e93467a96c vmm: Implement DeviceRelocation trait
By implementing the DeviceRelocation trait for the AddressManager
structure, we now have a way to let the PCI BAR reprogramming happen.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
4f8054fa82 pci: Store the type of BAR to return correct address
Based on the type of BAR, we can now provide the correct address related
to a BAR index provided by the caller.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
b51a9e1ef1 pci: Make PciBarRegionType implement PartialEq
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
8746c16593 vmm: Create AddressManager to own SystemAllocator
In order to reuse the SystemAllocator later at runtime, it is moved into
the new structure AddressManager. The goal is to have a hold onto the
SystemAllocator and both IO and MMIO buses so that we can use them
later.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
1870eb4295 devices: Lock the BtreeMap inside to avoid deadlocks
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
733e636f02 devices: Allow for bus range removal and update
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
e536f88012 vfio: Implement move_bar() from PciDevice trait
Everytime a PCI BAR is moved, the KVM regions need to be updated.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
c865f93c9b pci: Extend PciDevice trait with move_bar() function
In order to support PCI BAR reprogramming, the PciDevice trait defines a
new method move_bar() dedicated for taking appropriate action when a BAR
is moved to a different guest address.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
3e37f59933 pci: Add new DeviceRelocation trait
This new trait will allow the VMM to implement the mechanism following a
BAR modification regarding its location in the guest address space.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Sebastien Boeuf
5cc1e73e52 Fix Cargo.lock
Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-29 16:48:02 +01:00
Rob Bradford
05eb567a7c build: Ensure there is a release build artifact for travis to upload
After some of the build changes there was no longer a release artifact
left to be used for the release builds.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-29 15:23:31 +00:00
Samuel Ortiz
75bf240b83 cargo: Move to 0.3.0
Our most recent release.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-10-28 21:32:30 +01:00
dependabot-preview[bot]
be6a1975d2 build(deps): bump serde_derive from 1.0.101 to 1.0.102
Bumps [serde_derive](https://github.com/serde-rs/serde) from 1.0.101 to 1.0.102.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.101...v1.0.102)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-28 07:34:31 +00:00
dependabot-preview[bot]
f27893f822 build(deps): bump vm-memory from 8669369 to 366a907
Bumps [vm-memory](https://github.com/rust-vmm/vm-memory) from `8669369` to `366a907`.
- [Release notes](https://github.com/rust-vmm/vm-memory/releases)
- [Commits](8669369d17...366a907660)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-28 07:17:32 +00:00
dependabot-preview[bot]
696f6cae47 build(deps): bump signal-hook from 0.1.10 to 0.1.11
Bumps [signal-hook](https://github.com/vorner/signal-hook) from 0.1.10 to 0.1.11.
- [Release notes](https://github.com/vorner/signal-hook/releases)
- [Changelog](https://github.com/vorner/signal-hook/blob/master/CHANGELOG.md)
- [Commits](https://github.com/vorner/signal-hook/compare/v0.1.10...v0.1.11)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-28 06:59:16 +00:00
dependabot-preview[bot]
1f7f484f61 build(deps): bump serde from 1.0.101 to 1.0.102
Bumps [serde](https://github.com/serde-rs/serde) from 1.0.101 to 1.0.102.
- [Release notes](https://github.com/serde-rs/serde/releases)
- [Commits](https://github.com/serde-rs/serde/compare/v1.0.101...v1.0.102)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-28 06:28:18 +00:00
dependabot-preview[bot]
4e0b5e8a63 build(deps): bump syn from 1.0.6 to 1.0.7
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.6 to 1.0.7.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.6...1.0.7)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-28 06:27:34 +00:00
dependabot-preview[bot]
c159515e91 build(deps): bump syn from 1.0.5 to 1.0.6
Bumps [syn](https://github.com/dtolnay/syn) from 1.0.5 to 1.0.6.
- [Release notes](https://github.com/dtolnay/syn/releases)
- [Commits](https://github.com/dtolnay/syn/compare/1.0.5...1.0.6)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-27 09:21:34 +00:00
dependabot-preview[bot]
26336363cc build(deps): bump getrandom from 0.1.12 to 0.1.13
Bumps [getrandom](https://github.com/rust-random/getrandom) from 0.1.12 to 0.1.13.
- [Release notes](https://github.com/rust-random/getrandom/releases)
- [Changelog](https://github.com/rust-random/getrandom/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-random/getrandom/compare/v0.1.12...v0.1.13)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-25 13:03:06 +00:00
Rob Bradford
7c2c4fb3fc acpi_tables: aml: Rename to_bytes() to to_aml_bytes()
To avoid a clash with to_bytes() for the unsigned integer types that is
coming in a future release.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
ad60fe110b arch: x86_64: acpi: Mark 64-bit device area uncacheable
This region was erroneously marked as cacheable.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
025f1f9d9b arch: x86_64: acpi: Remove 16-bit PCI range
We don't use this range and it shouldn't be included in our DSDT.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
555ac68ea5 arch: x86_64: acpi: Generate DSDT programatically
This was verified by comparing the ASL from disassembling the DSDT
before and after. All the individual AML components themselves are also
unit tested.

Fixes: #352

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
dd539df633 acpi_tables: sdt: Add ability to add to the table from a slice
The generic version does not work in this case as it the size of the the
&[u8] is not the size of the slice's contents but how much memory the
slice object itself takes up.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
c76fd6df21 acpi_tables: aml: Implement AML Zero, One, Ones
These are special encodings for representing zero, one or all ones in a
single byte.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
9269e40ba5 acpi_tables: aml: Add support for device and scope
These both group a set of AML objects together.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
e1e0ac2ee3 acpi_tables: aml: Add support for creating IO and interrupt resources
As per ACPI spec: "6.4.2.5 I/O Port Descriptor" and "6.4.3.6 Extended
Interrupt Descriptor"

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
08aff4ed5a acpi_tables: aml: Add support for address spaces
Add support for Word/DWord/QWord address spaces for I/O, memory and
buses. Using sensible defaults for infrequently set flags.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
c4c3540a1d acpi_tables: aml: Add resource templates and Memory32Fixed
Add support for generating resource templates (a kind of buffer) along
with generating Memory32Fixed to go into it.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
03d8cdc4f2 acpi_tables: aml: Generate EISA name IDs
EISA names (of the the form UUUNNNN) are encoded into a 32-bit integer.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
3cb73b3a45 acpi_tables: aml: Add Package support
Packages are a way of grouping values together and as such they require
an explicit length which is a variable length encoding calculated with
create_pkg_length().

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
bf0d0d9f9b acpi_tables: aml: Add support for named definitions
Named definitions use op code 0x08 and are used to name some more
complex object.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
5a7076442c acpi_tables: aml: Implement numbers
Add support for the numerical types. By using type aliases the
generation can be very ergonomic as From<T> is implemented.

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Rob Bradford
a4ce596f7b acpi_tables: aml: Add support for generating AML name paths
Root ("\"), single, dual and multi-part names are supported. "^" is not
supported (not widely used.)

Signed-off-by: Rob Bradford <robert.bradford@intel.com>
2019-10-24 10:55:02 +01:00
Samuel Ortiz
1387ac5571 ci: Add cargo audit to the travis pipeline
cargo audit audits Cargo.lock for crates with security vulnerabvilities
reported by the RustSec Advisory Database.

Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-10-23 13:06:29 +03:00
Samuel Ortiz
de9eb3e0fa Bump vmm-sys-utils to 0.2.0
Signed-off-by: Samuel Ortiz <sameo@linux.intel.com>
2019-10-23 11:35:11 +03:00
dependabot-preview[bot]
dc951af167 build(deps): bump c2-chacha from 0.2.2 to 0.2.3
Bumps [c2-chacha](https://github.com/cryptocorrosion/cryptocorrosion) from 0.2.2 to 0.2.3.
- [Release notes](https://github.com/cryptocorrosion/cryptocorrosion/releases)
- [Commits](https://github.com/cryptocorrosion/cryptocorrosion/compare/c2-chacha-0.2.2...c2-chacha-0.2.3)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-21 17:44:17 +00:00
dependabot-preview[bot]
3dff551399 build(deps): bump ppv-lite86 from 0.2.5 to 0.2.6
Bumps [ppv-lite86](https://github.com/cryptocorrosion/cryptocorrosion) from 0.2.5 to 0.2.6.
- [Release notes](https://github.com/cryptocorrosion/cryptocorrosion/releases)
- [Commits](https://github.com/cryptocorrosion/cryptocorrosion/compare/ppv-lite86-0.2.5...ppv-lite86-0.2.6)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-21 17:10:47 +00:00
dependabot-preview[bot]
4783fe7402 build(deps): bump autocfg from 0.1.6 to 0.1.7
Bumps [autocfg](https://github.com/cuviper/autocfg) from 0.1.6 to 0.1.7.
- [Release notes](https://github.com/cuviper/autocfg/releases)
- [Commits](https://github.com/cuviper/autocfg/commits)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-21 04:26:47 +00:00
dependabot-preview[bot]
e10413b96c build(deps): bump proc-macro2 from 1.0.5 to 1.0.6
Bumps [proc-macro2](https://github.com/alexcrichton/proc-macro2) from 1.0.5 to 1.0.6.
- [Release notes](https://github.com/alexcrichton/proc-macro2/releases)
- [Commits](https://github.com/alexcrichton/proc-macro2/compare/1.0.5...1.0.6)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-20 14:30:54 +00:00
dependabot-preview[bot]
317d754946 build(deps): bump ssh2 from 0.4.0 to 0.5.0
Bumps [ssh2](https://github.com/alexcrichton/ssh2-rs) from 0.4.0 to 0.5.0.
- [Release notes](https://github.com/alexcrichton/ssh2-rs/releases)
- [Commits](https://github.com/alexcrichton/ssh2-rs/compare/0.4.0...0.5.0)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-20 14:30:18 +00:00
dependabot-preview[bot]
eff1ece368 build(deps): bump openssl-sys from 0.9.51 to 0.9.52
Bumps [openssl-sys](https://github.com/sfackler/rust-openssl) from 0.9.51 to 0.9.52.
- [Release notes](https://github.com/sfackler/rust-openssl/releases)
- [Commits](https://github.com/sfackler/rust-openssl/compare/openssl-sys-v0.9.51...openssl-sys-v0.9.52)

Signed-off-by: dependabot-preview[bot] <support@dependabot.com>
2019-10-20 14:30:02 +00:00
Sebastien Boeuf
05c7130f06 ci: Update ClearLinux image
A new ClearLinux image has been uploaded to the Azure storage account.
It is based off of the ClearLinux cloudguest image 31310 version, with
two extra bundles added to it.

First bundle is sysadmin-basic to include utility like netcat, and the
second bundle is iperf, adding the iperf binary to the image.

The image is 2G in size.

Signed-off-by: Sebastien Boeuf <sebastien.boeuf@intel.com>
2019-10-18 16:49:46 +01:00
168 changed files with 38816 additions and 21340 deletions

29
.github/workflows/build.yaml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: Cloud Hypervisor Build
on: [pull_request, create]
jobs:
build:
if: github.event_name == 'pull_request'
name: Build
runs-on: ubuntu-latest
strategy:
matrix:
rust:
- stable
- beta
- nightly
target:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
steps:
- name: Code checkout
uses: actions/checkout@v2
- name: Install Rust toolchain (${{ matrix.rust }})
uses: actions-rs/toolchain@v1
with:
toolchain: ${{ matrix.rust }}
target: ${{ matrix.target }}
override: true
- name: Build
run: cargo build --release --target=${{ matrix.target }}

65
.github/workflows/release.yaml vendored Normal file
View File

@@ -0,0 +1,65 @@
name: Cloud Hypervisor Release
on: [create]
jobs:
release:
if: github.event_name == 'create' && github.event.ref_type == 'tag'
name: Release
runs-on: ubuntu-latest
steps:
- name: Code checkout
uses: actions/checkout@v2
- name: Install Rust toolchain (x86_64-unknown-linux-gnu)
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: x86_64-unknown-linux-gnu
- name: Install Rust toolchain (x86_64-unknown-linux-musl)
uses: actions-rs/toolchain@v1
with:
toolchain: stable
target: x86_64-unknown-linux-musl
- name: Build
run: cargo build --release --target=x86_64-unknown-linux-gnu
- name: Static Build
run: cargo build --release --target=x86_64-unknown-linux-musl
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: ${{ github.ref }}
draft: true
prerelease: true
- name: Upload cloud-hypervisor
id: upload-release-cloud-hypervisor
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: target/x86_64-unknown-linux-gnu/release/cloud-hypervisor
asset_name: cloud-hypervisor
asset_content_type: application/octet-stream
- name: Upload static cloud-hypervisor
id: upload-release-static-cloud-hypervisor
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: target/x86_64-unknown-linux-musl/release/cloud-hypervisor
asset_name: cloud-hypervisor-static
asset_content_type: application/octet-stream
- name: Upload ch-remote
id: upload-release-ch-remote
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: target/x86_64-unknown-linux-gnu/release/ch-remote
asset_name: ch-remote
asset_content_type: application/octet-stream

1
.gitignore vendored
View File

@@ -1,3 +1,4 @@
/build
/target
**/*.rs.bk
**/Cargo.lock

1
.rustfmt.toml Normal file
View File

@@ -0,0 +1 @@
edition = "2018"

View File

@@ -1,30 +0,0 @@
language: rust
rust:
- stable
before_script:
- rustup component add clippy
- rustup component add rustfmt
script:
- cargo rustc --bin cloud-hypervisor -- -D warnings
- cargo rustc --bin cloud-hypervisor --no-default-features --features "pci" -- -D warnings
- cargo rustc --bin cloud-hypervisor --no-default-features --features "pci,acpi" -- -D warnings
- cargo rustc --bin cloud-hypervisor --no-default-features --features "mmio" -- -D warnings
- cargo rustc --bin vhost_user_net -- -D warnings
- cargo rustc --bin vhost_user_net --no-default-features --features "pci" -- -D warnings
- cargo rustc --bin vhost_user_net --no-default-features --features "pci,acpi" -- -D warnings
- cargo rustc --bin vhost_user_net --no-default-features --features "mmio" -- -D warnings
- cargo test
- cargo clippy --all-targets --all-features -- -D warnings
- find . -name "*.rs" | xargs rustfmt --check
deploy:
provider: releases
api_key: $GITHUB_OAUTH_TOKEN
file: target/release/cloud-hypervisor
skip_cleanup: true
draft: true
on:
tags: true

View File

@@ -51,7 +51,7 @@ Signed-off-by: Rob Bradford <robert.bradford@intel.com>
Cloud Hypervisor uses the “fork-and-pull” development model. Follow these steps if
you want to merge your changes to `cloud-hypervisor`:
1. Fork the [cloud-hypervisor](https://github.com/intel/cloud-hypervisor) project
1. Fork the [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor) project
into your github organization.
2. Within your fork, create a branch for your contribution.
3. [Create a pull request](https://help.github.com/articles/creating-a-pull-request-from-a-fork/)
@@ -65,7 +65,7 @@ you want to merge your changes to `cloud-hypervisor`:
## Issue tracking
If you have a problem, please let us know. We recommend using
[github issues](https://github.com/intel/cloud-hypervisor/issues/new) for formally
[github issues](https://github.com/cloud-hypervisor/cloud-hypervisor/issues/new) for formally
reporting and documenting them.
To quickly and informally bring something up to us, you can also reach out on [Slack](https://cloud-hypervisor.slack.com).

1398
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,35 +1,41 @@
[package]
name = "cloud-hypervisor"
version = "0.1.0"
version = "0.7.0"
authors = ["The Cloud Hypervisor Authors"]
edition = "2018"
default-run = "cloud-hypervisor"
build = "build.rs"
[dependencies]
clap = "2.33.0"
epoll = "4.1.0"
arc-swap = ">=0.4.4"
clap = { version = "2.33.0", features=["wrap_help"] }
epoll = ">=4.0.1"
futures = { version = "0.3.4", features = ["thread-pool"] }
lazy_static = "1.4.0"
libc = "0.2.65"
libc = "0.2.69"
log = { version = "0.4.8", features = ["std"] }
net_gen = { path = "net_gen" }
net_util = { path = "net_util" }
seccomp = { git = "https://github.com/firecracker-microvm/firecracker", tag = "v0.21.1" }
serde_json = ">=1.0.9"
vhost_user_backend = { path = "vhost_user_backend"}
vhost_user_block = { path = "vhost_user_block"}
vhost_user_fs = { path = "vhost_user_fs"}
vhost_user_net = { path = "vhost_user_net"}
virtio-bindings = "0.1.0"
vmm = { path = "vmm" }
vm-device = { path = "vm-device" }
vm-memory = { git = "https://github.com/rust-vmm/vm-memory" }
vmm-sys-util = "0.1.1"
vm-memory = "0.2.0"
vmm-sys-util = "0.5.0"
vm-virtio = { path = "vm-virtio" }
vhost_rs = { git = "https://github.com/cloud-hypervisor/vhost", branch = "dragonball", package = "vhost", features = ["vhost-user-slave"] }
[dev-dependencies]
ssh2 = "0.4.0"
ssh2 = "0.8.0"
dirs = "2.0.2"
credibility = "0.1.3"
tempdir= "0.3.7"
lazy_static= "1.4.0"
[dependencies.vhost_rs]
path = "vhost_rs"
features = ["vhost-user-slave"]
tempfile = "3.1.0"
serde_json = ">=1.0.9"
[features]
default = ["acpi", "pci", "cmos"]
@@ -37,11 +43,29 @@ acpi = ["vmm/acpi"]
pci = ["vmm/pci_support"]
mmio = ["vmm/mmio_support"]
cmos = ["vmm/cmos"]
fwdebug = ["vmm/fwdebug"]
# Integration tests require a special environment to run in
integration_tests = []
[workspace]
members = [
"arch",
"devices",
"qcow",
"pci",
"vmm",
"vm-virtio",
"vm-device",
"vm-migration",
"vhost_user_block",
"vhost_user_backend",
"vhost_user_fs",
"vhost_user_net",
"vfio",
"net_util",
"acpi_tables",
"arch_gen",
"net_gen",
"vm-allocator",
]

112
Jenkinsfile vendored
View File

@@ -1,22 +1,100 @@
stage ("Builds") {
node ('bionic') {
stage ('Checkout') {
checkout scm
pipeline{
agent none
stages {
stage ('Early checks') {
agent { node { label 'master' } }
stages {
stage ('Check for RFC/WIP builds') {
when {
changeRequest comparator: 'REGEXP', title: '.*(rfc|RFC|wip|WIP).*'
beforeAgent true
}
steps {
error("Failing as this is marked as a WIP or RFC PR.")
}
}
stage ('Cancel older builds') {
when { not { branch 'master' } }
steps {
cancelPreviousBuilds()
}
}
}
}
stage ('Install system packages') {
sh "sudo DEBIAN_FRONTEND=noninteractive apt-get install -yq build-essential mtools libssl-dev pkg-config"
sh "sudo apt-get install -yq flex bison libelf-dev qemu-utils qemu-system libglib2.0-dev libpixman-1-dev libseccomp-dev socat"
}
stage ('Install Rust') {
sh "nohup curl https://sh.rustup.rs -sSf | sh -s -- -y"
}
stage ('Run unit tests') {
sh "scripts/run_unit_tests.sh"
}
stage ('Run integration tests') {
sh "sudo mount -t tmpfs tmpfs /tmp"
sh "scripts/run_integration_tests.sh"
stage ('Build') {
failFast true
parallel {
stage ('Master build') {
agent { node { label 'master' } }
stages {
stage ('Checkout') {
steps {
checkout scm
}
}
stage ('Run Cargo tests') {
steps {
sh "scripts/dev_cli.sh tests --cargo"
}
}
stage ('Run OpenAPI tests') {
steps {
sh "scripts/run_openapi_tests.sh"
}
}
}
}
stage ('Worker build') {
agent { node { label 'bionic' } }
options {
timeout(time: 1, unit: 'HOURS')
}
stages {
stage ('Checkout') {
steps {
checkout scm
}
}
stage ('Run unit tests') {
steps {
sh "scripts/dev_cli.sh tests --unit"
}
}
stage ('Run integration tests') {
steps {
sh "scripts/dev_cli.sh tests --integration"
}
}
stage ('Run unit tests for musl') {
when { branch 'master' }
steps {
sh "scripts/dev_cli.sh tests --unit --libc musl"
}
}
stage ('Run integration tests for musl') {
when { branch 'master' }
steps {
sh "scripts/dev_cli.sh tests --integration --libc musl"
}
}
}
}
}
}
}
}
def cancelPreviousBuilds() {
// Check for other instances of this particular build, cancel any that are older than the current one
def jobName = env.JOB_NAME
def currentBuildNumber = env.BUILD_NUMBER.toInteger()
def currentJob = Jenkins.instance.getItemByFullName(jobName)
// Loop through all instances of this particular job/branch
for (def build : currentJob.builds) {
if (build.isBuilding() && (build.number.toInteger() < currentBuildNumber)) {
echo "Older build still queued. Sending kill signal to build number: ${build.number}"
build.doStop()
}
}
}

View File

@@ -1,4 +1,4 @@
[![Build Status](https://travis-ci.com/intel/cloud-hypervisor.svg?branch=master)](https://travis-ci.com/intel/cloud-hypervisor)
[![Build Status](https://travis-ci.com/cloud-hypervisor/cloud-hypervisor.svg?branch=master)](https://travis-ci.com/cloud-hypervisor/cloud-hypervisor)
1. [What is Cloud Hypervisor?](#1-what-is-cloud-hypervisor)
* [Requirements](#requirements)
@@ -14,6 +14,7 @@
- [Disk image](#disk-image)
- [Booting the guest VM](#booting-the-guest-vm)
3. [Status](#2-status)
* [Device Model](#device-model)
* [TODO](#todo)
4. [rust-vmm dependency](#4-rust-vmm-dependency)
* [Firecracker and crosvm](#firecracker-and-crosvm)
@@ -73,7 +74,7 @@ First you need to clone and build the cloud-hypervisor repo:
```shell
$ pushd $CLOUDH
$ git clone https://github.com/intel/cloud-hypervisor.git
$ git clone https://github.com/cloud-hypervisor/cloud-hypervisor.git
$ cd cloud-hypervisor
$ cargo build --release
@@ -85,6 +86,34 @@ $ popd
This will build a `cloud-hypervisor` binary under `$CLOUDH/cloud-hypervisor/target/release/cloud-hypervisor`.
### Containerized builds and tests
If you want to build and test Cloud Hypervisor without having to install all the
required dependencies (The rust toolchain, cargo tools, etc), you can also use
Cloud Hypervisor's development script: `dev_cli.sh`. Please note that upon its
first invocation, this script will pull a fairly large container image.
For example, to build the Cloud Hypervisor release binary:
```shell
$ pushd $CLOUDH
$ cd cloud-hypervisor
$ ./scripts/dev_cli.sh build --release
```
With `dev_cli.sh`, one can also run the Cloud Hypervisor CI locally. This can be
very convenient for debugging CI errors without having to fully rely on the
Cloud Hypervisor CI infrastructure.
For example, to run the Cloud Hypervisor unit tests:
```shell
$ ./scripts/dev_cli.sh tests --unit
```
Run the `./scripts/dev_cli.sh --help` command to view all the supported
development script commands and their related options.
## Run
You can run a guest VM by either using an existing cloud image or booting into your own kernel and disk image.
@@ -94,7 +123,7 @@ You can run a guest VM by either using an existing cloud image or booting into y
`cloud-hypervisor` supports booting disk images containing all needed
components to run cloud workloads, a.k.a. cloud images. To do that we rely on
the [Rust Hypervisor
Firmware](https://github.com/intel/rust-hypervisor-firmware) project to provide
Firmware](https://github.com/cloud-hypervisor/rust-hypervisor-firmware) project to provide
an ELF
formatted KVM firmware for `cloud-hypervisor` to directly boot into.
@@ -102,9 +131,9 @@ We need to get the latest `rust-hypervisor-firmware` release and also a working
```shell
$ pushd $CLOUDH
$ wget https://download.clearlinux.org/releases/29160/clear/clear-29160-kvm.img.xz
$ unxz clear-29160-kvm.img.xz
$ wget https://github.com/intel/rust-hypervisor-firmware/releases/download/0.2.0/hypervisor-fw
$ wget https://download.clearlinux.org/releases/31890/clear/clear-31890-kvm.img.xz
$ unxz clear-31890-kvm.img.xz
$ wget https://github.com/cloud-hypervisor/rust-hypervisor-firmware/releases/download/0.2.6/hypervisor-fw
$ popd
```
@@ -113,8 +142,8 @@ $ pushd $CLOUDH
$ sudo setcap cap_net_admin+ep ./cloud-hypervisor/target/release/cloud-hypervisor
$ ./cloud-hypervisor/target/release/cloud-hypervisor \
--kernel ./hypervisor-fw \
--disk path=clear-29160-kvm.img \
--cpus 4 \
--disk path=clear-31890-kvm.img \
--cpus boot=4 \
--memory size=1024M \
--net "tap=,mac=,ip=,mask=" \
--rng
@@ -128,18 +157,19 @@ Multiple arguments can be given to the `--disk` parameter.
#### Building your kernel
`cloud-hypervisor` also supports direct kernel boot into a `vmlinux` ELF kernel
image. You want to build such an image first:
image. In order to support virtio-fs and virtio-iommu we have our own development branch. You are of course able to use your own kernel but these instructions will continue with the version that we develop and test against.
To build the kernel:
```shell
# Clone a 5.0 Linux kernel
# Clone the Cloud Hypervisor Linux branch
$ pushd $CLOUDH
$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git linux-cloud-hypervisor
$ cd linux-cloud-hypervisor
$ git reset --hard v5.0
$ git clone --depth 1 https://github.com/cloud-hypervisor/linux.git -b virtio-fs-virtio-iommu-virtio-mem-5.6-rc4 linux-cloud-hypervisor
$ pushd linux-cloud-hypervisor
# Use the cloud-hypervisor kernel config to build your kernel
$ cp $CLOUDH/cloud-hypervisor/resources/linux-5.0-config .config
$ cp $CLOUDH/cloud-hypervisor/resources/linux-config .config
$ make bzImage -j `nproc`
$ popd
```
@@ -152,8 +182,8 @@ For the disk image, we will use a Clear Linux cloud image that contains a root p
```shell
$ pushd $CLOUDH
$ wget https://download.clearlinux.org/releases/29160/clear/clear-29160-kvm.img.xz
$ unxz clear-29160-kvm.img.xz
$ wget https://download.clearlinux.org/releases/31890/clear/clear-31890-kvm.img.xz
$ unxz clear-31890-kvm.img.xz
$ popd
```
@@ -167,9 +197,9 @@ $ pushd $CLOUDH
$ sudo setcap cap_net_admin+ep ./cloud-hypervisor/target/release/cloud-hypervisor
$ ./cloud-hypervisor/target/release/cloud-hypervisor \
--kernel ./linux-cloud-hypervisor/arch/x86/boot/compressed/vmlinux.bin \
--disk path=clear-29160-kvm.img \
--disk path=clear-31890-kvm.img \
--cmdline "console=hvc0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3" \
--cpus 4 \
--cpus boot=4 \
--memory size=1024M \
--net "tap=,mac=,ip=,mask=" \
--rng
@@ -187,27 +217,38 @@ $ ./cloud-hypervisor/target/release/cloud-hypervisor \
--kernel ./linux-cloud-hypervisor/arch/x86/boot/compressed/vmlinux.bin \
--console off \
--serial tty \
--disk path=clear-29160-kvm.img \
--disk path=clear-31890-kvm.img \
--cmdline "console=ttyS0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3" \
--cpus 4 \
--cpus boot=4 \
--memory size=1024M \
--net "tap=,mac=,ip=,mask=" \
--rng
```
# 3. Status
`cloud-hypervisor` is in a very early, pre-alpha stage. Use at your own risk!
As of 2019/05/12, booting cloud images has only been tested with [Clear Linux images](https://download.clearlinux.org/current/).
Direct kernel boot to userspace should work with most rootfs and it's been tested with
Clear Linux root partitions, and also basic initrd/initramfs images.
As of 2020-04-23, the following cloud images are supported:
* [Clear Linux](https://download.clearlinux.org/current/) (cloudguest and kvm)
* [Ubuntu Bionic](https://cloud-images.ubuntu.com/bionic/current/) (cloudimg)
* [Ubuntu Focal](https://cloud-images.ubuntu.com/focal/current/) (cloudimg)
Direct kernel boot to userspace should work with most rootfs.
## Hot Plug
This [document](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/hotplug.md) details how to add devices to
a running VM. Currently only CPU hot plug is supported.
## Device Model
Follow this [documentation](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/device_model.md).
## TODO
We are not tracking the `cloud-hypervisor` TODO list from a specific git tracked file but through
[github issues](https://github.com/intel/cloud-hypervisor/issues/new) instead.
[github issues](https://github.com/cloud-hypervisor/cloud-hypervisor/issues/new) instead.
# 4. `rust-vmm` project dependency

View File

@@ -5,5 +5,5 @@ authors = ["The Cloud Hypervisor Authors"]
edition = "2018"
[dependencies]
vm-memory = { git = "https://github.com/rust-vmm/vm-memory" }
vm-memory = "0.2.0"

1988
acpi_tables/src/aml.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0
//
pub mod aml;
pub mod rsdp;
pub mod sdt;

View File

@@ -36,7 +36,7 @@ impl RSDP {
};
rsdp.checksum = super::generate_checksum(&rsdp.as_slice()[0..19]);
rsdp.extended_checksum = super::generate_checksum(&rsdp.as_slice());;
rsdp.extended_checksum = super::generate_checksum(&rsdp.as_slice());
rsdp
}

View File

@@ -77,6 +77,14 @@ impl SDT {
self.write(orig_length, value);
}
pub fn append_slice(&mut self, data: &[u8]) {
let orig_length = self.data.len();
let new_length = orig_length + data.len();
self.write_u32(4, new_length as u32);
self.data.extend_from_slice(data);
self.update_checksum();
}
/// Write a value at the given offset
pub fn write<T>(&mut self, offset: usize, value: T) {
assert!((offset + (std::mem::size_of::<T>() - 1)) < self.data.len());

View File

@@ -5,24 +5,20 @@ authors = ["The Chromium OS Authors"]
[features]
default = []
acpi = ["acpi_tables"]
[dependencies]
byteorder = "1.3.2"
kvm-bindings = "0.1.1"
kvm-ioctls = { git = "https://github.com/rust-vmm/kvm-ioctls", branch = "master" }
libc = "0.2.60"
byteorder = "1.3.4"
kvm-bindings = { git = "https://github.com/cloud-hypervisor/kvm-bindings", branch = "ch" }
kvm-ioctls = { git = "https://github.com/cloud-hypervisor/kvm-ioctls", branch = "ch" }
libc = "0.2.69"
vm-memory = { version = "0.2.0", features = ["backend-mmap"] }
acpi_tables = { path = "../acpi_tables", optional = true }
arch_gen = { path = "../arch_gen" }
[dependencies.vm-memory]
git = "https://github.com/rust-vmm/vm-memory"
features = ["backend-mmap"]
[dependencies.linux-loader]
git = "https://github.com/rust-vmm/linux-loader"
features = ["elf", "bzimage"]
[dev-dependencies]
rand = "0.7.0"
rand = "0.7.3"

View File

@@ -16,8 +16,7 @@ pub fn configure_system(
_cmdline_addr: GuestAddress,
_cmdline_size: usize,
_num_cpus: u8,
_serial_enabled: bool,
_virt_iommu: Option<(u32, &[u32])>,
_rsdp_addr: Option<GuestAddress>,
) -> super::Result<()> {
Ok(())
}

View File

@@ -1,3 +1,5 @@
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
@@ -22,7 +24,7 @@ extern crate vm_memory;
use std::result;
#[derive(Debug, PartialEq)]
#[derive(Debug)]
pub enum Error {
#[cfg(target_arch = "x86_64")]
/// X86_64 specific error triggered during system configuration.
@@ -30,7 +32,19 @@ pub enum Error {
/// The zero page extends past the end of guest_mem.
ZeroPagePastRamEnd,
/// Error writing the zero page of guest memory.
ZeroPageSetup,
ZeroPageSetup(vm_memory::GuestMemoryError),
/// The memory map table extends past the end of guest memory.
MemmapTablePastRamEnd,
/// Error writing memory map table to guest memory.
MemmapTableSetup,
/// The hvm_start_info structure extends past the end of guest memory.
StartInfoPastRamEnd,
/// Error writing hvm_start_info to guest memory.
StartInfoSetup,
/// Failed to compute initramfs address.
InitramfsAddress,
/// Error writing module entry to guest memory.
ModlistSetup(vm_memory::GuestMemoryError),
}
pub type Result<T> = result::Result<T, Error>;
@@ -66,5 +80,21 @@ pub mod x86_64;
#[cfg(target_arch = "x86_64")]
pub use x86_64::{
arch_memory_regions, configure_system, layout, layout::CMDLINE_MAX_SIZE, layout::CMDLINE_START,
arch_memory_regions, configure_system, initramfs_load_addr, layout, layout::CMDLINE_MAX_SIZE,
layout::CMDLINE_START, regs, BootProtocol, EntryPoint,
};
/// Safe wrapper for `sysconf(_SC_PAGESIZE)`.
#[inline(always)]
fn pagesize() -> usize {
// Trivially safe
unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize }
}
/// Type for passing information about the initramfs in the guest memory.
pub struct InitramfsConfig {
/// Load address of initramfs in guest memory
pub address: vm_memory::GuestAddress,
/// Size of initramfs in guest memory
pub size: usize,
}

View File

@@ -1,484 +0,0 @@
// Copyright © 2019 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use acpi_tables::{
rsdp::RSDP,
sdt::{GenericAddress, SDT},
};
use vm_memory::{GuestAddress, GuestMemoryMmap};
use vm_memory::{Address, ByteValued, Bytes};
use std::convert::TryInto;
use super::layout;
#[repr(packed)]
struct LocalAPIC {
pub r#type: u8,
pub length: u8,
pub processor_id: u8,
pub apic_id: u8,
pub flags: u32,
}
#[repr(packed)]
#[derive(Default)]
struct IOAPIC {
pub r#type: u8,
pub length: u8,
pub ioapic_id: u8,
_reserved: u8,
pub apic_address: u32,
pub gsi_base: u32,
}
#[repr(packed)]
#[derive(Default)]
struct InterruptSourceOverride {
pub r#type: u8,
pub length: u8,
pub bus: u8,
pub source: u8,
pub gsi: u32,
pub flags: u16,
}
#[repr(packed)]
#[derive(Default)]
struct PCIRangeEntry {
pub base_address: u64,
pub segment: u16,
pub start: u8,
pub end: u8,
_reserved: u32,
}
#[repr(packed)]
#[derive(Default)]
struct IortParavirtIommuNode {
pub type_: u8,
pub length: u16,
pub revision: u8,
_reserved1: u32,
pub num_id_mappings: u32,
pub ref_id_mappings: u32,
pub device_id: u32,
_reserved2: [u32; 3],
pub model: u32,
pub flags: u32,
_reserved3: [u32; 4],
}
#[repr(packed)]
#[derive(Default)]
struct IortPciRootComplexNode {
pub type_: u8,
pub length: u16,
pub revision: u8,
_reserved1: u32,
pub num_id_mappings: u32,
pub ref_id_mappings: u32,
pub mem_access_props: IortMemoryAccessProperties,
pub ats_attr: u32,
pub pci_seg_num: u32,
pub mem_addr_size_limit: u8,
_reserved2: [u8; 3],
}
#[repr(packed)]
#[derive(Default)]
struct IortMemoryAccessProperties {
pub cca: u32,
pub ah: u8,
_reserved: u16,
pub maf: u8,
}
#[repr(packed)]
#[derive(Default)]
struct IortIdMapping {
pub input_base: u32,
pub num_of_ids: u32,
pub ouput_base: u32,
pub output_ref: u32,
pub flags: u32,
}
pub fn create_dsdt_table(
serial_enabled: bool,
start_of_device_area: GuestAddress,
end_of_device_area: GuestAddress,
) -> SDT {
/*
The hex tables in this file are generated from the ASL below with:
"iasl -tc <dsdt.asl>"
As the output contains a table header that is not required the first 36 bytes
should be disregarded.
*/
/*
Device (_SB.PCI0)
{
Name (_HID, EisaId ("PNP0A08") /* PCI Express Bus */) // _HID: Hardware ID
Name (_CID, EisaId ("PNP0A03") /* PCI Bus */) // _CID: Compatible ID
Name (_ADR, Zero) // _ADR: Address
Name (_SEG, Zero) // _SEG: PCI Segment
Name (_UID, Zero) // _UID: Unique ID
Name (SUPP, Zero)
}
Scope (_SB.PCI0)
{
Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
{
WordBusNumber (ResourceProducer, MinFixed, MaxFixed, PosDecode,
0x0000, // Granularity
0x0000, // Range Minimum
0x00FF, // Range Maximum
0x0000, // Translation Offset
0x0100, // Length
,, )
IO (Decode16,
0x0CF8, // Range Minimum
0x0CF8, // Range Maximum
0x01, // Alignment
0x08, // Length
)
WordIO (ResourceProducer, MinFixed, MaxFixed, PosDecode, EntireRange,
0x0000, // Granularity
0x0000, // Range Minimum
0x0CF7, // Range Maximum
0x0000, // Translation Offset
0x0CF8, // Length
,, , TypeStatic, DenseTranslation)
WordIO (ResourceProducer, MinFixed, MaxFixed, PosDecode, EntireRange,
0x0000, // Granularity
0x0D00, // Range Minimum
0xFFFF, // Range Maximum
0x0000, // Translation Offset
0xF300, // Length
,, , TypeStatic, DenseTranslation)
DWordMemory (ResourceProducer, PosDecode, MinFixed, MaxFixed, Cacheable, ReadWrite,
0x00000000, // Granularity
0x000A0000, // Range Minimum
0x000BFFFF, // Range Maximum
0x00000000, // Translation Offset
0x00020000, // Length
,, , AddressRangeMemory, TypeStatic)
DWordMemory (ResourceProducer, PosDecode, MinFixed, MaxFixed, NonCacheable, ReadWrite,
0x00000000, // Granularity
0xC0000000, // Range Minimum
0xFEBFFFFF, // Range Maximum
0x00000000, // Translation Offset
0x3EC00000, // Length
,, , AddressRangeMemory, TypeStatic)
QWordMemory (ResourceProducer, PosDecode, MinFixed, MaxFixed, Cacheable, ReadWrite,
0x0000000000000000, // Granularity
0x0000000800000000, // Range Minimum
0x0000000FFFFFFFFF, // Range Maximum
0x0000000000000000, // Translation Offset
0x0000000800000000, // Length
,, , AddressRangeMemory, TypeStatic)
})
}
*/
let mut pci_dsdt_data = [
0x5Bu8, 0x82, 0x36, 0x2E, 0x5F, 0x53, 0x42, 0x5F, 0x50, 0x43, 0x49, 0x30, 0x08, 0x5F, 0x48,
0x49, 0x44, 0x0C, 0x41, 0xD0, 0x0A, 0x08, 0x08, 0x5F, 0x43, 0x49, 0x44, 0x0C, 0x41, 0xD0,
0x0A, 0x03, 0x08, 0x5F, 0x41, 0x44, 0x52, 0x00, 0x08, 0x5F, 0x53, 0x45, 0x47, 0x00, 0x08,
0x5F, 0x55, 0x49, 0x44, 0x00, 0x08, 0x53, 0x55, 0x50, 0x50, 0x00, 0x10, 0x41, 0x0B, 0x2E,
0x5F, 0x53, 0x42, 0x5F, 0x50, 0x43, 0x49, 0x30, 0x08, 0x5F, 0x43, 0x52, 0x53, 0x11, 0x40,
0x0A, 0x0A, 0x9C, 0x88, 0x0D, 0x00, 0x02, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00,
0x00, 0x00, 0x00, 0x01, 0x47, 0x01, 0xF8, 0x0C, 0xF8, 0x0C, 0x01, 0x08, 0x88, 0x0D, 0x00,
0x01, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0xF7, 0x0C, 0x00, 0x00, 0xF8, 0x0C, 0x88, 0x0D,
0x00, 0x01, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x0D, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0xF3, 0x87,
0x17, 0x00, 0x00, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0xFF, 0xFF,
0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x87, 0x17, 0x00, 0x00, 0x0C,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0xFF, 0xBF, 0xFE, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0xC0, 0x3E, 0x8A, 0x2B, 0x00, 0x00, 0x0C, 0x03, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0xFF, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x79, 0x00,
];
// Patch Range Minimum/Range Maximum/Length for the the 64-bit device area
pci_dsdt_data[170..174].copy_from_slice(&layout::MEM_32BIT_DEVICES_START.0.to_le_bytes()[0..4]);
pci_dsdt_data[174..178].copy_from_slice(
&(layout::MEM_32BIT_DEVICES_START.0 + layout::MEM_32BIT_DEVICES_SIZE - 1).to_le_bytes()
[0..4],
);
pci_dsdt_data[182..186].copy_from_slice(&layout::MEM_32BIT_DEVICES_SIZE.to_le_bytes()[0..4]);
// Patch the Range Minimum/Range Maximum/Length for the the 64-bit device area
pci_dsdt_data[200..208].copy_from_slice(&(start_of_device_area.0).to_le_bytes());
pci_dsdt_data[208..216].copy_from_slice(&end_of_device_area.0.to_le_bytes());
pci_dsdt_data[224..232].copy_from_slice(
&(end_of_device_area.unchecked_offset_from(start_of_device_area) + 1).to_le_bytes(),
);
/*
Device (_SB.MBRD)
{
Name (_HID, EisaId ("PNP0C02") /* PNP Motherboard Resources */) // _HID: Hardware ID
Name (_UID, Zero) // _UID: Unique ID
}
Scope (_SB.MBRD)
{
Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
{
Memory32Fixed (ReadWrite,
0xE8000000, // Address Base
0x10000000, // Address Length
)
})
}
*/
let mut mbrd_dsdt_data = [
0x5Bu8, 0x82, 0x1A, 0x2E, 0x5F, 0x53, 0x42, 0x5F, 0x4D, 0x42, 0x52, 0x44, 0x08, 0x5F, 0x48,
0x49, 0x44, 0x0C, 0x41, 0xD0, 0x0C, 0x02, 0x08, 0x5F, 0x55, 0x49, 0x44, 0x00, 0x10, 0x21,
0x2E, 0x5F, 0x53, 0x42, 0x5F, 0x4D, 0x42, 0x52, 0x44, 0x08, 0x5F, 0x43, 0x52, 0x53, 0x11,
0x11, 0x0A, 0x0E, 0x86, 0x09, 0x00, 0x01, 0x00, 0x00, 0x00, 0xE8, 0x00, 0x00, 0x00, 0x10,
0x79, 0x00,
];
mbrd_dsdt_data[52..56].copy_from_slice(&layout::PCI_MMCONFIG_START.0.to_le_bytes()[0..4]);
mbrd_dsdt_data[56..60].copy_from_slice(&layout::PCI_MMCONFIG_SIZE.to_le_bytes()[0..4]);
/*
Device (_SB.COM1)
{
Name (_HID, EisaId ("PNP0501") /* 16550A-compatible COM Serial Port */) // _HID: Hardware ID
Name (_UID, Zero) // _UID: Unique ID
Name (_CRS, ResourceTemplate () // _CRS: Current Resource Settings
{
Interrupt (ResourceConsumer, Edge, ActiveHigh, Exclusive, ,, )
{
0x00000004,
}
IO (Decode16,
0x03F8, // Range Minimum
0x03F8, // Range Maximum
0x00, // Alignment
0x08, // Length
)
})
}
*/
let com1_dsdt_data = [
0x5Bu8, 0x82, 0x36, 0x2E, 0x5F, 0x53, 0x42, 0x5F, 0x43, 0x4F, 0x4D, 0x31, 0x08, 0x5F, 0x48,
0x49, 0x44, 0x0C, 0x41, 0xD0, 0x05, 0x01, 0x08, 0x5F, 0x55, 0x49, 0x44, 0x00, 0x08, 0x5F,
0x43, 0x52, 0x53, 0x11, 0x16, 0x0A, 0x13, 0x89, 0x06, 0x00, 0x03, 0x01, 0x04, 0x00, 0x00,
0x00, 0x47, 0x01, 0xF8, 0x03, 0xF8, 0x03, 0x00, 0x08, 0x79, 0x00,
];
/*
Name (\_S5, Package (0x01) // _S5_: S5 System State
{
0x05
})
*/
let s5_sleep_data = [0x08u8, 0x5F, 0x53, 0x35, 0x5F, 0x12, 0x04, 0x01, 0x0A, 0x05];
// DSDT
let mut dsdt = SDT::new(*b"DSDT", 36, 6, *b"CLOUDH", *b"CHDSDT ", 1);
dsdt.append(pci_dsdt_data);
dsdt.append(mbrd_dsdt_data);
if serial_enabled {
dsdt.append(com1_dsdt_data);
}
dsdt.append(s5_sleep_data);
dsdt
}
pub fn create_acpi_tables(
guest_mem: &GuestMemoryMmap,
num_cpus: u8,
serial_enabled: bool,
start_of_device_area: GuestAddress,
end_of_device_area: GuestAddress,
virt_iommu: Option<(u32, &[u32])>,
) -> GuestAddress {
// RSDP is at the EBDA
let rsdp_offset = layout::RSDP_POINTER;
let mut tables: Vec<u64> = Vec::new();
// DSDT
let dsdt = create_dsdt_table(serial_enabled, start_of_device_area, end_of_device_area);
let dsdt_offset = rsdp_offset.checked_add(RSDP::len() as u64).unwrap();
guest_mem
.write_slice(dsdt.as_slice(), dsdt_offset)
.expect("Error writing DSDT table");
// FACP aka FADT
// Revision 6 of the ACPI FADT table is 276 bytes long
let mut facp = SDT::new(*b"FACP", 276, 6, *b"CLOUDH", *b"CHFACP ", 1);
// HW_REDUCED_ACPI and RESET_REG_SUP
let fadt_flags: u32 = 1 << 20 | 1 << 10;
facp.write(112, fadt_flags);
// RESET_REG
facp.write(116, GenericAddress::io_port_address(0x3c0));
// RESET_VALUE
facp.write(128, 1u8);
facp.write(131, 3u8); // FADT minor version
facp.write(140, dsdt_offset.0); // X_DSDT
// SLEEP_CONTROL_REG
facp.write(244, GenericAddress::io_port_address(0x3c0));
// SLEEP_STATUS_REG
facp.write(256, GenericAddress::io_port_address(0x3c0));
facp.write(268, b"CLOUDHYP"); // Hypervisor Vendor Identity
facp.update_checksum();
let facp_offset = dsdt_offset.checked_add(dsdt.len() as u64).unwrap();
guest_mem
.write_slice(facp.as_slice(), facp_offset)
.expect("Error writing FACP table");
tables.push(facp_offset.0);
// MADT
let mut madt = SDT::new(*b"APIC", 44, 5, *b"CLOUDH", *b"CHMADT ", 1);
madt.write(36, layout::APIC_START);
for cpu in 0..num_cpus {
let lapic = LocalAPIC {
r#type: 0,
length: 8,
processor_id: cpu,
apic_id: cpu,
flags: 1,
};
madt.append(lapic);
}
madt.append(IOAPIC {
r#type: 1,
length: 12,
ioapic_id: 0,
apic_address: layout::IOAPIC_START.0 as u32,
gsi_base: 0,
..Default::default()
});
madt.append(InterruptSourceOverride {
r#type: 2,
length: 10,
bus: 0,
source: 4,
gsi: 4,
flags: 0,
});
let madt_offset = facp_offset.checked_add(facp.len() as u64).unwrap();
guest_mem
.write_slice(madt.as_slice(), madt_offset)
.expect("Error writing MADT table");
tables.push(madt_offset.0);
// MCFG
let mut mcfg = SDT::new(*b"MCFG", 36, 1, *b"CLOUDH", *b"CHMCFG ", 1);
// MCFG reserved 8 bytes
mcfg.append(0u64);
// 32-bit PCI enhanced configuration mechanism
mcfg.append(PCIRangeEntry {
base_address: layout::PCI_MMCONFIG_START.0,
segment: 0,
start: 0,
end: 0xff,
..Default::default()
});
let mcfg_offset = madt_offset.checked_add(madt.len() as u64).unwrap();
guest_mem
.write_slice(mcfg.as_slice(), mcfg_offset)
.expect("Error writing MCFG table");
tables.push(mcfg_offset.0);
let (prev_tbl_len, prev_tbl_off) = if let Some((iommu_id, dev_ids)) = &virt_iommu {
// IORT
let mut iort = SDT::new(*b"IORT", 36, 1, *b"CLOUDH", *b"CHIORT ", 1);
// IORT number of nodes
iort.append(2u32);
// IORT offset to array of IORT nodes
iort.append(48u32);
// IORT reserved 4 bytes
iort.append(0u32);
// IORT paravirtualized IOMMU node
iort.append(IortParavirtIommuNode {
type_: 128,
length: 56,
revision: 0,
num_id_mappings: 0,
ref_id_mappings: 56,
device_id: *iommu_id,
model: 1,
..Default::default()
});
let num_entries = dev_ids.len();
let length: u16 = (36 + (20 * num_entries)).try_into().unwrap();
// IORT PCI root complex node
iort.append(IortPciRootComplexNode {
type_: 2,
length,
revision: 0,
num_id_mappings: num_entries as u32,
ref_id_mappings: 36,
ats_attr: 0,
pci_seg_num: 0,
mem_addr_size_limit: 255,
..Default::default()
});
for dev_id in dev_ids.iter() {
// IORT ID mapping
iort.append(IortIdMapping {
input_base: *dev_id,
num_of_ids: 1,
ouput_base: *dev_id,
output_ref: 48,
flags: 0,
});
}
let iort_offset = mcfg_offset.checked_add(mcfg.len() as u64).unwrap();
guest_mem
.write_slice(iort.as_slice(), iort_offset)
.expect("Error writing IORT table");
tables.push(iort_offset.0);
(iort.len(), iort_offset)
} else {
(mcfg.len(), mcfg_offset)
};
// XSDT
let mut xsdt = SDT::new(*b"XSDT", 36, 1, *b"CLOUDH", *b"CHXSDT ", 1);
for table in tables {
xsdt.append(table);
}
xsdt.update_checksum();
let xsdt_offset = prev_tbl_off.checked_add(prev_tbl_len as u64).unwrap();
guest_mem
.write_slice(xsdt.as_slice(), xsdt_offset)
.expect("Error writing XSDT table");
// RSDP
let rsdp = RSDP::new(*b"CLOUDH", xsdt_offset.0);
guest_mem
.write_slice(rsdp.as_slice(), rsdp_offset)
.expect("Error writing RSDP");
rsdp_offset
}

View File

@@ -1,3 +1,5 @@
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@@ -11,21 +13,47 @@ use kvm_bindings::kvm_segment;
/// Constructor for a conventional segment GDT (or LDT) entry. Derived from the kernel's segment.h.
pub fn gdt_entry(flags: u16, base: u32, limit: u32) -> u64 {
((((base as u64) & 0xff000000u64) << (56 - 24))
(((base as u64) & 0xff000000u64) << (56 - 24))
| (((flags as u64) & 0x0000f0ffu64) << 40)
| (((limit as u64) & 0x000f0000u64) << (48 - 16))
| (((base as u64) & 0x00ffffffu64) << 16)
| ((limit as u64) & 0x0000ffffu64))
| ((limit as u64) & 0x0000ffffu64)
}
fn get_base(entry: u64) -> u64 {
((((entry) & 0xFF00000000000000) >> 32)
(((entry) & 0xFF00000000000000) >> 32)
| (((entry) & 0x000000FF00000000) >> 16)
| (((entry) & 0x00000000FFFF0000) >> 16))
| (((entry) & 0x00000000FFFF0000) >> 16)
}
// Extract the segment limit from the GDT segment descriptor.
//
// In a segment descriptor, the limit field is 20 bits, so it can directly describe
// a range from 0 to 0xFFFFF (1MByte). When G flag is set (4-KByte page granularity) it
// scales the value in the limit field by a factor of 2^12 (4Kbytes), making the effective
// limit range from 0xFFF (4 KBytes) to 0xFFFF_FFFF (4 GBytes).
//
// However, the limit field in the VMCS definition is a 32 bit field, and the limit value is not
// automatically scaled using the G flag. This means that for a desired range of 4GB for a
// given segment, its limit must be specified as 0xFFFF_FFFF. Therefore the method of obtaining
// the limit from the GDT entry is not sufficient, since it only provides 20 bits when 32 bits
// are necessary. Fortunately, we can check if the G flag is set when extracting the limit since
// the full GDT entry is passed as an argument, and perform the scaling of the limit value to
// return the full 32 bit value.
//
// The scaling mentioned above is required when using PVH boot, since the guest boots in protected
// (32-bit) mode and must be able to access the entire 32-bit address space. It does not cause issues
// for the case of direct boot to 64-bit (long) mode, since in 64-bit mode the processor does not
// perform runtime limit checking on code or data segments.
fn get_limit(entry: u64) -> u32 {
((((entry) & 0x000F000000000000) >> 32) | ((entry) & 0x000000000000FFFF)) as u32
let limit: u32 =
((((entry) & 0x000F000000000000) >> 32) | ((entry) & 0x000000000000FFFF)) as u32;
// Perform manual limit scaling if G flag is set
match get_g(entry) {
0 => limit,
_ => ((limit << 12) | 0xFFF), // G flag is either 0 or 1
}
}
fn get_g(entry: u64) -> u8 {
@@ -109,7 +137,7 @@ mod tests {
assert_eq!(0xB, seg.type_);
// base and limit
assert_eq!(0x100000, seg.base);
assert_eq!(0xfffff, seg.limit);
assert_eq!(0xffffffff, seg.limit);
assert_eq!(0x0, seg.unusable);
}
}

View File

@@ -5,7 +5,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
use std::io::{self, Cursor};
use std::io::Cursor;
use std::mem;
use std::result;
@@ -16,8 +16,8 @@ use kvm_ioctls;
#[derive(Debug)]
pub enum Error {
GetLapic(io::Error),
SetLapic(io::Error),
GetLapic(kvm_ioctls::Error),
SetLapic(kvm_ioctls::Error),
}
pub type Result<T> = result::Result<T, Error>;
@@ -55,7 +55,7 @@ fn set_klapic_reg(klapic: &mut kvm_lapic_state, reg_offset: usize, value: u32) {
}
fn set_apic_delivery_mode(reg: u32, mode: u32) -> u32 {
(((reg) & !0x700) | ((mode) << 8))
((reg) & !0x700) | ((mode) << 8)
}
/// Configures LAPICs. LAPIC0 is set for external interrupts, LAPIC1 is set for NMI.

View File

@@ -1,3 +1,5 @@
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@@ -26,6 +28,17 @@ pub const LOW_RAM_START: GuestAddress = GuestAddress(0x0);
pub const BOOT_GDT_START: GuestAddress = GuestAddress(0x500);
pub const BOOT_IDT_START: GuestAddress = GuestAddress(0x520);
/// Address for the hvm_start_info struct used in PVH boot
pub const PVH_INFO_START: GuestAddress = GuestAddress(0x6000);
/// Starting address of array of modules of hvm_modlist_entry type.
/// Used to enable initrd support using the PVH boot ABI.
pub const MODLIST_START: GuestAddress = GuestAddress(0x6040);
/// Address of memory map table used in PVH boot. Can overlap
/// with the zero page address since they are mutually exclusive.
pub const MEMMAP_START: GuestAddress = GuestAddress(0x7000);
/// The 'zero page', a.k.a linux kernel bootparams.
pub const ZERO_PAGE_START: GuestAddress = GuestAddress(0x7000);
@@ -65,18 +78,18 @@ pub const HIGH_RAM_START: GuestAddress = GuestAddress(0x100000);
// ** 32-bit reserved area (start: 3GiB, length: 1GiB) **
pub const MEM_32BIT_RESERVED_START: GuestAddress = GuestAddress(0xc000_0000);
pub const MEM_32BIT_RESERVED_SIZE: GuestUsize = (1024 << 20);
pub const MEM_32BIT_RESERVED_SIZE: GuestUsize = 1024 << 20;
// == Fixed constants within the "32-bit reserved" range ==
// Sub range: 32-bit PCI devices (start: 3GiB, length: 640Mib)
pub const MEM_32BIT_DEVICES_START: GuestAddress = MEM_32BIT_RESERVED_START;
pub const MEM_32BIT_DEVICES_SIZE: GuestUsize = (640 << 20);
pub const MEM_32BIT_DEVICES_SIZE: GuestUsize = 640 << 20;
// PCI MMCONFIG space (start: after the device space, length: 256MiB)
pub const PCI_MMCONFIG_START: GuestAddress =
GuestAddress(MEM_32BIT_DEVICES_START.0 + MEM_32BIT_DEVICES_SIZE);
pub const PCI_MMCONFIG_SIZE: GuestUsize = (256 << 20);
pub const PCI_MMCONFIG_SIZE: GuestUsize = 256 << 20;
// IOAPIC
pub const IOAPIC_START: GuestAddress = GuestAddress(0xfec0_0000);

View File

@@ -1,3 +1,5 @@
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@@ -5,25 +7,74 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
#[cfg(feature = "acpi")]
mod acpi;
mod gdt;
pub mod interrupts;
pub mod layout;
mod mptable;
pub mod regs;
use crate::InitramfsConfig;
use crate::RegionType;
use linux_loader::loader::bootparam::{boot_params, setup_header};
use linux_loader::loader::elf::start_info::{
hvm_memmap_table_entry, hvm_modlist_entry, hvm_start_info,
};
use std::mem;
use vm_memory::{
Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap, GuestUsize,
Address, ByteValued, Bytes, GuestAddress, GuestMemory, GuestMemoryMmap, GuestMemoryRegion,
GuestUsize,
};
#[derive(Debug, Copy, Clone)]
pub enum BootProtocol {
LinuxBoot,
PvhBoot,
}
impl ::std::fmt::Display for BootProtocol {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
match self {
BootProtocol::LinuxBoot => write!(f, "Linux 64-bit boot protocol"),
BootProtocol::PvhBoot => write!(f, "PVH boot protocol"),
}
}
}
#[derive(Debug, Copy, Clone)]
/// Specifies the entry point address where the guest must start
/// executing code, as well as which of the supported boot protocols
/// is to be used to configure the guest initial state.
pub struct EntryPoint {
/// Address in guest memory where the guest must start execution
pub entry_addr: GuestAddress,
/// Specifies which boot protocol to use
pub protocol: BootProtocol,
}
const E820_RAM: u32 = 1;
const E820_RESERVED: u32 = 2;
// This is a workaround to the Rust enforcement specifying that any implementation of a foreign
// trait (in this case `DataInit`) where:
// * the type that is implementing the trait is foreign or
// * all of the parameters being passed to the trait (if there are any) are also foreign
// is prohibited.
#[derive(Copy, Clone, Default)]
struct StartInfoWrapper(hvm_start_info);
// It is safe to initialize StartInfoWrapper which is a wrapper over `hvm_start_info` (a series of ints).
unsafe impl ByteValued for StartInfoWrapper {}
#[derive(Copy, Clone, Default)]
struct MemmapTableEntryWrapper(hvm_memmap_table_entry);
unsafe impl ByteValued for MemmapTableEntryWrapper {}
#[derive(Copy, Clone, Default)]
struct ModlistEntryWrapper(hvm_modlist_entry);
unsafe impl ByteValued for ModlistEntryWrapper {}
// This is a workaround to the Rust enforcement specifying that any implementation of a foreign
// trait (in this case `DataInit`) where:
// * the type that is implementing the trait is foreign or
@@ -35,7 +86,7 @@ struct BootParamsWrapper(boot_params);
// It is safe to initialize BootParamsWrap which is a wrapper over `boot_params` (a series of ints).
unsafe impl ByteValued for BootParamsWrapper {}
#[derive(Debug, PartialEq)]
#[derive(Debug)]
pub enum Error {
/// Invalid e820 setup params.
E820Configuration,
@@ -109,38 +160,210 @@ pub fn configure_system(
guest_mem: &GuestMemoryMmap,
cmdline_addr: GuestAddress,
cmdline_size: usize,
initramfs: &Option<InitramfsConfig>,
num_cpus: u8,
setup_hdr: Option<setup_header>,
_serial_enabled: bool,
_end_of_range: GuestAddress,
_virt_iommu: Option<(u32, &[u32])>,
rsdp_addr: Option<GuestAddress>,
boot_prot: BootProtocol,
) -> super::Result<()> {
// Note that this puts the mptable at the last 1k of Linux's 640k base RAM
mptable::setup_mptable(guest_mem, num_cpus).map_err(Error::MpTableSetup)?;
match boot_prot {
BootProtocol::PvhBoot => {
configure_pvh(guest_mem, cmdline_addr, initramfs, rsdp_addr)?;
}
BootProtocol::LinuxBoot => {
configure_64bit_boot(
guest_mem,
cmdline_addr,
cmdline_size,
initramfs,
setup_hdr,
rsdp_addr,
)?;
}
}
Ok(())
}
fn configure_pvh(
guest_mem: &GuestMemoryMmap,
cmdline_addr: GuestAddress,
initramfs: &Option<InitramfsConfig>,
rsdp_addr: Option<GuestAddress>,
) -> super::Result<()> {
const XEN_HVM_START_MAGIC_VALUE: u32 = 0x336ec578;
let mut start_info: StartInfoWrapper = StartInfoWrapper(hvm_start_info::default());
start_info.0.magic = XEN_HVM_START_MAGIC_VALUE;
start_info.0.version = 1; // pvh has version 1
start_info.0.nr_modules = 0;
start_info.0.cmdline_paddr = cmdline_addr.raw_value() as u64;
start_info.0.memmap_paddr = layout::MEMMAP_START.raw_value();
if let Some(rsdp_addr) = rsdp_addr {
start_info.0.rsdp_paddr = rsdp_addr.0;
}
if let Some(initramfs_config) = initramfs {
// The initramfs has been written to guest memory already, here we just need to
// create the module structure that describes it.
let ramdisk_mod: ModlistEntryWrapper = ModlistEntryWrapper(hvm_modlist_entry {
paddr: initramfs_config.address.raw_value(),
size: initramfs_config.size as u64,
..Default::default()
});
start_info.0.nr_modules += 1;
start_info.0.modlist_paddr = layout::MODLIST_START.raw_value();
// Write the modlist struct to guest memory.
guest_mem
.write_obj(ramdisk_mod, layout::MODLIST_START)
.map_err(super::Error::ModlistSetup)?;
}
// Vector to hold the memory maps which needs to be written to guest memory
// at MEMMAP_START after all of the mappings are recorded.
let mut memmap: Vec<hvm_memmap_table_entry> = Vec::new();
// Create the memory map entries.
add_memmap_entry(&mut memmap, 0, layout::EBDA_START.raw_value(), E820_RAM)?;
let mem_end = guest_mem.last_addr();
if mem_end < layout::MEM_32BIT_RESERVED_START {
add_memmap_entry(
&mut memmap,
layout::HIGH_RAM_START.raw_value(),
mem_end.unchecked_offset_from(layout::HIGH_RAM_START) + 1,
E820_RAM,
)?;
} else {
add_memmap_entry(
&mut memmap,
layout::HIGH_RAM_START.raw_value(),
layout::MEM_32BIT_RESERVED_START.unchecked_offset_from(layout::HIGH_RAM_START),
E820_RAM,
)?;
if mem_end > layout::RAM_64BIT_START {
add_memmap_entry(
&mut memmap,
layout::RAM_64BIT_START.raw_value(),
mem_end.unchecked_offset_from(layout::RAM_64BIT_START) + 1,
E820_RAM,
)?;
}
}
add_memmap_entry(
&mut memmap,
layout::PCI_MMCONFIG_START.0,
layout::PCI_MMCONFIG_SIZE,
E820_RESERVED,
)?;
start_info.0.memmap_entries = memmap.len() as u32;
// Copy the vector with the memmap table to the MEMMAP_START address
// which is already saved in the memmap_paddr field of hvm_start_info struct.
let mut memmap_start_addr = layout::MEMMAP_START;
guest_mem
.checked_offset(
memmap_start_addr,
mem::size_of::<hvm_memmap_table_entry>() * start_info.0.memmap_entries as usize,
)
.ok_or(super::Error::MemmapTablePastRamEnd)?;
// For every entry in the memmap vector, create a MemmapTableEntryWrapper
// and write it to guest memory.
for memmap_entry in memmap {
let map_entry_wrapper: MemmapTableEntryWrapper = MemmapTableEntryWrapper(memmap_entry);
guest_mem
.write_obj(map_entry_wrapper, memmap_start_addr)
.map_err(|_| super::Error::MemmapTableSetup)?;
memmap_start_addr =
memmap_start_addr.unchecked_add(mem::size_of::<hvm_memmap_table_entry>() as u64);
}
// The hvm_start_info struct itself must be stored at PVH_START_INFO
// address, and %rbx will be initialized to contain PVH_INFO_START prior to
// starting the guest, as required by the PVH ABI.
let start_info_addr = layout::PVH_INFO_START;
guest_mem
.checked_offset(start_info_addr, mem::size_of::<hvm_start_info>())
.ok_or(super::Error::StartInfoPastRamEnd)?;
// Write the start_info struct to guest memory.
guest_mem
.write_obj(start_info, start_info_addr)
.map_err(|_| super::Error::StartInfoSetup)?;
Ok(())
}
fn add_memmap_entry(
memmap: &mut Vec<hvm_memmap_table_entry>,
addr: u64,
size: u64,
mem_type: u32,
) -> Result<(), Error> {
// Add the table entry to the vector
memmap.push(hvm_memmap_table_entry {
addr,
size,
type_: mem_type,
reserved: 0,
});
Ok(())
}
fn configure_64bit_boot(
guest_mem: &GuestMemoryMmap,
cmdline_addr: GuestAddress,
cmdline_size: usize,
initramfs: &Option<InitramfsConfig>,
setup_hdr: Option<setup_header>,
rsdp_addr: Option<GuestAddress>,
) -> super::Result<()> {
const KERNEL_BOOT_FLAG_MAGIC: u16 = 0xaa55;
const KERNEL_HDR_MAGIC: u32 = 0x53726448;
const KERNEL_LOADER_OTHER: u8 = 0xff;
const KERNEL_MIN_ALIGNMENT_BYTES: u32 = 0x1000000; // Must be non-zero.
// Note that this puts the mptable at the last 1k of Linux's 640k base RAM
mptable::setup_mptable(guest_mem, num_cpus).map_err(Error::MpTableSetup)?;
let mut params: BootParamsWrapper = BootParamsWrapper(boot_params::default());
if let Some(hdr) = setup_hdr {
// We should use the header if the loader provides one (e.g. from a bzImage).
params.0.hdr = hdr;
params.0.hdr.cmd_line_ptr = cmdline_addr.raw_value() as u32;
params.0.hdr.cmdline_size = cmdline_size as u32;
} else {
params.0.hdr.type_of_loader = KERNEL_LOADER_OTHER;
params.0.hdr.boot_flag = KERNEL_BOOT_FLAG_MAGIC;
params.0.hdr.header = KERNEL_HDR_MAGIC;
params.0.hdr.cmd_line_ptr = cmdline_addr.raw_value() as u32;
params.0.hdr.cmdline_size = cmdline_size as u32;
params.0.hdr.kernel_alignment = KERNEL_MIN_ALIGNMENT_BYTES;
};
// Common bootparams settings
if params.0.hdr.type_of_loader == 0 {
params.0.hdr.type_of_loader = KERNEL_LOADER_OTHER;
}
params.0.hdr.cmd_line_ptr = cmdline_addr.raw_value() as u32;
params.0.hdr.cmdline_size = cmdline_size as u32;
if let Some(initramfs_config) = initramfs {
params.0.hdr.ramdisk_image = initramfs_config.address.raw_value() as u32;
params.0.hdr.ramdisk_size = initramfs_config.size as u32;
}
add_e820_entry(&mut params.0, 0, layout::EBDA_START.raw_value(), E820_RAM)?;
let mem_end = guest_mem.end_addr();
let mem_end = guest_mem.last_addr();
if mem_end < layout::MEM_32BIT_RESERVED_START {
add_e820_entry(
&mut params.0,
@@ -172,21 +395,7 @@ pub fn configure_system(
E820_RESERVED,
)?;
#[cfg(feature = "acpi")]
{
let start_of_device_area = if mem_end < layout::MEM_32BIT_RESERVED_START {
layout::RAM_64BIT_START
} else {
guest_mem.end_addr().unchecked_add(1)
};
let rsdp_addr = acpi::create_acpi_tables(
guest_mem,
num_cpus,
_serial_enabled,
start_of_device_area,
_end_of_range,
_virt_iommu,
);
if let Some(rsdp_addr) = rsdp_addr {
params.0.acpi_rsdp_addr = rsdp_addr.0;
}
@@ -196,7 +405,7 @@ pub fn configure_system(
.ok_or(super::Error::ZeroPagePastRamEnd)?;
guest_mem
.write_obj(params, zero_page_addr)
.map_err(|_| super::Error::ZeroPageSetup)?;
.map_err(super::Error::ZeroPageSetup)?;
Ok(())
}
@@ -221,6 +430,25 @@ fn add_e820_entry(
Ok(())
}
/// Returns the memory address where the initramfs could be loaded.
pub fn initramfs_load_addr(
guest_mem: &GuestMemoryMmap,
initramfs_size: usize,
) -> super::Result<u64> {
let first_region = guest_mem
.find_region(GuestAddress::new(0))
.ok_or(super::Error::InitramfsAddress)?;
// It's safe to cast to usize because the size of a region can't be greater than usize.
let lowmem_size = first_region.len() as usize;
if lowmem_size < initramfs_size {
return Err(super::Error::InitramfsAddress);
}
let aligned_addr: u64 = ((lowmem_size - initramfs_size) & !(crate::pagesize() - 1)) as u64;
Ok(aligned_addr)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -245,24 +473,18 @@ mod tests {
#[test]
fn test_system_configuration() {
let no_vcpus = 4;
let gm = GuestMemoryMmap::new(&vec![(GuestAddress(0), 0x10000)]).unwrap();
let gm = GuestMemoryMmap::from_ranges(&vec![(GuestAddress(0), 0x10000)]).unwrap();
let config_err = configure_system(
&gm,
GuestAddress(0),
0,
&None,
1,
None,
false,
GuestAddress((1 << 36) - 1),
None,
BootProtocol::LinuxBoot,
);
assert!(config_err.is_err());
assert_eq!(
config_err.unwrap_err(),
super::super::Error::X86_64Setup(super::Error::MpTableSetup(
mptable::Error::NotEnoughMemory
))
);
// Now assigning some memory that falls before the 32bit memory hole.
let mem_size = 128 << 20;
@@ -272,16 +494,28 @@ mod tests {
.filter(|r| r.2 == RegionType::Ram)
.map(|r| (r.0, r.1))
.collect();
let gm = GuestMemoryMmap::new(&ram_regions).unwrap();
let gm = GuestMemoryMmap::from_ranges(&ram_regions).unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
false,
GuestAddress((1 << 36) - 1),
None,
BootProtocol::LinuxBoot,
)
.unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
None,
BootProtocol::PvhBoot,
)
.unwrap();
@@ -293,16 +527,28 @@ mod tests {
.filter(|r| r.2 == RegionType::Ram)
.map(|r| (r.0, r.1))
.collect();
let gm = GuestMemoryMmap::new(&ram_regions).unwrap();
let gm = GuestMemoryMmap::from_ranges(&ram_regions).unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
false,
GuestAddress((1 << 36) - 1),
None,
BootProtocol::LinuxBoot,
)
.unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
None,
BootProtocol::PvhBoot,
)
.unwrap();
@@ -314,16 +560,28 @@ mod tests {
.filter(|r| r.2 == RegionType::Ram)
.map(|r| (r.0, r.1))
.collect();
let gm = GuestMemoryMmap::new(&ram_regions).unwrap();
let gm = GuestMemoryMmap::from_ranges(&ram_regions).unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
false,
GuestAddress((1 << 36) - 1),
None,
BootProtocol::LinuxBoot,
)
.unwrap();
configure_system(
&gm,
GuestAddress(0),
0,
&None,
no_vcpus,
None,
None,
BootProtocol::PvhBoot,
)
.unwrap();
}
@@ -367,4 +625,29 @@ mod tests {
)
.is_err());
}
#[test]
fn test_add_memmap_entry() {
let mut memmap: Vec<hvm_memmap_table_entry> = Vec::new();
let expected_memmap = vec![
hvm_memmap_table_entry {
addr: 0x0,
size: 0x1000,
type_: E820_RAM,
..Default::default()
},
hvm_memmap_table_entry {
addr: 0x10000,
size: 0xa000,
type_: E820_RESERVED,
..Default::default()
},
];
add_memmap_entry(&mut memmap, 0, 0x1000, E820_RAM).unwrap();
add_memmap_entry(&mut memmap, 0x10000, 0xa000, E820_RESERVED).unwrap();
assert_eq!(format!("{:?}", memmap), format!("{:?}", expected_memmap));
}
}

View File

@@ -14,7 +14,7 @@ use libc::c_char;
use arch_gen::x86::mpspec;
use layout::{APIC_START, IOAPIC_START, MPTABLE_START};
use vm_memory::{Address, ByteValued, Bytes, GuestMemory, GuestMemoryMmap};
use vm_memory::{Address, ByteValued, Bytes, GuestMemory, GuestMemoryError, GuestMemoryMmap};
// This is a workaround to the Rust enforcement specifying that any implementation of a foreign
// trait (in this case `ByteValued`) where:
@@ -45,30 +45,30 @@ unsafe impl ByteValued for MpcTableWrapper {}
unsafe impl ByteValued for MpcLintsrcWrapper {}
unsafe impl ByteValued for MpfIntelWrapper {}
#[derive(Debug, PartialEq)]
#[derive(Debug)]
pub enum Error {
/// There was too little guest memory to store the entire MP table.
NotEnoughMemory,
/// The MP table has too little address space to be stored.
AddressOverflow,
/// Failure while zeroing out the memory for the MP table.
Clear,
Clear(GuestMemoryError),
/// Number of CPUs exceeds the maximum supported CPUs
TooManyCpus,
/// Failure to write the MP floating pointer.
WriteMpfIntel,
WriteMpfIntel(GuestMemoryError),
/// Failure to write MP CPU entry.
WriteMpcCpu,
WriteMpcCpu(GuestMemoryError),
/// Failure to write MP ioapic entry.
WriteMpcIoapic,
WriteMpcIoapic(GuestMemoryError),
/// Failure to write MP bus entry.
WriteMpcBus,
WriteMpcBus(GuestMemoryError),
/// Failure to write MP interrupt source entry.
WriteMpcIntsrc,
WriteMpcIntsrc(GuestMemoryError),
/// Failure to write MP local interrupt source entry.
WriteMpcLintsrc,
WriteMpcLintsrc(GuestMemoryError),
/// Failure to write MP table header.
WriteMpcTable,
WriteMpcTable(GuestMemoryError),
}
pub type Result<T> = result::Result<T, Error>;
@@ -145,7 +145,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
}
mem.read_exact_from(base_mp, &mut io::repeat(0), mp_size)
.map_err(|_| Error::Clear)?;
.map_err(Error::Clear)?;
{
let mut mpf_intel = MpfIntelWrapper(mpspec::mpf_intel::default());
@@ -156,7 +156,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpf_intel.0.physptr = (base_mp.raw_value() + size) as u32;
mpf_intel.0.checksum = mpf_intel_compute_checksum(&mpf_intel.0);
mem.write_obj(mpf_intel, base_mp)
.map_err(|_| Error::WriteMpfIntel)?;
.map_err(Error::WriteMpfIntel)?;
base_mp = base_mp.unchecked_add(size);
}
@@ -181,7 +181,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_cpu.0.cpufeature = CPU_STEPPING;
mpc_cpu.0.featureflag = CPU_FEATURE_APIC | CPU_FEATURE_FPU;
mem.write_obj(mpc_cpu, base_mp)
.map_err(|_| Error::WriteMpcCpu)?;
.map_err(Error::WriteMpcCpu)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_cpu.0));
}
@@ -193,7 +193,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_bus.0.busid = 0;
mpc_bus.0.bustype = BUS_TYPE_ISA;
mem.write_obj(mpc_bus, base_mp)
.map_err(|_| Error::WriteMpcBus)?;
.map_err(Error::WriteMpcBus)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_bus.0));
}
@@ -206,7 +206,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_ioapic.0.flags = mpspec::MPC_APIC_USABLE as u8;
mpc_ioapic.0.apicaddr = IOAPIC_START.0 as u32;
mem.write_obj(mpc_ioapic, base_mp)
.map_err(|_| Error::WriteMpcIoapic)?;
.map_err(Error::WriteMpcIoapic)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_ioapic.0));
}
@@ -222,7 +222,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_intsrc.0.dstapic = ioapicid;
mpc_intsrc.0.dstirq = i;
mem.write_obj(mpc_intsrc, base_mp)
.map_err(|_| Error::WriteMpcIntsrc)?;
.map_err(Error::WriteMpcIntsrc)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc.0));
}
@@ -237,7 +237,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_lintsrc.0.destapic = 0;
mpc_lintsrc.0.destapiclint = 0;
mem.write_obj(mpc_lintsrc, base_mp)
.map_err(|_| Error::WriteMpcLintsrc)?;
.map_err(Error::WriteMpcLintsrc)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc.0));
}
@@ -252,7 +252,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
mpc_lintsrc.0.destapic = 0xFF; /* to all local APICs */
mpc_lintsrc.0.destapiclint = 1;
mem.write_obj(mpc_lintsrc, base_mp)
.map_err(|_| Error::WriteMpcLintsrc)?;
.map_err(Error::WriteMpcLintsrc)?;
base_mp = base_mp.unchecked_add(size as u64);
checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc.0));
}
@@ -271,7 +271,7 @@ pub fn setup_mptable(mem: &GuestMemoryMmap, num_cpus: u8) -> Result<()> {
checksum = checksum.wrapping_add(compute_checksum(&mpc_table.0));
mpc_table.0.checksum = (!checksum).wrapping_add(1) as i8;
mem.write_obj(mpc_table, table_base)
.map_err(|_| Error::WriteMpcTable)?;
.map_err(Error::WriteMpcTable)?;
}
Ok(())
@@ -296,7 +296,8 @@ mod tests {
#[test]
fn bounds_check() {
let num_cpus = 4;
let mem = GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
let mem =
GuestMemoryMmap::from_ranges(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
setup_mptable(&mem, num_cpus).unwrap();
}
@@ -304,7 +305,8 @@ mod tests {
#[test]
fn bounds_check_fails() {
let num_cpus = 4;
let mem = GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(num_cpus) - 1)]).unwrap();
let mem = GuestMemoryMmap::from_ranges(&[(MPTABLE_START, compute_mp_size(num_cpus) - 1)])
.unwrap();
assert!(setup_mptable(&mem, num_cpus).is_err());
}
@@ -312,7 +314,8 @@ mod tests {
#[test]
fn mpf_intel_checksum() {
let num_cpus = 1;
let mem = GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
let mem =
GuestMemoryMmap::from_ranges(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
setup_mptable(&mem, num_cpus).unwrap();
@@ -327,7 +330,8 @@ mod tests {
#[test]
fn mpc_table_checksum() {
let num_cpus = 4;
let mem = GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
let mem =
GuestMemoryMmap::from_ranges(&[(MPTABLE_START, compute_mp_size(num_cpus))]).unwrap();
setup_mptable(&mem, num_cpus).unwrap();
@@ -356,9 +360,11 @@ mod tests {
#[test]
fn cpu_entry_count() {
let mem =
GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(MAX_SUPPORTED_CPUS as u8))])
.unwrap();
let mem = GuestMemoryMmap::from_ranges(&[(
MPTABLE_START,
compute_mp_size(MAX_SUPPORTED_CPUS as u8),
)])
.unwrap();
for i in 0..MAX_SUPPORTED_CPUS as u8 {
setup_mptable(&mem, i).unwrap();
@@ -391,9 +397,10 @@ mod tests {
#[test]
fn cpu_entry_count_max() {
let cpus = MAX_SUPPORTED_CPUS + 1;
let mem = GuestMemoryMmap::new(&[(MPTABLE_START, compute_mp_size(cpus as u8))]).unwrap();
let mem =
GuestMemoryMmap::from_ranges(&[(MPTABLE_START, compute_mp_size(cpus as u8))]).unwrap();
let result = setup_mptable(&mem, cpus as u8).unwrap_err();
assert_eq!(result, Error::TooManyCpus);
let result = setup_mptable(&mem, cpus as u8);
assert!(result.is_err());
}
}

View File

@@ -1,3 +1,5 @@
// Copyright © 2020, Oracle and/or its affiliates.
//
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
@@ -5,14 +7,15 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
use std::{io, mem, result};
use std::{mem, result};
use super::gdt::{gdt_entry, kvm_segment_from_gdt};
use super::BootProtocol;
use arch_gen::x86::msr_index;
use kvm_bindings::{kvm_fpu, kvm_msr_entry, kvm_msrs, kvm_regs, kvm_sregs};
use kvm_bindings::{kvm_fpu, kvm_msr_entry, kvm_regs, kvm_sregs, Msrs};
use kvm_ioctls::VcpuFd;
use layout::{BOOT_GDT_START, BOOT_IDT_START, PDE_START, PDPTE_START, PML4_START};
use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryMmap};
use layout::{BOOT_GDT_START, BOOT_IDT_START, PDE_START, PDPTE_START, PML4_START, PVH_INFO_START};
use vm_memory::{Address, Bytes, GuestMemory, GuestMemoryError, GuestMemoryMmap};
// MTRR constants
const MTRR_ENABLE: u64 = 0x800; // IA32_MTRR_DEF_TYPE MSR: E (MTRRs enabled) flag, bit 11
@@ -21,25 +24,27 @@ const MTRR_MEM_TYPE_WB: u64 = 0x6;
#[derive(Debug)]
pub enum Error {
/// Failed to get SREGs for this CPU.
GetStatusRegisters(io::Error),
GetStatusRegisters(kvm_ioctls::Error),
/// Failed to set base registers for this CPU.
SetBaseRegisters(io::Error),
SetBaseRegisters(kvm_ioctls::Error),
/// Failed to configure the FPU.
SetFPURegisters(io::Error),
SetFPURegisters(kvm_ioctls::Error),
/// Setting up MSRs failed.
SetModelSpecificRegisters(io::Error),
SetModelSpecificRegisters(kvm_ioctls::Error),
/// Failed to set SREGs for this CPU.
SetStatusRegisters(io::Error),
SetStatusRegisters(kvm_ioctls::Error),
/// Checking the GDT address failed.
CheckGDTAddr,
/// Writing the GDT to RAM failed.
WriteGDT,
WriteGDT(GuestMemoryError),
/// Writing the IDT to RAM failed.
WriteIDT,
WriteIDT(GuestMemoryError),
/// Writing PDPTE to RAM failed.
WritePDPTEAddress,
WritePDPTEAddress(GuestMemoryError),
/// Writing PDE to RAM failed.
WritePDEAddress,
WritePDEAddress(GuestMemoryError),
/// Writing PML4 to RAM failed.
WritePML4Address,
WritePML4Address(GuestMemoryError),
}
pub type Result<T> = result::Result<T, Error>;
@@ -65,26 +70,10 @@ pub fn setup_fpu(vcpu: &VcpuFd) -> Result<()> {
///
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_msrs(vcpu: &VcpuFd) -> Result<()> {
let entry_vec = create_msr_entries();
let vec_size_bytes =
mem::size_of::<kvm_msrs>() + (entry_vec.len() * mem::size_of::<kvm_msr_entry>());
let vec: Vec<u8> = Vec::with_capacity(vec_size_bytes);
let msrs: &mut kvm_msrs = unsafe {
// Converting the vector's memory to a struct is unsafe. Carefully using the read-only
// vector to size and set the members ensures no out-of-bounds errors below.
&mut *(vec.as_ptr() as *mut kvm_msrs)
};
vcpu.set_msrs(&boot_msr_entries())
.map_err(Error::SetModelSpecificRegisters)?;
unsafe {
// Mapping the unsized array to a slice is unsafe because the length isn't known.
// Providing the length used to create the struct guarantees the entire slice is valid.
let entries: &mut [kvm_msr_entry] = msrs.entries.as_mut_slice(entry_vec.len());
entries.copy_from_slice(&entry_vec);
}
msrs.nmsrs = entry_vec.len() as u32;
vcpu.set_msrs(msrs)
.map_err(Error::SetModelSpecificRegisters)
Ok(())
}
/// Configure base registers for a given CPU.
@@ -95,16 +84,31 @@ pub fn setup_msrs(vcpu: &VcpuFd) -> Result<()> {
/// * `boot_ip` - Starting instruction pointer.
/// * `boot_sp` - Starting stack pointer.
/// * `boot_si` - Must point to zero page address per Linux ABI.
pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64, boot_sp: u64, boot_si: u64) -> Result<()> {
let regs: kvm_regs = kvm_regs {
rflags: 0x0000000000000002u64,
rip: boot_ip,
rsp: boot_sp,
rbp: boot_sp,
rsi: boot_si,
..Default::default()
pub fn setup_regs(
vcpu: &VcpuFd,
boot_ip: u64,
boot_sp: u64,
boot_si: u64,
boot_prot: BootProtocol,
) -> Result<()> {
let regs: kvm_regs = match boot_prot {
// Configure regs as required by PVH boot protocol.
BootProtocol::PvhBoot => kvm_regs {
rflags: 0x0000000000000002u64,
rbx: PVH_INFO_START.raw_value(),
rip: boot_ip,
..Default::default()
},
// Configure regs as required by Linux 64-bit boot protocol.
BootProtocol::LinuxBoot => kvm_regs {
rflags: 0x0000000000000002u64,
rip: boot_ip,
rsp: boot_sp,
rbp: boot_sp,
rsi: boot_si,
..Default::default()
},
};
vcpu.set_regs(&regs).map_err(Error::SetBaseRegisters)
}
@@ -114,11 +118,14 @@ pub fn setup_regs(vcpu: &VcpuFd, boot_ip: u64, boot_sp: u64, boot_si: u64) -> Re
///
/// * `mem` - The memory that will be passed to the guest.
/// * `vcpu` - Structure for the VCPU that holds the VCPU's fd.
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd) -> Result<()> {
pub fn setup_sregs(mem: &GuestMemoryMmap, vcpu: &VcpuFd, boot_prot: BootProtocol) -> Result<()> {
let mut sregs: kvm_sregs = vcpu.get_sregs().map_err(Error::GetStatusRegisters)?;
configure_segments_and_sregs(mem, &mut sregs)?;
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
configure_segments_and_sregs(mem, &mut sregs, boot_prot)?;
if let BootProtocol::LinuxBoot = boot_prot {
setup_page_tables(mem, &mut sregs)?; // TODO(dgreid) - Can this be done once per system instead?
}
vcpu.set_sregs(&sregs).map_err(Error::SetStatusRegisters)
}
@@ -137,10 +144,8 @@ fn write_gdt_table(table: &[u64], guest_mem: &GuestMemoryMmap) -> Result<()> {
for (index, entry) in table.iter().enumerate() {
let addr = guest_mem
.checked_offset(boot_gdt_addr, index * mem::size_of::<u64>())
.ok_or(Error::WriteGDT)?;
guest_mem
.write_obj(*entry, addr)
.map_err(|_| Error::WriteGDT)?;
.ok_or(Error::CheckGDTAddr)?;
guest_mem.write_obj(*entry, addr).map_err(Error::WriteGDT)?;
}
Ok(())
}
@@ -149,16 +154,34 @@ fn write_idt_value(val: u64, guest_mem: &GuestMemoryMmap) -> Result<()> {
let boot_idt_addr = BOOT_IDT_START;
guest_mem
.write_obj(val, boot_idt_addr)
.map_err(|_| Error::WriteIDT)
.map_err(Error::WriteIDT)
}
fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = [
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
];
fn configure_segments_and_sregs(
mem: &GuestMemoryMmap,
sregs: &mut kvm_sregs,
boot_prot: BootProtocol,
) -> Result<()> {
let gdt_table: [u64; BOOT_GDT_MAX as usize] = match boot_prot {
BootProtocol::PvhBoot => {
// Configure GDT entries as specified by PVH boot protocol
[
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xc09b, 0, 0xffffffff), // CODE
gdt_entry(0xc093, 0, 0xffffffff), // DATA
gdt_entry(0x008b, 0, 0x67), // TSS
]
}
BootProtocol::LinuxBoot => {
// Configure GDT entries as specified by Linux 64bit boot protocol
[
gdt_entry(0, 0, 0), // NULL
gdt_entry(0xa09b, 0, 0xfffff), // CODE
gdt_entry(0xc093, 0, 0xfffff), // DATA
gdt_entry(0x808b, 0, 0xfffff), // TSS
]
}
};
let code_seg = kvm_segment_from_gdt(gdt_table[1], 1);
let data_seg = kvm_segment_from_gdt(gdt_table[2], 2);
@@ -181,9 +204,17 @@ fn configure_segments_and_sregs(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) ->
sregs.ss = data_seg;
sregs.tr = tss_seg;
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
match boot_prot {
BootProtocol::PvhBoot => {
sregs.cr0 = X86_CR0_PE;
sregs.cr4 = 0;
}
BootProtocol::LinuxBoot => {
/* 64-bit protected mode */
sregs.cr0 |= X86_CR0_PE;
sregs.efer |= EFER_LME | EFER_LMA;
}
}
Ok(())
}
@@ -193,16 +224,16 @@ fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()>
// Entry covering VA [0..512GB)
mem.write_obj(PDPTE_START.raw_value() | 0x03, PML4_START)
.map_err(|_| Error::WritePML4Address)?;
.map_err(Error::WritePML4Address)?;
// Entry covering VA [0..1GB)
mem.write_obj(PDE_START.raw_value() | 0x03, PDPTE_START)
.map_err(|_| Error::WritePDPTEAddress)?;
.map_err(Error::WritePDPTEAddress)?;
// 512 2MB entries together covering VA [0..1GB). Note we are assuming
// CPU supports 2MB pages (/proc/cpuinfo has 'pse'). All modern CPUs do.
for i in 0..512 {
mem.write_obj((i << 21) + 0x83u64, PDE_START.unchecked_add(i * 8))
.map_err(|_| Error::WritePDEAddress)?;
.map_err(Error::WritePDEAddress)?;
}
sregs.cr3 = PML4_START.raw_value();
@@ -211,68 +242,43 @@ fn setup_page_tables(mem: &GuestMemoryMmap, sregs: &mut kvm_sregs) -> Result<()>
Ok(())
}
fn create_msr_entries() -> Vec<kvm_msr_entry> {
let mut entries = Vec::<kvm_msr_entry>::new();
macro_rules! kvm_msr {
($msr:expr) => {
kvm_msr_entry {
index: $msr,
data: 0x0,
..Default::default()
}
};
}
entries.push(kvm_msr_entry {
index: msr_index::MSR_IA32_SYSENTER_CS,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_IA32_SYSENTER_ESP,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_IA32_SYSENTER_EIP,
data: 0x0,
..Default::default()
});
// x86_64 specific msrs, we only run on x86_64 not x86.
entries.push(kvm_msr_entry {
index: msr_index::MSR_STAR,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_CSTAR,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_KERNEL_GS_BASE,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_SYSCALL_MASK,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_LSTAR,
data: 0x0,
..Default::default()
});
// end of x86_64 specific code
entries.push(kvm_msr_entry {
index: msr_index::MSR_IA32_TSC,
data: 0x0,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_IA32_MISC_ENABLE,
data: msr_index::MSR_IA32_MISC_ENABLE_FAST_STRING as u64,
..Default::default()
});
entries.push(kvm_msr_entry {
index: msr_index::MSR_MTRRdefType,
data: MTRR_ENABLE | MTRR_MEM_TYPE_WB,
..Default::default()
});
macro_rules! kvm_msr_data {
($msr:expr, $data:expr) => {
kvm_msr_entry {
index: $msr,
data: $data,
..Default::default()
}
};
}
entries
pub fn boot_msr_entries() -> Msrs {
Msrs::from_entries(&[
kvm_msr!(msr_index::MSR_IA32_SYSENTER_CS),
kvm_msr!(msr_index::MSR_IA32_SYSENTER_ESP),
kvm_msr!(msr_index::MSR_IA32_SYSENTER_EIP),
kvm_msr!(msr_index::MSR_STAR),
kvm_msr!(msr_index::MSR_CSTAR),
kvm_msr!(msr_index::MSR_LSTAR),
kvm_msr!(msr_index::MSR_KERNEL_GS_BASE),
kvm_msr!(msr_index::MSR_SYSCALL_MASK),
kvm_msr!(msr_index::MSR_IA32_TSC),
kvm_msr_data!(
msr_index::MSR_IA32_MISC_ENABLE,
msr_index::MSR_IA32_MISC_ENABLE_FAST_STRING as u64
),
kvm_msr_data!(msr_index::MSR_MTRRdefType, MTRR_ENABLE | MTRR_MEM_TYPE_WB),
])
}
#[cfg(test)]
@@ -285,7 +291,7 @@ mod tests {
use vm_memory::{GuestAddress, GuestMemoryMmap};
fn create_guest_mem() -> GuestMemoryMmap {
GuestMemoryMmap::new(&vec![(GuestAddress(0), 0x10000)]).unwrap()
GuestMemoryMmap::from_ranges(&vec![(GuestAddress(0), 0x10000)]).unwrap()
}
fn read_u64(gm: &GuestMemoryMmap, offset: GuestAddress) -> u64 {
@@ -296,7 +302,7 @@ mod tests {
fn segments_and_sregs() {
let mut sregs: kvm_sregs = Default::default();
let gm = create_guest_mem();
configure_segments_and_sregs(&gm, &mut sregs).unwrap();
configure_segments_and_sregs(&gm, &mut sregs, BootProtocol::LinuxBoot).unwrap();
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_START));
assert_eq!(
@@ -314,16 +320,46 @@ mod tests {
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_START));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xfffff, sregs.ds.limit);
assert_eq!(0xffffffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0xfffff, sregs.tr.limit);
assert_eq!(0xffffffff, sregs.tr.limit);
assert_eq!(0, sregs.tr.avl);
assert_eq!(X86_CR0_PE, sregs.cr0);
assert_eq!(EFER_LME | EFER_LMA, sregs.efer);
configure_segments_and_sregs(&gm, &mut sregs, BootProtocol::PvhBoot).unwrap();
assert_eq!(0x0, read_u64(&gm, BOOT_GDT_START));
assert_eq!(
0xcf9b000000ffff,
read_u64(&gm, BOOT_GDT_START.unchecked_add(8))
);
assert_eq!(
0xcf93000000ffff,
read_u64(&gm, BOOT_GDT_START.unchecked_add(16))
);
assert_eq!(
0x8b0000000067,
read_u64(&gm, BOOT_GDT_START.unchecked_add(24))
);
assert_eq!(0x0, read_u64(&gm, BOOT_IDT_START));
assert_eq!(0, sregs.cs.base);
assert_eq!(0xffffffff, sregs.ds.limit);
assert_eq!(0x10, sregs.es.selector);
assert_eq!(1, sregs.fs.present);
assert_eq!(1, sregs.gs.g);
assert_eq!(0, sregs.ss.avl);
assert_eq!(0, sregs.tr.base);
assert_eq!(0, sregs.tr.g);
assert_eq!(0x67, sregs.tr.limit);
assert_eq!(0xb, sregs.tr.type_);
assert_eq!(0, sregs.tr.avl);
assert_eq!(X86_CR0_PE, sregs.cr0);
assert_eq!(0, sregs.cr4);
}
#[test]
@@ -377,24 +413,11 @@ mod tests {
// This test will check against the last MSR entry configured (the tenth one).
// See create_msr_entries for details.
let test_kvm_msrs_entry = [kvm_msr_entry {
let mut msrs = Msrs::from_entries(&[kvm_msr_entry {
index: msr_index::MSR_IA32_MISC_ENABLE,
..Default::default()
}];
let vec_size_bytes = mem::size_of::<kvm_msrs>() + mem::size_of::<kvm_msr_entry>();
let vec: Vec<u8> = Vec::with_capacity(vec_size_bytes);
let mut msrs: &mut kvm_msrs = unsafe {
// Converting the vector's memory to a struct is unsafe. Carefully using the read-only
// vector to size and set the members ensures no out-of-bounds errors below.
&mut *(vec.as_ptr() as *mut kvm_msrs)
};
}]);
unsafe {
let entries: &mut [kvm_msr_entry] = msrs.entries.as_mut_slice(1);
entries.copy_from_slice(&test_kvm_msrs_entry);
}
msrs.nmsrs = 1;
// get_msrs returns the number of msrs that it succeed in reading. We only want to read 1
// in this test case scenario.
let read_msrs = vcpu.get_msrs(&mut msrs).unwrap();
@@ -403,10 +426,8 @@ mod tests {
// Official entries that were setup when we did setup_msrs. We need to assert that the
// tenth one (i.e the one with index msr_index::MSR_IA32_MISC_ENABLE has the data we
// expect.
let entry_vec = create_msr_entries();
unsafe {
assert_eq!(entry_vec[9], msrs.entries.as_slice(1)[0]);
}
let entry_vec = boot_msr_entries();
assert_eq!(entry_vec.as_slice()[9], msrs.as_slice()[0]);
}
#[test]
@@ -429,6 +450,7 @@ mod tests {
expected_regs.rip,
expected_regs.rsp,
expected_regs.rsi,
BootProtocol::LinuxBoot,
)
.unwrap();
@@ -444,10 +466,10 @@ mod tests {
let mut expected_sregs: kvm_sregs = vcpu.get_sregs().unwrap();
let gm = create_guest_mem();
configure_segments_and_sregs(&gm, &mut expected_sregs).unwrap();
configure_segments_and_sregs(&gm, &mut expected_sregs, BootProtocol::LinuxBoot).unwrap();
setup_page_tables(&gm, &mut expected_sregs).unwrap();
setup_sregs(&gm, &vcpu).unwrap();
setup_sregs(&gm, &vcpu, BootProtocol::LinuxBoot).unwrap();
let actual_sregs: kvm_sregs = vcpu.get_sregs().unwrap();
assert_eq!(expected_sregs, actual_sregs);
}

File diff suppressed because it is too large Load Diff

View File

@@ -16,7 +16,6 @@
clippy::should_implement_trait,
clippy::transmute_ptr_to_ptr
)]
pub mod bootparam;
#[allow(non_camel_case_types)]
#[allow(non_upper_case_globals)]
#[allow(clippy::unreadable_literal, clippy::redundant_static_lifetimes)]

22
build.rs Normal file
View File

@@ -0,0 +1,22 @@
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use std::process::Command;
fn main() {
let git_out = Command::new("git")
.args(&["describe", "--dirty"])
.output()
.expect("Expect to get git describe output");
// This println!() has a special behavior, as it will set the environment
// variable BUILT_VERSION, so that it can be reused from the binary.
// Particularly, this is used from src/main.rs to display the exact
// version.
println!(
"cargo:rustc-env=BUILT_VERSION={}",
String::from_utf8(git_out.stdout).unwrap()
);
}

View File

@@ -4,19 +4,26 @@ version = "0.1.0"
authors = ["The Chromium OS Authors"]
[dependencies]
byteorder = "1.3.2"
epoll = "4.1.0"
kvm-bindings = "0.1.1"
kvm-ioctls = { git = "https://github.com/rust-vmm/kvm-ioctls", branch = "master" }
libc = "0.2.60"
anyhow = "1.0"
bitflags = ">=1.2.1"
byteorder = "1.3.4"
epoll = ">=4.0.1"
libc = "0.2.69"
log = "0.4.8"
vm-memory = { git = "https://github.com/rust-vmm/vm-memory" }
vmm-sys-util = "0.1.1"
serde = {version = ">=1.0.27", features = ["rc"] }
serde_derive = ">=1.0.27"
serde_json = ">=1.0.9"
vm-device = { path = "../vm-device" }
acpi_tables = { path = "../acpi_tables", optional = true }
vm-memory = "0.2.0"
vm-migration = { path = "../vm-migration" }
vmm-sys-util = ">=0.3.1"
[dev-dependencies]
tempfile = "3.1.0"
[features]
default = []
acpi = []
acpi = ["acpi_tables"]
cmos = []
fwdebug = []

View File

@@ -3,8 +3,12 @@
// SPDX-License-Identifier: Apache-2.0
//
use acpi_tables::{aml, aml::Aml};
use std::sync::Arc;
use vm_device::interrupt::InterruptSourceGroup;
use vmm_sys_util::eventfd::EventFd;
use BusDevice;
use HotPlugNotificationFlags;
/// A device for handling ACPI shutdown and reboot
pub struct AcpiShutdownDevice {
@@ -44,9 +48,104 @@ impl BusDevice for AcpiShutdownDevice {
const SLEEP_VALUE_BIT: u8 = 2;
if data[0] == (S5_SLEEP_VALUE << SLEEP_VALUE_BIT) | (1 << SLEEP_STATUS_EN_BIT) {
debug!("ACPI Shutdown signalled");
extern crate bitflags;
if let Err(e) = self.exit_evt.write(1) {
error!("Error triggering ACPI shutdown event: {}", e);
}
}
}
}
/// A device for handling ACPI GED event generation
pub struct AcpiGEDDevice {
interrupt: Arc<Box<dyn InterruptSourceGroup>>,
notification_type: HotPlugNotificationFlags,
ged_irq: u32,
}
impl AcpiGEDDevice {
pub fn new(interrupt: Arc<Box<dyn InterruptSourceGroup>>, ged_irq: u32) -> AcpiGEDDevice {
AcpiGEDDevice {
interrupt,
notification_type: HotPlugNotificationFlags::NO_DEVICES_CHANGED,
ged_irq,
}
}
pub fn notify(
&mut self,
notification_type: HotPlugNotificationFlags,
) -> Result<(), std::io::Error> {
self.notification_type |= notification_type;
self.interrupt.trigger(0)
}
pub fn irq(&self) -> u32 {
self.ged_irq
}
}
// I/O port reports what type of notification was made
impl BusDevice for AcpiGEDDevice {
// Spec has all fields as zero
fn read(&mut self, _base: u64, _offset: u64, data: &mut [u8]) {
data[0] = self.notification_type.bits();
self.notification_type = HotPlugNotificationFlags::NO_DEVICES_CHANGED;
}
fn write(&mut self, _base: u64, _offset: u64, _data: &[u8]) {}
}
#[cfg(feature = "acpi")]
impl Aml for AcpiGEDDevice {
fn to_aml_bytes(&self) -> Vec<u8> {
aml::Device::new(
"_SB_.GED_".into(),
vec![
&aml::Name::new("_HID".into(), &"ACPI0013"),
&aml::Name::new("_UID".into(), &aml::ZERO),
&aml::Name::new(
"_CRS".into(),
&aml::ResourceTemplate::new(vec![&aml::Interrupt::new(
true,
true,
false,
false,
self.ged_irq,
)]),
),
&aml::OpRegion::new("GDST".into(), aml::OpRegionSpace::SystemIO, 0xb000, 0x1),
&aml::Field::new(
"GDST".into(),
aml::FieldAccessType::Byte,
aml::FieldUpdateRule::WriteAsZeroes,
vec![aml::FieldEntry::Named(*b"GDAT", 8)],
),
&aml::Method::new(
"_EVT".into(),
1,
true,
vec![
&aml::Store::new(&aml::Local(0), &aml::Path::new("GDAT")),
&aml::And::new(&aml::Local(1), &aml::Local(0), &aml::ONE),
&aml::If::new(
&aml::Equal::new(&aml::Local(1), &aml::ONE),
vec![&aml::MethodCall::new("\\_SB_.CPUS.CSCN".into(), vec![])],
),
&aml::And::new(&aml::Local(1), &aml::Local(0), &2usize),
&aml::If::new(
&aml::Equal::new(&aml::Local(1), &2usize),
vec![&aml::MethodCall::new("\\_SB_.MHPC.MSCN".into(), vec![])],
),
&aml::And::new(&aml::Local(1), &aml::Local(0), &4usize),
&aml::If::new(
&aml::Equal::new(&aml::Local(1), &4usize),
vec![&aml::MethodCall::new("\\_SB_.PCI0.PCNT".into(), vec![])],
),
],
),
],
)
.to_aml_bytes()
}
}

View File

@@ -9,8 +9,8 @@
use std::cmp::{Ord, Ordering, PartialEq, PartialOrd};
use std::collections::btree_map::BTreeMap;
use std::result;
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, RwLock, Weak};
use std::{convert, error, fmt, io, result};
/// Trait for devices that respond to reads or writes in an arbitrary address space.
///
@@ -30,10 +30,28 @@ pub trait BusDevice: Send {
pub enum Error {
/// The insertion failed because the new device overlapped with an old device.
Overlap,
/// Failed to operate on zero sized range.
ZeroSizedRange,
/// Failed to find address range.
MissingAddressRange,
}
pub type Result<T> = result::Result<T, Error>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "bus_error: {:?}", self)
}
}
impl error::Error for Error {}
impl convert::From<Error> for io::Error {
fn from(e: Error) -> Self {
io::Error::new(io::ErrorKind::Other, e)
}
}
/// Holds a base and length representing the address space occupied by a `BusDevice`.
///
/// * base - The address at which the range start.
@@ -75,29 +93,30 @@ impl PartialOrd for BusRange {
///
/// This doesn't have any restrictions on what kind of device or address space this applies to. The
/// only restriction is that no two devices can overlap in this address space.
#[derive(Clone, Default)]
#[derive(Default)]
pub struct Bus {
devices: BTreeMap<BusRange, Arc<Mutex<dyn BusDevice>>>,
devices: RwLock<BTreeMap<BusRange, Weak<Mutex<dyn BusDevice>>>>,
}
impl Bus {
/// Constructs an a bus with an empty address space.
pub fn new() -> Bus {
Bus {
devices: BTreeMap::new(),
devices: RwLock::new(BTreeMap::new()),
}
}
fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<dyn BusDevice>)> {
let (range, dev) = self
.devices
fn first_before(&self, addr: u64) -> Option<(BusRange, Arc<Mutex<dyn BusDevice>>)> {
let devices = self.devices.read().unwrap();
let (range, dev) = devices
.range(..=BusRange { base: addr, len: 1 })
.rev()
.next()?;
Some((*range, dev))
Some((*range, dev.upgrade().unwrap().clone()))
}
pub fn resolve(&self, addr: u64) -> Option<(u64, u64, &Mutex<dyn BusDevice>)> {
#[allow(clippy::type_complexity)]
pub fn resolve(&self, addr: u64) -> Option<(u64, u64, Arc<Mutex<dyn BusDevice>>)> {
if let Some((range, dev)) = self.first_before(addr) {
let offset = addr - range.base;
if offset < range.len {
@@ -108,14 +127,16 @@ impl Bus {
}
/// Puts the given device at the given address space.
pub fn insert(&mut self, device: Arc<Mutex<dyn BusDevice>>, base: u64, len: u64) -> Result<()> {
pub fn insert(&self, device: Arc<Mutex<dyn BusDevice>>, base: u64, len: u64) -> Result<()> {
if len == 0 {
return Err(Error::Overlap);
return Err(Error::ZeroSizedRange);
}
// Reject all cases where the new device's range overlaps with an existing device.
if self
.devices
.read()
.unwrap()
.iter()
.any(|(range, _dev)| range.overlaps(base, len))
{
@@ -124,7 +145,9 @@ impl Bus {
if self
.devices
.insert(BusRange { base, len }, device)
.write()
.unwrap()
.insert(BusRange { base, len }, Arc::downgrade(&device))
.is_some()
{
return Err(Error::Overlap);
@@ -133,6 +156,61 @@ impl Bus {
Ok(())
}
/// Removes the device at the given address space range.
pub fn remove(&self, base: u64, len: u64) -> Result<()> {
if len == 0 {
return Err(Error::ZeroSizedRange);
}
let bus_range = BusRange { base, len };
if self.devices.write().unwrap().remove(&bus_range).is_none() {
return Err(Error::MissingAddressRange);
}
Ok(())
}
/// Removes all entries referencing the given device.
pub fn remove_by_device(&self, device: &Arc<Mutex<dyn BusDevice>>) -> Result<()> {
let mut device_list = self.devices.write().unwrap();
let mut remove_key_list = Vec::new();
for (key, value) in device_list.iter() {
if Arc::ptr_eq(&value.upgrade().unwrap(), device) {
remove_key_list.push(*key);
}
}
for key in remove_key_list.iter() {
device_list.remove(key);
}
Ok(())
}
/// Updates the address range for an existing device.
pub fn update_range(
&self,
old_base: u64,
old_len: u64,
new_base: u64,
new_len: u64,
) -> Result<()> {
// Retrieve the device corresponding to the range
let device = if let Some((_, _, dev)) = self.resolve(old_base) {
dev.clone()
} else {
return Err(Error::MissingAddressRange);
};
// Remove the old address range
self.remove(old_base, old_len)?;
// Insert the new address range
self.insert(device, new_base, new_len)
}
/// Reads data from the device that owns the range containing `addr` and puts it into `data`.
///
/// Returns true on success, otherwise `data` is untouched.
@@ -188,7 +266,7 @@ mod tests {
#[test]
fn bus_insert() {
let mut bus = Bus::new();
let bus = Bus::new();
let dummy = Arc::new(Mutex::new(DummyDevice));
assert!(bus.insert(dummy.clone(), 0x10, 0).is_err());
assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_ok());
@@ -209,7 +287,7 @@ mod tests {
#[test]
fn bus_read_write() {
let mut bus = Bus::new();
let bus = Bus::new();
let dummy = Arc::new(Mutex::new(DummyDevice));
assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_ok());
assert!(bus.read(0x10, &mut [0, 0, 0, 0]));
@@ -226,7 +304,7 @@ mod tests {
#[test]
fn bus_read_write_values() {
let mut bus = Bus::new();
let bus = Bus::new();
let dummy = Arc::new(Mutex::new(ConstantDevice));
assert!(bus.insert(dummy.clone(), 0x10, 0x10).is_ok());
@@ -240,7 +318,7 @@ mod tests {
}
#[test]
fn busrange_cmp_and_clone() {
fn busrange_cmp() {
let range = BusRange { base: 0x10, len: 2 };
assert_eq!(range, BusRange { base: 0x10, len: 3 });
assert_eq!(range, BusRange { base: 0x10, len: 2 });
@@ -250,17 +328,13 @@ mod tests {
assert_eq!(range, range.clone());
let mut bus = Bus::new();
let bus = Bus::new();
let mut data = [1, 2, 3, 4];
assert!(bus
.insert(Arc::new(Mutex::new(DummyDevice)), 0x10, 0x10)
.is_ok());
let device = Arc::new(Mutex::new(DummyDevice));
assert!(bus.insert(device.clone(), 0x10, 0x10).is_ok());
assert!(bus.write(0x10, &mut data));
let bus_clone = bus.clone();
assert!(bus.read(0x10, &mut data));
assert_eq!(data, [1, 2, 3, 4]);
assert!(bus_clone.read(0x10, &mut data));
assert_eq!(data, [1, 2, 3, 4]);
}
#[test]

View File

@@ -10,23 +10,45 @@
// See https://pdos.csail.mit.edu/6.828/2016/readings/ia32/ioapic.pdf for a specification.
use crate::BusDevice;
use anyhow::anyhow;
use byteorder::{ByteOrder, LittleEndian};
use kvm_bindings::kvm_msi;
use kvm_ioctls::VmFd;
use std::io;
use std::result;
use std::sync::Arc;
use std::{io, result};
use vm_device::interrupt::{
InterruptIndex, InterruptManager, InterruptSourceConfig, InterruptSourceGroup,
MsiIrqGroupConfig, MsiIrqSourceConfig,
};
use vm_memory::GuestAddress;
use vm_migration::{
Migratable, MigratableError, Pausable, Snapshot, SnapshotDataSection, Snapshottable,
Transportable,
};
#[derive(Serialize, Deserialize)]
#[serde(remote = "GuestAddress")]
pub struct GuestAddressDef(pub u64);
#[derive(Debug)]
pub enum Error {
/// Failed to send an interrupt.
InterruptFailed(io::Error),
/// Invalid destination mode.
InvalidDestinationMode,
/// Invalid trigger mode.
InvalidTriggerMode,
/// Invalid delivery mode.
InvalidDeliveryMode,
/// Failed creating the interrupt source group.
CreateInterruptSourceGroup(io::Error),
/// Failed triggering the interrupt.
TriggerInterrupt(io::Error),
/// Failed masking the interrupt.
MaskInterrupt(io::Error),
/// Failed unmasking the interrupt.
UnmaskInterrupt(io::Error),
/// Failed updating the interrupt.
UpdateInterrupt(io::Error),
/// Failed enabling the interrupt.
EnableInterrupt(io::Error),
}
type Result<T> = result::Result<T, Error>;
@@ -86,25 +108,6 @@ fn set_remote_irr(entry: &mut RedirectionTableEntry, val: u8) {
*entry |= u64::from(val & 0x1) << 14;
}
pub struct MsiMessage {
// Message Address Register
// 31-20: Base address. Fixed value (0x0FEE)
// 19-12: Destination ID
// 11-4: Reserved
// 3: Redirection Hint indication
// 2: Destination Mode
// 1-0: Reserved
pub addr: u32,
// Message Data Register
// 32-16: Reserved
// 15: Trigger Mode. 0 = Edge, 1 = Level
// 14: Level. 0 = Deassert, 1 = Assert
// 13-11: Reserved
// 10-8: Delivery Mode
// 7-0: Vector
pub data: u32,
}
pub const NUM_IOAPIC_PINS: usize = 24;
const IOAPIC_VERSION_ID: u32 = 0x0017_0011;
@@ -153,10 +156,22 @@ fn decode_irq_from_selector(selector: u8) -> (usize, bool) {
}
pub struct Ioapic {
id: u32,
id: String,
id_reg: u32,
reg_sel: u32,
reg_entries: [RedirectionTableEntry; NUM_IOAPIC_PINS],
vm_fd: Arc<VmFd>,
used_entries: [bool; NUM_IOAPIC_PINS],
apic_address: GuestAddress,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
}
#[derive(Serialize, Deserialize)]
pub struct IoapicState {
id_reg: u32,
reg_sel: u32,
reg_entries: [RedirectionTableEntry; NUM_IOAPIC_PINS],
used_entries: [bool; NUM_IOAPIC_PINS],
#[serde(with = "GuestAddressDef")]
apic_address: GuestAddress,
}
@@ -196,14 +211,31 @@ impl BusDevice for Ioapic {
}
impl Ioapic {
pub fn new(vm_fd: Arc<VmFd>, apic_address: GuestAddress) -> Ioapic {
Ioapic {
id: 0,
pub fn new(
id: String,
apic_address: GuestAddress,
interrupt_manager: Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) -> Result<Ioapic> {
let interrupt_source_group = interrupt_manager
.create_group(MsiIrqGroupConfig {
base: 0 as InterruptIndex,
count: NUM_IOAPIC_PINS as InterruptIndex,
})
.map_err(Error::CreateInterruptSourceGroup)?;
interrupt_source_group
.enable()
.map_err(Error::EnableInterrupt)?;
Ok(Ioapic {
id,
id_reg: 0,
reg_sel: 0,
reg_entries: [0; NUM_IOAPIC_PINS],
vm_fd,
used_entries: [false; NUM_IOAPIC_PINS],
apic_address,
}
interrupt_source_group,
})
}
// The ioapic must be informed about EOIs in order to deassert interrupts
@@ -223,16 +255,30 @@ impl Ioapic {
pub fn service_irq(&mut self, irq: usize) -> Result<()> {
let entry = &mut self.reg_entries[irq];
// Don't inject the interrupt if the IRQ is masked
if interrupt_mask(*entry) == 1 {
return Ok(());
self.interrupt_source_group
.trigger(irq as InterruptIndex)
.map_err(Error::TriggerInterrupt)?;
debug!("Interrupt successfully delivered");
// If trigger mode is level sensitive, set the Remote IRR bit.
// It will be cleared when the EOI is received.
if trigger_mode(*entry) == 1 {
set_remote_irr(entry, 1);
}
// Clear the Delivery Status bit
set_delivery_status(entry, 0);
Ok(())
}
fn update_entry(&self, irq: usize) -> Result<()> {
let entry = self.reg_entries[irq];
// Validate Destination Mode value, and retrieve Destination ID
let destination_mode = destination_mode(*entry);
let destination_mode = destination_mode(entry);
let destination_id: u8 = match destination_mode {
x if x == DestinationMode::Physical as u8 => destination_field_physical(*entry),
x if x == DestinationMode::Logical as u8 => destination_field_logical(*entry),
x if x == DestinationMode::Physical as u8 => destination_field_physical(entry),
x if x == DestinationMode::Logical as u8 => destination_field_logical(entry),
_ => return Err(Error::InvalidDestinationMode),
};
@@ -242,20 +288,20 @@ impl Ioapic {
let redirection_hint: u8 = 1;
// Generate MSI message address
let address_lo: u32 = self.apic_address.0 as u32
let low_addr: u32 = self.apic_address.0 as u32
| u32::from(destination_id) << 12
| u32::from(redirection_hint) << 3
| u32::from(destination_mode) << 2;
// Validate Trigger Mode value
let trigger_mode = trigger_mode(*entry);
let trigger_mode = trigger_mode(entry);
match trigger_mode {
x if (x == TriggerMode::Edge as u8) || (x == TriggerMode::Level as u8) => {}
_ => return Err(Error::InvalidTriggerMode),
}
// Validate Delivery Mode value
let delivery_mode = delivery_mode(*entry);
let delivery_mode = delivery_mode(entry);
match delivery_mode {
x if (x == DeliveryMode::Fixed as u8)
|| (x == DeliveryMode::Lowest as u8)
@@ -270,44 +316,38 @@ impl Ioapic {
// Generate MSI message data
let data: u32 = u32::from(trigger_mode) << 15
| u32::from(remote_irr(*entry)) << 14
| u32::from(remote_irr(entry)) << 14
| u32::from(delivery_mode) << 8
| u32::from(vector(*entry));
| u32::from(vector(entry));
let msi = kvm_msi {
address_lo,
address_hi: 0x0,
let config = MsiIrqSourceConfig {
high_addr: 0x0,
low_addr,
data,
flags: 0u32,
devid: 0u32,
pad: [0u8; 12],
};
match self.vm_fd.signal_msi(msi) {
Ok(ret) => {
if ret > 0 {
debug!("MSI message successfully delivered");
// If trigger mode is level sensitive, set the Remote IRR bit.
// It will be cleared when the EOI is received.
if trigger_mode == 1 {
set_remote_irr(entry, 1);
}
// Clear the Delivery Status bit
set_delivery_status(entry, 0);
} else {
warn!("failed to deliver MSI message, blocked by guest");
}
Ok(())
}
Err(e) => Err(Error::InterruptFailed(e)),
self.interrupt_source_group
.update(irq as InterruptIndex, InterruptSourceConfig::MsiIrq(config))
.map_err(Error::UpdateInterrupt)?;
if interrupt_mask(entry) == 1 {
self.interrupt_source_group
.mask(irq as InterruptIndex)
.map_err(Error::MaskInterrupt)?;
} else {
self.interrupt_source_group
.unmask(irq as InterruptIndex)
.map_err(Error::UnmaskInterrupt)?;
}
Ok(())
}
fn ioapic_write(&mut self, val: u32) {
debug!("IOAPIC_W reg 0x{:x}, val 0x{:x}", self.reg_sel, val);
match self.reg_sel as u8 {
IOAPIC_REG_ID => self.id = (val >> 24) & 0xf,
IOAPIC_REG_ID => self.id_reg = (val >> 24) & 0xf,
IOWIN_OFF..=REG_MAX_OFFSET => {
let (index, is_high_bits) = decode_irq_from_selector(self.reg_sel as u8);
if is_high_bits {
@@ -320,6 +360,13 @@ impl Ioapic {
self.reg_entries[index] &= 0xffff_ffff_0000_5000;
self.reg_entries[index] |= u64::from(val) & 0xffff_afff;
}
// The entry must be updated through the interrupt source
// group.
if let Err(e) = self.update_entry(index) {
error!("Failed updating IOAPIC entry: {:?}", e);
}
// Store the information this IRQ is now being used.
self.used_entries[index] = true;
}
_ => error!("IOAPIC: invalid write to register offset"),
}
@@ -330,7 +377,7 @@ impl Ioapic {
match self.reg_sel as u8 {
IOAPIC_REG_VERSION => IOAPIC_VERSION_ID,
IOAPIC_REG_ID | IOAPIC_REG_ARBITRATION_ID => (self.id & 0xf) << 24,
IOAPIC_REG_ID | IOAPIC_REG_ARBITRATION_ID => (self.id_reg & 0xf) << 24,
IOWIN_OFF..=REG_MAX_OFFSET => {
let (index, is_high_bits) = decode_irq_from_selector(self.reg_sel as u8);
if is_high_bits {
@@ -345,4 +392,74 @@ impl Ioapic {
}
}
}
fn state(&self) -> IoapicState {
IoapicState {
id_reg: self.id_reg,
reg_sel: self.reg_sel,
reg_entries: self.reg_entries,
used_entries: self.used_entries,
apic_address: self.apic_address,
}
}
fn set_state(&mut self, state: &IoapicState) -> Result<()> {
self.id_reg = state.id_reg;
self.reg_sel = state.reg_sel;
self.reg_entries = state.reg_entries;
self.used_entries = state.used_entries;
self.apic_address = state.apic_address;
for (irq, entry) in self.used_entries.iter().enumerate() {
if *entry {
self.update_entry(irq)?;
}
}
Ok(())
}
}
impl Snapshottable for Ioapic {
fn id(&self) -> String {
self.id.clone()
}
fn snapshot(&self) -> std::result::Result<Snapshot, MigratableError> {
let snapshot =
serde_json::to_vec(&self.state()).map_err(|e| MigratableError::Snapshot(e.into()))?;
let mut ioapic_snapshot = Snapshot::new(self.id.as_str());
ioapic_snapshot.add_data_section(SnapshotDataSection {
id: format!("{}-section", self.id),
snapshot,
});
Ok(ioapic_snapshot)
}
fn restore(&mut self, snapshot: Snapshot) -> std::result::Result<(), MigratableError> {
if let Some(ioapic_section) = snapshot.snapshot_data.get(&format!("{}-section", self.id)) {
let ioapic_state = match serde_json::from_slice(&ioapic_section.snapshot) {
Ok(state) => state,
Err(error) => {
return Err(MigratableError::Restore(anyhow!(
"Could not deserialize IOAPIC {}",
error
)))
}
};
return self.set_state(&ioapic_state).map_err(|e| {
MigratableError::Restore(anyhow!("Could not restore IOAPIC state {:?}", e))
});
}
Err(MigratableError::Restore(anyhow!(
"Could not find IOAPIC snapshot section"
)))
}
}
impl Pausable for Ioapic {}
impl Transportable for Ioapic {}
impl Migratable for Ioapic {}

View File

@@ -0,0 +1,40 @@
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
//
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
//
use BusDevice;
/// Provides firmware debug output via I/O port controls
#[derive(Default)]
pub struct FwDebugDevice {}
impl FwDebugDevice {
pub fn new() -> Self {
Self {}
}
}
/// FwDebugDevice sits on the I/O bus as 0x402 and receives ASCII characters
impl BusDevice for FwDebugDevice {
/// Upon read return the magic value to indicate that there is a debug port
fn read(&mut self, _base: u64, _offset: u64, data: &mut [u8]) {
if data.len() == 1 {
data[0] = 0xe9
} else {
error!("Invalid read size on debug port: {}", data.len())
}
}
fn write(&mut self, _base: u64, _offset: u64, data: &[u8]) {
if data.len() == 1 {
print!("{}", data[0] as char);
} else {
error!("Invalid write size on debug port: {}", data.len())
}
}
}

View File

@@ -7,10 +7,14 @@
#[cfg(feature = "cmos")]
mod cmos;
#[cfg(feature = "fwdebug")]
mod fwdebug;
mod i8042;
mod serial;
#[cfg(feature = "cmos")]
pub use self::cmos::Cmos;
#[cfg(feature = "fwdebug")]
pub use self::fwdebug::FwDebugDevice;
pub use self::i8042::I8042Device;
pub use self::serial::Serial;

View File

@@ -5,9 +5,16 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
use crate::{BusDevice, Interrupt};
use crate::BusDevice;
use anyhow::anyhow;
use std::collections::VecDeque;
use std::sync::Arc;
use std::{io, result};
use vm_device::interrupt::InterruptSourceGroup;
use vm_migration::{
Migratable, MigratableError, Pausable, Snapshot, SnapshotDataSection, Snapshottable,
Transportable,
};
use vmm_sys_util::errno::Result;
const LOOP_SIZE: usize = 0x40;
@@ -53,9 +60,10 @@ const DEFAULT_BAUD_DIVISOR: u16 = 12; // 9600 bps
/// This can optionally write the guest's output to a Write trait object. To send input to the
/// guest, use `queue_input_bytes`.
pub struct Serial {
id: String,
interrupt_enable: u8,
interrupt_identification: u8,
interrupt: Box<dyn Interrupt>,
interrupt: Arc<Box<dyn InterruptSourceGroup>>,
line_control: u8,
line_status: u8,
modem_control: u8,
@@ -66,9 +74,27 @@ pub struct Serial {
out: Option<Box<dyn io::Write + Send>>,
}
#[derive(Serialize, Deserialize)]
pub struct SerialState {
interrupt_enable: u8,
interrupt_identification: u8,
line_control: u8,
line_status: u8,
modem_control: u8,
modem_status: u8,
scratch: u8,
baud_divisor: u16,
in_buffer: VecDeque<u8>,
}
impl Serial {
pub fn new(interrupt: Box<dyn Interrupt>, out: Option<Box<dyn io::Write + Send>>) -> Serial {
pub fn new(
id: String,
interrupt: Arc<Box<dyn InterruptSourceGroup>>,
out: Option<Box<dyn io::Write + Send>>,
) -> Serial {
Serial {
id,
interrupt_enable: 0,
interrupt_identification: DEFAULT_INTERRUPT_IDENTIFICATION,
interrupt,
@@ -84,13 +110,17 @@ impl Serial {
}
/// Constructs a Serial port ready for output.
pub fn new_out(interrupt: Box<dyn Interrupt>, out: Box<dyn io::Write + Send>) -> Serial {
Self::new(interrupt, Some(out))
pub fn new_out(
id: String,
interrupt: Arc<Box<dyn InterruptSourceGroup>>,
out: Box<dyn io::Write + Send>,
) -> Serial {
Self::new(id, interrupt, Some(out))
}
/// Constructs a Serial port with no connected output.
pub fn new_sink(interrupt: Box<dyn Interrupt>) -> Serial {
Self::new(interrupt, None)
pub fn new_sink(id: String, interrupt: Arc<Box<dyn InterruptSourceGroup>>) -> Serial {
Self::new(id, interrupt, None)
}
/// Queues raw bytes for the guest to read and signals the interrupt if the line status would
@@ -149,7 +179,7 @@ impl Serial {
}
fn trigger_interrupt(&mut self) -> result::Result<(), io::Error> {
self.interrupt.deliver()
self.interrupt.trigger(0)
}
fn iir_reset(&mut self) {
@@ -186,6 +216,32 @@ impl Serial {
}
Ok(())
}
fn state(&self) -> SerialState {
SerialState {
interrupt_enable: self.interrupt_enable,
interrupt_identification: self.interrupt_identification,
line_control: self.line_control,
line_status: self.line_status,
modem_control: self.modem_control,
modem_status: self.modem_status,
scratch: self.scratch,
baud_divisor: self.baud_divisor,
in_buffer: self.in_buffer.clone(),
}
}
fn set_state(&mut self, state: &SerialState) {
self.interrupt_enable = state.interrupt_enable;
self.interrupt_identification = state.interrupt_identification;
self.line_control = state.line_control;
self.line_status = state.line_status;
self.modem_control = state.modem_control;
self.modem_status = state.modem_status;
self.scratch = state.scratch;
self.baud_divisor = state.baud_divisor;
self.in_buffer = state.in_buffer.clone();
}
}
impl BusDevice for Serial {
@@ -228,21 +284,76 @@ impl BusDevice for Serial {
}
}
impl Snapshottable for Serial {
fn id(&self) -> String {
self.id.clone()
}
fn snapshot(&self) -> std::result::Result<Snapshot, MigratableError> {
let snapshot =
serde_json::to_vec(&self.state()).map_err(|e| MigratableError::Snapshot(e.into()))?;
let mut serial_snapshot = Snapshot::new(self.id.as_str());
serial_snapshot.add_data_section(SnapshotDataSection {
id: format!("{}-section", self.id),
snapshot,
});
Ok(serial_snapshot)
}
fn restore(&mut self, snapshot: Snapshot) -> std::result::Result<(), MigratableError> {
if let Some(serial_section) = snapshot.snapshot_data.get(&format!("{}-section", self.id)) {
let serial_state = match serde_json::from_slice(&serial_section.snapshot) {
Ok(state) => state,
Err(error) => {
return Err(MigratableError::Restore(anyhow!(
"Could not deserialize SERIAL {}",
error
)))
}
};
self.set_state(&serial_state);
return Ok(());
}
Err(MigratableError::Restore(anyhow!(
"Could not find the serial snapshot section"
)))
}
}
impl Pausable for Serial {}
impl Transportable for Serial {}
impl Migratable for Serial {}
#[cfg(test)]
mod tests {
use super::*;
use std::io;
use std::sync::{Arc, Mutex};
use vm_device::interrupt::{InterruptIndex, InterruptSourceConfig};
use vmm_sys_util::eventfd::EventFd;
const SERIAL_NAME: &str = "serial";
struct TestInterrupt {
event_fd: EventFd,
}
impl Interrupt for TestInterrupt {
fn deliver(&self) -> result::Result<(), std::io::Error> {
impl InterruptSourceGroup for TestInterrupt {
fn trigger(&self, _index: InterruptIndex) -> result::Result<(), std::io::Error> {
self.event_fd.write(1)
}
fn update(
&self,
_index: InterruptIndex,
_config: InterruptSourceConfig,
) -> result::Result<(), std::io::Error> {
Ok(())
}
}
impl TestInterrupt {
@@ -278,7 +389,8 @@ mod tests {
let intr_evt = EventFd::new(0).unwrap();
let serial_out = SharedBuffer::new();
let mut serial = Serial::new_out(
Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())),
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
Box::new(serial_out.clone()),
);
@@ -297,7 +409,8 @@ mod tests {
let intr_evt = EventFd::new(0).unwrap();
let serial_out = SharedBuffer::new();
let mut serial = Serial::new_out(
Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())),
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
Box::new(serial_out.clone()),
);
@@ -334,8 +447,10 @@ mod tests {
#[test]
fn serial_thr() {
let intr_evt = EventFd::new(0).unwrap();
let mut serial =
Serial::new_sink(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())));
let mut serial = Serial::new_sink(
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
);
// write 1 to the interrupt event fd, so that read doesn't block in case the event fd
// counter doesn't change (for 0 it blocks)
@@ -354,8 +469,10 @@ mod tests {
#[test]
fn serial_dlab() {
let intr_evt = EventFd::new(0).unwrap();
let mut serial =
Serial::new_sink(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())));
let mut serial = Serial::new_sink(
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
);
serial.write(0, LCR as u64, &[LCR_DLAB_BIT as u8]);
serial.write(0, DLAB_LOW as u64, &[0x12 as u8]);
@@ -373,8 +490,10 @@ mod tests {
#[test]
fn serial_modem() {
let intr_evt = EventFd::new(0).unwrap();
let mut serial =
Serial::new_sink(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())));
let mut serial = Serial::new_sink(
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
);
serial.write(0, MCR as u64, &[MCR_LOOP_BIT as u8]);
serial.write(0, DATA as u64, &['a' as u8]);
@@ -397,8 +516,10 @@ mod tests {
#[test]
fn serial_scratch() {
let intr_evt = EventFd::new(0).unwrap();
let mut serial =
Serial::new_sink(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap())));
let mut serial = Serial::new_sink(
String::from(SERIAL_NAME),
Arc::new(Box::new(TestInterrupt::new(intr_evt.try_clone().unwrap()))),
);
serial.write(0, SCR as u64, &[0x12 as u8]);

View File

@@ -6,18 +6,27 @@
// found in the LICENSE-BSD-3-Clause file.
//! Emulates virtual and hardware devices.
extern crate anyhow;
#[macro_use]
extern crate bitflags;
extern crate byteorder;
extern crate epoll;
extern crate kvm_bindings;
extern crate kvm_ioctls;
extern crate libc;
#[macro_use]
extern crate log;
#[cfg(feature = "acpi")]
extern crate acpi_tables;
extern crate serde;
extern crate vm_device;
extern crate vm_memory;
extern crate vm_migration;
extern crate vmm_sys_util;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
use std::fs::File;
use std::{io, result};
use std::io;
#[cfg(feature = "acpi")]
mod acpi;
@@ -26,7 +35,7 @@ pub mod ioapic;
pub mod legacy;
#[cfg(feature = "acpi")]
pub use self::acpi::AcpiShutdownDevice;
pub use self::acpi::{AcpiGEDDevice, AcpiShutdownDevice};
pub use self::bus::{Bus, BusDevice, Error as BusError};
pub type DeviceEventT = u16;
@@ -67,6 +76,11 @@ pub enum Error {
IoError(io::Error),
}
pub trait Interrupt: Send + Sync {
fn deliver(&self) -> result::Result<(), std::io::Error>;
bitflags! {
pub struct HotPlugNotificationFlags: u8 {
const NO_DEVICES_CHANGED = 0;
const CPU_DEVICES_CHANGED = 0b1;
const MEMORY_DEVICES_CHANGED = 0b10;
const PCI_DEVICES_CHANGED = 0b100;
}
}

378
docs/api.md Normal file
View File

@@ -0,0 +1,378 @@
- [Cloud Hypervisor API](#cloud-hypervisor-api)
* [External API](#external-api)
+ [REST API](#rest-api)
- [Location and availability](#location-and-availability)
- [Endpoints](#endpoints)
* [Virtual Machine Manager (VMM) Actions](#virtual-machine-manager-vmm-actions)
* [Virtual Machine (VM) Actions](#virtual-machine-vm-actions)
- [REST API Examples](#rest-api-examples)
* [Create a Virtual Machine](#create-a-virtual-machine)
* [Boot a Virtual Machine](#boot-a-virtual-machine)
* [Dump a Virtual Machine Information](#dump-a-virtual-machine-information)
* [Reboot a Virtual Machine](#reboot-a-virtual-machine)
* [Shut a Virtual Machine Down](#shut-a-virtual-machine-down)
+ [Command Line Interface](#command-line-interface)
+ [REST API and CLI Architecural Relationship](#rest-api-and-cli-architectural-relationship)
* [Internal API](#internal-api)
+ [Goals and Design](#goals-and-design)
* [End to End Example](#end-to-end-example)
# Cloud Hypervisor API
The Cloud Hypervisor API is made of 2 distinct interfaces:
1. **The external API**. This is the user facing API. Users and operators can
control and manage Cloud Hypervisor through either a REST API or a Command
Line Interface (CLI).
1. **The internal API**, based on [rust's Multi-Producer, Single-Consumer (MPSC)](https://doc.rust-lang.org/std/sync/mpsc/)
module. This API is used internally by the Cloud Hypervisor threads to
communicate between each others.
The goal of this document is to describe the Cloud Hypervisor API as a whole,
and to outline how the internal and external APIs are architecturally related.
## External API
### REST API
The Cloud Hypervisor [REST](https://en.wikipedia.org/wiki/Representational_state_transfer)
API triggers VM and VMM specific actions, and as such it is designed as a
collection of RPC-style, static methods.
The API is [OpenAPI 3.0](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md)
compliant. Please consult the [Cloud Hypervisor API](https://raw.githubusercontent.com/cloud-hypervisor/cloud-hypervisor/master/vmm/src/api/openapi/cloud-hypervisor.yaml)
document for more details about the API payloads and responses.
### Location and availability
The REST API is available as soon as the Cloud Hypervisor binary is started,
through a local UNIX socket.
By default, it is located at `/run/user/{user ID}/cloud-hypervisor.{Cloud Hypervisor PID}`.
For example, if you launched Cloud Hypervisor as user ID 1000 and its PID is
123456, the Cloud Hypervisor REST API will be available at `/run/user/1000/cloud-hypervisor.123456`.
The REST API default URL can be overridden through the Cloud Hypervisor
option `--api-socket`:
```
$ ./target/debug/cloud-hypervisor --api-socket /tmp/cloud-hypervisor.sock
Cloud Hypervisor Guest
API server: /tmp/cloud-hypervisor.sock
vCPUs: 1
Memory: 512 MB
Kernel: None
Kernel cmdline:
Disk(s): None
```
### Endpoints
The Cloud Hypervisor API exposes the following actions through its endpoints:
#### Virtual Machine Manager (VMM) Actions
Action | Endpoint | Request Body | Response Body | Prerequisites
------------------------------------|-----------------|--------------|----------------------------|---------------------------
Check for the REST API availability | `/vmm.ping` | N/A | `/schemas/VmmPingResponse` | N/A
Shut the VMM down | `/vmm.shutdown` | N/A | N/A | The VMM is running
#### Virtual Machine (VM) Actions
Action | Endpoint | Request Body | Response Body | Prerequisites
-----------------------------------|---------------------|---------------------------|-------------------|---------------------------
Create the VM | `/vm.create` | `/schemas/VmConfig` | N/A | The VM is not created yet
Delete the VM | `/vm.delete` | N/A | N/A | The VM is created but not booted
Boot the VM | `/vm.boot` | N/A | N/A | The VM is created
Shut the VM down | `/vm.shutdown` | N/A | N/A | The VM is booted
Reboot the VM | `/vm.reboot` | N/A | N/A | The VM is booted
Pause the VM | `/vm.pause` | N/A | N/A | The VM is booted
Resume the VM | `/vm.resume` | N/A | N/A | The VM is paused
Add/remove CPUs to/from the VM | `/vm.resize` | `/schemas/VmResize` | N/A | The VM is booted
Remove memory from the VM | `/vm.resize` | `/schemas/VmResize` | N/A | The VM is booted
Dump the VM information | `/vm.info` | N/A | `/schemas/VmInfo` | The VM is created
Add VFIO PCI device to the VM | `/vm.add-device` | `/schemas/VmAddDevice` | N/A | The VM is booted
Remove VFIO PCI device from the VM | `/vm.remove-device` | `/schemas/VmRemoveDevice` | N/A | The VM is booted
Add disk device to the VM | `/vm.add-disk` | `/schemas/DiskConfig` | N/A | The VM is booted
Add fs device to the VM | `/vm.add-fs` | `/schemas/FsConfig` | N/A | The VM is booted
Add pmem device to the VM | `/vm.add-pmem` | `/schemas/PmemConfig` | N/A | The VM is booted
Add network device to the VM | `/vm.add-net` | `/schemas/NetConfig` | N/A | The VM is booted
Add vsock device to the VM | `/vm.add-vsock` | `/schemas/VsockConfig` | N/A | The VM is booted
### REST API Examples
For the following set of examples, we assume Cloud Hypervisor is started with
the REST API available at `/tmp/cloud-hypervisor.sock`:
```
$ ./target/debug/cloud-hypervisor --api-socket /tmp/cloud-hypervisor.sock
Cloud Hypervisor Guest
API server: /tmp/cloud-hypervisor.sock
vCPUs: 1
Memory: 512 MB
Kernel: None
Kernel cmdline:
Disk(s): None
```
#### Create a Virtual Machine
We want to create a virtual machine with the following characteristics:
* 4 vCPUs
* 1 GB of RAM
* 1 virtio based networking interface
* Direct kernel boot from a custom 5.5.0 Linux kernel located at
`/opt/clh/kernel/vmlinux-virtio-fs-virtio-iommu`
* Using a Clear Linux image as its root filesystem, located at
`/opt/clh/images/clear-30080-kvm.img`
```shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i \
-X PUT 'http://localhost/api/v1/vm.create' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"cpus":{"boot_vcpus": 4, "max_vcpus": 4},
"kernel":{"path":"/opt/clh/kernel/vmlinux-virtio-fs-virtio-iommu"},
"cmdline":{"args":"console=hvc0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3"},
"disks":[{"path":"/opt/clh/images/clear-30080-kvm.img"}],
"rng":{"src":"/dev/urandom"},
"net":[{"ip":"192.168.10.10", "mask":"255.255.255.0", "mac":"12:34:56:78:90:01"}]
}'
```
#### Boot a Virtual Machine
Once the VM is created, we can boot it:
```shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i -X PUT 'http://localhost/api/v1/vm.boot'
```
#### Dump a Virtual Machine Information
We can fetch information about any VM, as soon as it's created:
```shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i \
-X GET 'http://localhost/api/v1/vm.info' \
-H 'Accept: application/json'
```
#### Reboot a Virtual Machine
We can reboot a VM that's already booted:
```shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i -X PUT 'http://localhost/api/v1/vm.reboot'
```
#### Shut a Virtual Machine Down
Once booted, we can shut a VM down from the REST API:
```shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i -X PUT 'http://localhost/api/v1/vm.shutdown'
```
### Command Line Interface
The Cloud Hypervisor Command Line Interface (CLI) can only be used for launching
the Cloud Hypervisor binary, i.e. it can not be used for controlling the VMM or
the launched VM once they're up and running.
If you want to inspect the VMM, or control the VM after launching Cloud
Hypervisor from the CLI, you must use the [REST API](#rest-api).
From the CLI, one can either:
1. Create and boot a complete virtual machine by using the CLI options to build
the VM config. Run `cloud-hypervisor --help` for a complete list of CLI
options. As soon as the `cloud-hypervisor` binary is launched, the
[REST API](#rest-api) is available for controlling and managing the VM.
1. Start the [REST API](#rest-api) server only, by not passing any VM
configuration options. The VM can then be asynchronously created and booted
by sending HTTP commands to the [REST API](#rest-api). Check the
[REST API examples](#rest-api-examples) section for more details.
### REST API and CLI Architectural Relationship
The REST API and the CLI both rely on a common, [internal API](#internal-api).
The CLI options are parsed by the
[clap crate](https://docs.rs/clap/2.33.0/clap/) and then translated into
[internal API](#internal-api) commands.
The REST API is processed by an HTTP thread using the
[Firecracker's `micro_http`](https://github.com/firecracker-microvm/firecracker/tree/master/src/micro_http)
crate. As with the CLI, the HTTP requests eventually get translated into
[internal API](#internal-api) commands.
As a summary, the REST API and the CLI are essentially frontends for the
[internal API](#internal-api):
```
+------------------+
REST API | |
+--------->+ micro_http +--------+
| | | |
| +------------------+ |
| | +------------------------+
| | | |
+------------+ | | | |
| | | | | +--------------+ |
| User +---------+ +------> | Internal API | |
| | | | | +--------------+ |
+------------+ | | | |
| | | |
| | +------------------------+
| +----------+ | VMM
| CLI | | |
+----------->+ clap +--------------+
| |
+----------+
```
## Internal API
The Cloud Hypervisor internal API, as its name suggests, is used internally
by the different Cloud Hypervisor threads (VMM, HTTP, control loop, etc) to
send commands and responses to each others.
It is based on [rust's Multi-Producer, Single-Consumer (MPSC)](https://doc.rust-lang.org/std/sync/mpsc/),
and the single consumer (a.k.a. the API receiver) is the Cloud Hypervisor
control loop.
API producers are the HTTP thread handling the [REST API](#rest-api) and the
main thread that initially parses the [CLI](#command-line-interface).
### Goals and Design
The internal API is designed for controlling, managing and inspecting a Cloud
Hypervisor VMM and its guest. It is a backend for handling external, user
visible requests through either the [REST API](#rest-api) or the
[CLI](#command-line-interface) interfaces.
The API follows a command-response scheme that closely maps the [REST API](#rest-api).
Any command must be replied to with a response.
Commands are [MPSC](https://doc.rust-lang.org/std/sync/mpsc/) based messages and
are received and processed by the VMM control loop.
In order for the VMM control loop to respond to any internal API command, it
must be able to send a response back to the MPSC sender. For that purpose, all
internal API command payload carry the [Sender](https://doc.rust-lang.org/std/sync/mpsc/struct.Sender.html)
end of an [MPSC](https://doc.rust-lang.org/std/sync/mpsc/) channel.
The sender of any internal API command is therefore responsible for:
1. Creating an [MPSC](https://doc.rust-lang.org/std/sync/mpsc/) response
channel.
1. Passing the [Sender](https://doc.rust-lang.org/std/sync/mpsc/struct.Sender.html)
end of the response channel as part of the internal API command payload.
1. Waiting for the internal API command's response on the [Receiver](https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html)
end of the response channel.
## End to End Example
In order to further understand how the external and internal Cloud Hypervisor
APIs work together, let's look at a complete VM creation flow, from the
[REST API](#rest-api) call, to the reply the external user will receive:
1. A user or operator sends an HTTP request to the Cloud Hypervisor
[REST API](#rest-api) in order to creates a virtual machine:
```
shell
#!/bin/bash
curl --unix-socket /tmp/cloud-hypervisor.sock -i \
-X PUT 'http://localhost/api/v1/vm.create' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"cpus":{"boot_vcpus": 4, "max_vcpus": 4},
"kernel":{"path":"/opt/clh/kernel/vmlinux-virtio-fs-virtio-iommu"},
"cmdline":{"args":"console=hvc0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3"},
"disks":[{"path":"/opt/clh/images/clear-30080-kvm.img"}],
"rng":{"src":"/dev/urandom"},
"net":[{"ip":"192.168.10.10", "mask":"255.255.255.0", "mac":"12:34:56:78:90:01"}]
}'
```
1. The Cloud Hypervisor HTTP thread processes the request and de-serializes the
HTTP request JSON body into an internal `VmConfig` structure.
1. The Cloud Hypervisor HTTP thread creates an
[MPSC](https://doc.rust-lang.org/std/sync/mpsc/) channel for the internal API
server to send its response back.
1. The Cloud Hypervisor HTTP thread prepares an internal API command for creating a
virtual machine. The command's payload is made of the de-serialized
`VmConfig` structure and the response channel:
```Rust
VmCreate(Arc<Mutex<VmConfig>>, Sender<ApiResponse>)
```
1. The Cloud Hypervisor HTTP thread sends the internal API command, and waits
for the response:
```Rust
// Send the VM creation request.
api_sender
.send(ApiRequest::VmCreate(config, response_sender))
.map_err(ApiError::RequestSend)?;
api_evt.write(1).map_err(ApiError::EventFdWrite)?;
response_receiver.recv().map_err(ApiError::ResponseRecv)??;
```
1. The Cloud Hypervisor control loop receives the command, as it listens on the
internal API [MPSC](https://doc.rust-lang.org/std/sync/mpsc/) channel:
```Rust
// Read from the API receiver channel
let api_request = api_receiver.recv().map_err(Error::ApiRequestRecv)?;
```
1. The Cloud Hypervisor control loop matches the received internal API against
the `VmCreate` payload, and extracts both the `VmConfig` structure and the
[Sender](https://doc.rust-lang.org/std/sync/mpsc/struct.Sender.html) from the
command payload. It stores the `VmConfig` structure and replies back to the
sender ((The HTTP thread):
```Rust
match api_request {
ApiRequest::VmCreate(config, sender) => {
// We only store the passed VM config.
// The VM will be created when being asked to boot it.
let response = if self.vm_config.is_none() {
self.vm_config = Some(config);
Ok(ApiResponsePayload::Empty)
} else {
Err(ApiError::VmAlreadyCreated)
};
sender.send(response).map_err(Error::ApiResponseSend)?;
}
```
1. The Cloud Hypervisor HTTP thread receives the internal API command response
as the return value from its `VmCreate` HTTP handler. Depending on the
control loop internal API response, it generates the appropriate HTTP
response:
```Rust
// Call vm_create()
match vm_create(api_notifier, api_sender, Arc::new(Mutex::new(vm_config)))
.map_err(HttpError::VmCreate)
{
Ok(_) => Response::new(Version::Http11, StatusCode::NoContent),
Err(e) => error_response(e, StatusCode::InternalServerError),
}
```
1. The Cloud Hypervisor HTTP thread sends the formed HTTP response back to the
user. This is abstracted by the
[micro_http](https://github.com/firecracker-microvm/firecracker/tree/master/src/micro_http)
crate.

View File

@@ -45,7 +45,7 @@ sudo swupd bundle-add os-installer
wget https://download.clearlinux.org/current/config/image/cloudguest.yaml
sed -i '/size: \"864M\"/d' cloudguest.yaml
sed -i 's/\"800M\"/\"2G\"/g' cloudguest.yaml
sed -i 's/bootloader,/bootloader,\n iperf,/g' cloudguest.yaml
sed -i 's/bootloader,/bootloader,\n curl,\n iperf,/g' cloudguest.yaml
sed -i 's/systemd-networkd-autostart/sysadmin-basic,\n systemd-networkd-autostart/g' cloudguest.yaml
# Create the custom cloudguest image
clr-installer -c cloudguest.yaml

208
docs/device_model.md Normal file
View File

@@ -0,0 +1,208 @@
# Device Model
This document describes the device model supported by `cloud-hypervisor`.
## Summary
| Device | Build configurable | Enabled by default | Runtime configurable |
| :----: | :----: | :----: | :----: |
| Serial port | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| RTC/CMOS | :heavy_check_mark: | :heavy_check_mark: | :negative_squared_cross_mark: |
| I/O APIC | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| i8042 shutdown/reboot | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :negative_squared_cross_mark: |
| ACPI shutdown/reboot | :negative_squared_cross_mark: | :heavy_check_mark: | :negative_squared_cross_mark: |
| virtio-blk | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-console | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-iommu | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-net | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-pmem | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-rng | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| virtio-vsock | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| vhost-user-blk | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| vhost-user-fs | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| vhost-user-net | :negative_squared_cross_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
| VFIO | :heavy_check_mark: | :negative_squared_cross_mark: | :heavy_check_mark: |
## Legacy devices
### Serial port
Simple emulation of a serial port by reading and writing to specific port I/O
addresses. Used as the default console for Linux when booting with the option
`console=ttyS0`, the serial port can be very useful to gather early logs from
the operating system booted inside the VM.
This device is always built-in, and it is disabled by default. It can be
enabled with the `--serial` option, as long as its parameter is not `off`.
### RTC/CMOS
For environments such as Windows or EFI which cannot rely on KVM clock, the
emulation of this legacy device makes the platform usable.
This device is built-in by default, but it can be compiled out with Rust
features. When compiled in, it is always enabled, and cannot be disabled
from the command line.
### I/O APIC
`cloud-hypervisor` supports a so-called split IRQ chip implementation by
implementing support for the [IOAPIC](https://wiki.osdev.org/IOAPIC).
By moving part of the IRQ chip implementation from kernel space to user space,
the IRQ chip emulation does not always run in a fully privileged mode.
The device is always built-in, and it is enabled depending on the presence of
the serial port. If the serial port is disabled, and because no other device
would require pin based interrupts (INTx), the I/O APIC is disabled.
### i8042
Simplified PS/2 port since it supports only one key to trigger a reboot or
shutdown, depending on the ACPI support.
This device is always built-in, but it is disabled by default. Because ACPI is
enabled by default, the handling of reboot/shutdown goes through the dedicated
ACPI device. In case ACPI is disabled, this device is enabled to bring to the
VM some reboot/shutdown support.
### ACPI device
This is a dedicated device for handling ACPI shutdown and reboot when ACPI is
enabled.
This device is always built-in, and it is enabled by default since the ACPI
feature is enabled by default.
## Virtio devices
For all virtio devices listed below, both `virtio-mmio` and `virtio-pci`
transport layers are supported, `virtio-pci` being the default.
Both `virtio-mmio` and `virtio-pci` can be compiled out. `virtio-pci` is
built-in by default, and enabled by default. If both transport layers were
built at the same time, `virtio-pci` would be the default transport layer.
### virtio-block
The `virtio-blk` device exposes a block device to the guest. This device is
usually used to boot the operating system running in the VM.
This device is always built-in, and it is enabled based on the presence of the
flag `--disk`.
### virtio-console
`cloud-hypervisor` exposes a `virtio-console` device to the guest. Although
using this device as a guest console can potentially cut some early boot
messages, it can reduce the guest boot time and provides a complete console
implementation.
This device is always built-in, and it is enabled by default to provide a guest
console. It can be disabled, switching back to the legacy serial port by
selecting `--serial tty --console off` from the command line.
### virtio-iommu
As we want to improve our nested guests support, we added support for exposing
a [paravirtualized IOMMU](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/iommu.md)
device through virtio. This allows for a safer nested virtio and directly
assigned devices support.
This device is always built-in, and it is enabled based on the presence of the
parameter `iommu=on` in any of the virtio or VFIO devices. If at least one of
these devices needs to be connected to the paravirtualized IOMMU, the
`virtio-iommu` device will be created.
### virtio-net
The `virtio-net` device provides network connectivity for the guest, as it
creates a network interface connected to a TAP interface automatically created
by the `cloud-hypervisor` on the host.
This device is always built-in, and it is enabled based on the presence of the
flag `--net`.
### virtio-pmem
The `virtio-pmem` implementation emulates a virtual persistent memory device
that `cloud-hypervisor` can e.g. boot from. Booting from a `virtio-pmem` device
allows to bypass the guest page cache and improve the guest memory footprint.
This device is always built-in, and it is enabled based on the presence of the
flag `--pmem`.
### virtio-rng
A VM does not generate entropy like a real machine would, which is an issue
when workloads running in the guest need random numbers to be generated. The
`virtio-rng` device provides entropy to the guest by relying on the generator
that can be found on the host. By default, the chosen source of entropy is
`/dev/urandom`.
This device is always built-in, and it is always enabled. The `--rng` flag can
be used to change the source of entropy.
### virtio-vsock
In order to more efficiently and securely communicate between host and guest,
we added a hybrid implementation of the [VSOCK](http://man7.org/linux/man-pages/man7/vsock.7.html)
socket address family over virtio.
Credits go to the [Firecracker](https://github.com/firecracker-microvm/firecracker/blob/master/docs/vsock.md)
project as our implementation is a copy of theirs.
This device is always built-in, and it is enabled based on the presence of the
flag `--vsock`.
## Vhost-user devices
Vhost-user devices are virtio backends running outside of the VMM, as its own
separate process. They are usually used to bring more flexibility and increased
isolation.
### vhost-user-blk
As part of the general effort to offload paravirtualized I/O to external
processes, we added support for vhost-user-blk backends. This enables
`cloud-hypervisor` users to plug a `vhost-user` based block device (e.g. SPDK)
into the VMM as their virtio block backend.
This device is always built-in, and it is enabled when `vhost_user=true` and
`socket` are provided to the `--disk` parameter.
### vhost-user-fs
`cloud-hypervisor` supports the [virtio-fs](https://virtio-fs.gitlab.io/)
shared file system, allowing for an efficient and reliable way of sharing
a filesystem between the host and the cloud-hypervisor guest.
See our [filesystem sharing](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/fs.md)
documentation for more details on how to use virtio-fs with cloud-hypervisor.
This device is always built-in, and it is enabled based on the presence of the
flag `--fs`.
### vhost-user-net
As part of the general effort to offload paravirtualized I/O to external
processes, we added support for [vhost-user-net](https://access.redhat.com/solutions/3394851)
backends. This enables `cloud-hypervisor` users to plug a `vhost-user` based
networking device (e.g. DPDK) into the VMM as their virtio network backend.
This device is always built-in, and it is enabled when `vhost_user=true` and
`socket` are provided to the `--net` parameter.
## VFIO
VFIO (Virtual Function I/O) is a kernel framework that exposes direct device
access to userspace. `cloud-hypervisor` uses VFIO to directly assign host
physical devices into its guest.
See our [VFIO documentation](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/vfio.md)
for more details on how to directly assign host devices to `cloud-hypervisor`
guests.
Because VFIO implies `vfio-pci` in the `cloud-hypervisor` context, the VFIO
support is built-in when the `pci` feature is selected. And because the `pci`
feature is built-in by default, VFIO support is also built-in by default.
When VFIO support is built-in, a physical device can be passed through, using
the flag `--device` in order to enable the VFIO code.

View File

@@ -10,11 +10,12 @@ __virtio-fs__, also known as __vhost-user-fs__ is a virtual device defined by th
This virtual device relies on the _vhost-user_ protocol, which assumes the backend (device emulation) is handled by a dedicated process running on the host. This daemon is called __virtiofsd__ and needs to be present on the host.
_Install virtiofsd_
_Build virtiofsd_
```bash
VIRTIOFSD_URL="$(curl --silent https://api.github.com/repos/intel/nemu/releases/latest | grep "browser_download_url" | grep "virtiofsd-x86_64" | grep -o 'https://.*[^ "]')"
wget --quiet $VIRTIOFSD_URL -O "virtiofsd"
chmod +x "virtiofsd"
git clone --depth 1 "https://github.com/sboeuf/qemu.git" -b "virtio-fs" $VIRTIOFSD_DIR
cd $VIRTIOFSD_DIR
./configure --prefix=$PWD --target-list=x86_64-softmmu
make virtiofsd -j `nproc`
sudo setcap cap_sys_admin+epi "virtiofsd"
```
_Create shared directory_
@@ -25,17 +26,20 @@ _Run virtiofsd_
```bash
./virtiofsd \
-d \
-o vhost_user_socket=/tmp/virtiofs \
--socket-path=/tmp/virtiofs \
-o source=/tmp/shared_dir \
-o cache=none
```
The `cache=none` option here is an important one as it tells the daemon not to try any memory mapping of the files, but instead to use the _virtqueues_ to convey the files content. The support for the memory mapping of the files will be added later.
The `cache=none` option should be the default when using `virtiofsd` with the __cloud-hypervisor__ VMM. This prevents from using the guest page cache, which reduces the memory footprint of the guest. When running multiple virtual machines on the same host, this will let the host deal with page cache, which will increase the density of virtual machines which can be launched.
The `cache=always` option will allow for the guest page cache to be used, which will increase the memory footprint of the guest. This option should be used only for specific use cases where a single VM is going to be running on a host.
### The kernel
In order to leverage __virtio-fs__ support from within the guest, and because the code has not been merged in upstream Linux kernel yet, it is required to build a custom kernel embedding the patches.
The following branch `virtio-pmem_and_virtio-fs` on the repository https://github.com/sboeuf/linux.git includes all the needed patches to support __virtio-fs__.
The following branch `virtio-fs-virtio-iommu` on the repository https://github.com/cloud-hypervisor/linux.git includes all the needed patches to support __virtio-fs__.
Make sure to build a kernel out of this branch that can be then used to boot the VM.
@@ -56,15 +60,29 @@ Assuming you have `clear-kvm.img` and `custom-vmlinux.bin` on your system, here
--disk path=clear-kvm.img \
--kernel custom-vmlinux.bin \
--cmdline "console=ttyS0 reboot=k panic=1 nomodules root=/dev/vda3" \
--fs tag=virtiofs,sock=/tmp/virtiofs,num_queues=1,queue_size=512
--fs tag=myfs,sock=/tmp/virtiofs,num_queues=1,queue_size=512
```
By default, DAX is enabled with a cache window of 8GiB. You can specify a custom size (let's say 4GiB for this example) for the cache by explicitly setting DAX and the cache size:
```bash
--fs tag=virtiofs,sock=/tmp/virtiofs,num_queues=1,queue_size=512,dax=on,cache_size=4G
```
In case you don't want to use a shared window of cache to pass the shared files content, this means you will have to explicitly disable DAX with `dax=off`. Note that in this case, the `cache_size` parameter will be ignored.
```bash
--fs tag=virtiofs,sock=/tmp/virtiofs,num_queues=1,queue_size=512,dax=off
```
### Mount the shared directory
The last step is to mount the shared directory inside the guest, using the `virtio_fs` filesystem type.
The last step is to mount the shared directory inside the guest, using the `virtiofs` filesystem type.
```bash
mkdir mount_dir
mount \
-t virtio_fs /dev/null mount_dir/ \
-o tag=virtiofs,rootmode=040000,user_id=0,group_id=0
mount -t virtiofs -o dax myfs mount_dir/
```
The `tag` needs to be consistent with what has been provided through the __cloud-hypervisor__ command line.
The `tag` needs to be consistent with what has been provided through the __cloud-hypervisor__ command line, which happens to be `myfs` in this example.
The `-o dax` option must be removed in case the shared cache region is not enabled from the VMM.

113
docs/hotplug.md Normal file
View File

@@ -0,0 +1,113 @@
# Cloud Hypervisor Hot Plug
Currently Cloud Hypervisor only support hot plugging of CPU devices.
## Kernel support
For hotplug on Cloud Hypervisor ACPI GED support is needed. This can either be achieved by turning on `CONFIG_ACPI_REDUCED_HARDWARE_ONLY`
or by using this kernel patch (available in 5.5rc1 and later): https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/patch/drivers/acpi/Makefile?id=ac36d37e943635fc072e9d4f47e40a48fbcdb3f0
This patch is integrated into the Clear Linux KVM and cloudguest images.
## CPU Hot Plug
Extra vCPUs can be added and removed from a running Cloud Hypervisor instance. This is controlled by two mechanisms:
1. Specifying a number of maximum potential vCPUs that is greater than the number of default (boot) vCPUs.
2. Making a HTTP API request to the VMM to ask for the additional vCPUs to be added.
To use CPU hotplug start the VM with the number of max vCPUs greater than the number of boot vCPUs, e.g.
```shell
$ pushd $CLOUDH
$ sudo setcap cap_net_admin+ep ./cloud-hypervisor/target/release/cloud-hypervisor
$ ./cloud-hypervisor/target/release/cloud-hypervisor \
--kernel ./hypervisor-fw \
--disk path=clear-31890-kvm.img \
--cpus boot=4,max=8 \
--memory size=1024M \
--net "tap=,mac=,ip=,mask=" \
--rng \
--api-socket=/tmp/ch-socket
$ popd
```
Notice the addition of `--api-socket=/tmp/ch-socket` and a `max` parameter on `--cpus boot=4.max=8`.
To ask the VMM to add additional vCPUs then use the resize API:
```shell
curl -H "Accept: application/json" -H "Content-Type: application/json" -i -XPUT --unix-socket /tmp/ch-socket -d "{ \"desired_vcpus\":8}" http://localhost/api/v1/vm.resize
```
The extra vCPU threads will be created and advertised to the running kernel. The kernel does not bring up the CPUs immediately and instead the user must "online" them from inside the VM:
```shell
root@ch-guest ~ # lscpu | grep list:
On-line CPU(s) list: 0-3
Off-line CPU(s) list: 4-7
root@ch-guest ~ # echo 1 | tee /sys/devices/system/cpu/cpu[4,5,6,7]/online
1
root@ch-guest ~ # lscpu | grep list:
On-line CPU(s) list: 0-7
```
After a reboot the added CPUs will remain.
Removing CPUs works similarly by reducing the number in the "desired_vcpus" field of the reisze API. The CPUs will be automatically offlined inside the guest so there is no need to run any commands inside the guest:
```shell
curl -H "Accept: application/json" -H "Content-Type: application/json" -i -XPUT --unix-socket /tmp/ch-socket -d "{ \"desired_vcpus\":2}" http://localhost/api/v1/vm.resize
```
As per adding CPUs to the guest, after a reboot the VM will be running with the reduced number of vCPUs.
## Memory Hot Plug
Extra memory can be added from a runing Cloud Hypervisor instance. This is controlled by two mechanisms:
1. Allocating some of the guest physical address space for hotplug memory.
2. Making a HTTP API request to the VMM to ask for a new amount of RAM to be assigned to the VM. In the case of expanding the memory for the VM the new memory will be hotplugged into the running VM, if reducing the size of the memory then change will take effect after the next reboot.
To use memory hotplug start the VM specifying some size RAM in the "hotplug_size" parameter to the memory configuration. Not all the memory specified in this parameter will be available to hotplug as there are spacing and alignment requirements so it is recommended to make it larger than the hotplug RAM needed.
```shell
$ pushd $CLOUDH
$ sudo setcap cap_net_admin+ep ./cloud-hypervisor/target/release/cloud-hypervisor
$ ./cloud-hypervisor/target/release/cloud-hypervisor \
--kernel ./hypervisor-fw \
--disk path=clear-31890-kvm.img \
--cpus boot=4,max=8 \
--memory size=1024M,hotplug_size=8192M \
--net "tap=,mac=,ip=,mask=" \
--rng \
--api-socket=/tmp/ch-socket
$ popd
```
Before issuing the API request it is necessary to run the following command inside the VM to make it automatically online the added memory:
```shell
root@ch-guest ~ # echo online | sudo tee /sys/devices/system/memory/auto_online_blocks
```
To ask the VMM to add expand the RAM for the VM (request is in bytes):
```shell
curl -H "Accept: application/json" -H "Content-Type: application/json" -i -XPUT --unix-socket /tmp/ch-socket -d "{ \"desired_vcpus\": 4, \"desired_ram\" : 3221225472}" http://localhost/api/v1/vm.resize
```
The new memory is now available to use inside the VM:
```shell
free -h
total used free shared buff/cache available
Mem: 3.0Gi 71Mi 2.8Gi 0.0Ki 47Mi 2.8Gi
Swap: 32Mi 0B 32Mi
```
Due to guest OS limitations is is necessary to ensure that amount of memory added (between currently assigned RAM and that which is desired) is a multiple of 128MiB.
The same API can also be used to reduce the desired RAM for a VM but the change will not be applied until the VM is rebooted.
Memory and CPU resizing can be combined together into the same HTTP API request.

View File

@@ -1,6 +1,21 @@
# How to use networking
cloud-hypervisor can emulate one or more virtual network interfaces, represented at the hypervisor host by [tap devices](https://www.kernel.org/doc/Documentation/networking/tuntap.txt"). This guide briefly describes, in a manual and distribution neutral way, how to setup and use networking with cloud-hypevisor.
cloud-hypervisor can emulate one or more virtual network interfaces, represented at the hypervisor host by [tap devices](https://www.kernel.org/doc/Documentation/networking/tuntap.txt). This guide briefly describes, in a manual and distribution neutral way, how to setup and use networking with cloud-hypevisor.
## Multiple queue support for net devices ##
While multiple vcpus defined for guest, to gain the benefit of vcpu scalable to improve performance, it suggests to define multiple queue pairs for net devices, one Tx/Rx queue pair per one vcpu, that means the number of queue pairs at least is equal to the vcpu count. In that case, after virtnet driver set cpu affinity for virtqueues in guest kernel, vcpus could handle interrupt from different virtqueue pairs in parallel.
It will gain better performance for guest that has multiple queues defined for net devices while it has multiple net sessions running in userspace.
To enable multiple queue support in cloud-hypervisor, multiple queue pairs will be defined, while multiple tap fds will be opened for the same tap device, it will also have multiple threads started, each thread will monitor and handle the events from each virtqueue pairs and the associated tap fd.
Note:
- Currently, it does not support to use ethtool to change the combined queue numbers in guest.
- Multiple queue is enabled for vhost-user-net backend in cloud-hypervisor, however, multiple thread is not added to handle mq, thus, the performance for vhost-user-net backend is not supposed to be improved. The multiple thread will be added for backend later.
- Performance test for vhost-user-net will be covered once vhost-user-net backend has mulitple thread supported.
- Performance test for virtio-net is done by comparing 2 queue pairs with 1 queue pairs, that to run 2 iperf3 sessions in the same test environments, throughput is improved about 37%.
## Start cloud-hypervisor with net devices
@@ -13,18 +28,34 @@ Use one `--net` command-line argument from cloud-hypervisor to specify the emula
--disk path=my-root-disk.img \
--kernel my-vmlinux.bin \
--cmdline "console=ttyS0 reboot=k panic=1 nomodules root=/dev/vda3" \
--net tap=ich0,mac=a4:a1:c2:00:00:01,ip=192.168.4.2,mask=255.255.255.0 \
tap=ich1,mac=a4:a1:c2:00:00:02,ip=10.0.1.2,mask=255.255.255.0
--net tap=ich0,mac=a4:a1:c2:00:00:01,ip=192.168.4.2,mask=255.255.255.0,num_queues=2,queue_size=256 \
tap=ich1,mac=a4:a1:c2:00:00:02,ip=10.0.1.2,mask=255.255.255.0,num_queues=2,queue_size=256
```
The `--net` argument takes 1 or more space-separated strings of key value pairs containing the following 4 keys or fields:
| Name | Purpose | Optional |
| -------- |----------------------------| ----------|
| tap | tap device name | Yes |
| mac | vNIC mac address | Yes |
| ip | tap IP IP address | yes |
| mask | tap IP netmask | Yes |
| Name | Purpose | Optional |
| -----------|----------------------------| ----------|
| tap | tap device name | Yes |
| mac | vNIC mac address | Yes |
| ip | tap IP IP address | yes |
| mask | tap IP netmask | Yes |
| num_queues | the number of queues | yes |
| queue_size | the size of each queue | Yes |
num_queues is the total number of tx and rx queues, the default value is 2, and it could be increased by multiples of 2. Additionally, num_queues is suggested to be as 2 times of vcpu count. The default value for queue_size is 256.
If the tap device is pre-created on host before guest boot up. To use multiple queue support for net device in guest, the tap device should be opened like this from host.
```bash
[root@localhost ~]# ip tuntap add name ich0 mode tap multi_queue
```
And the `--net` device should specify support for multiple queues. `num_queues` must be a multiple of 2 starting at least from 4 since multiple queues really means multiple queue pairs. We need at least 2 pairs for this configuration to be correct:
```bash
--net tap=ich0,mac=a4:a1:c2:00:00:01,ip=192.168.4.2,mask=255.255.255.0,num_queues=4,queue_size=256
```
## Configure the tap devices

View File

@@ -0,0 +1,104 @@
# How to test vhost-user-blk with SPDK
The purpose of this document is to illustrate how to test vhost-user-blk in Cloud Hypervisor with SPDK as the backend.
## Framework
It's a simple test to validate the block read/write between VM and block backend.
```
+----+----------+ +-------------+-----------+
| | | | | |
| |vhost-user|----------| vhost-user | dpdk |
| |blk device| | port 1 | |
| | | | | |
| +----------+ +-------------+-----------+
| | | |
| vm | | spdk |
| | | |
+--+----------------------------------------------------+--+
| | hugepages | |
| +----------------------------------------------------+ |
| |
| host |
| |
+----------------------------------------------------------+
```
## Prerequisites
Prior to running the test, the following steps need to be performed.
- Enable hugepages
- Install SPDK
Here are some good references for detailing them.
- spdk
* https://spdk.io/doc/
## Test environment
The below test environment is based on ubuntu release(16.04.1 LTS), as for other system, please check related document.
The test runs with multiple queue (MQ) support enabled, using 4 queues defined for both SPDK and the virtual machine.
Here are the details on how the test can be run.
### The hugepages settings in host linux
Add "default_hugepagesz=1G hugepagesz=1G hugepages=2" into host linux cmdline.
As for how to change Ubuntu linux cmdline in grub file, please ref below link:
https://www.ostechnix.com/configure-grub-2-boot-loader-settings-ubuntu-16-04/
reboot Ubuntu
sudo mount -t hugetlbfs -o pagesize=1G none /dev/hugepages
### Download the SPDK code
git clone https://github.com/spdk/spdk
cd spdk
git submodule update --init
### Create the build dep
./scripts/pkgdep.sh
### Build spdk
./configure
make
### Set the SPDk environment
sudo HUGEMEM=2048 scripts/setup.sh
sudo ./app/vhost/vhost -S /var/tmp -s 1024 -m 0x3 &
### Create 512M block device
sudo scripts/rpc.py bdev_malloc_create 512 512 -b Malloc0
sudo scripts/rpc.py vhost_create_blk_controller --cpumask 0x1 vhost.1 Malloc0
_Launch the VM_
VMs run in client mode. They connect to the socket created by the `dpdkvhostuser` in the SPDK backend.
```bash
# From the test terminal. We need to create one vhost-user-blk device for the --disk.
./cloud-hypervisor \
--cpus boot=4 \
--memory size=1024M,file=/dev/hugepages \
--kernel linux/arch/x86/boot/compressed/vmlinux.bin \
--cmdline "console=ttyS0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3 iommu=off" \
--disk "path=images/clear-kvm.img" "num_queues=4,queue_size=128,vhost_user=true,socket=/var/tmp/vhost.1,wce=true" \
--console off \
--serial tty \
--rng
```
```bash
# How to test the vhost-user-blk device with SPDK backend
login in guest
# Use lsblk command to find out vhost-user-blk device
lsblk
NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
vda 253:0 0 8.5G 0 disk
├─vda1 253:1 0 511M 0 part
├─vda2 253:2 0 32M 0 part [SWAP]
└─vda3 253:3 0 8G 0 part /
vdb 253:16 0 512M 0 disk
The vhost-user-blk device is /dev/vdb
# How to do simple read/write test
dd if=/dev/vdb of=/dev/null bs=2M iflag=direct
dd of=/dev/vdb if=/dev/zero bs=2M oflag=direct count=256
If you want to do fio test, please install fio binary into guest. The detailed info is not listed here.

View File

@@ -0,0 +1,132 @@
# How to test Vhost-user net with OpenVSwitch/DPDK
The purpose of this document is to illustrate how to test vhost-user-net in cloud-hypervisor with OVS/DPDK as the backend.
## Framework
It's a simple test to validate the communication between two virtual machine, connecting them to vhost-user ports respectively provided by `OVS/DPDK`.
```
+----+----------+ +-------------+-----------+-------------+ +----------+----+
| | | | | | | | | |
| |vhost-user|----------| vhost-user | ovs | vhost-user |----------|vhost-user| |
| |net device| | port 1 | | port 2 | |net device| |
| | | | | | | | | |
| +----------+ +-------------+-----------+-------------+ +----------+ |
| | | | | |
|vm1 | | dpdk | | vm2 |
| | | | | |
+--+---------------------------------------------------------------------------------------------+--+
| | hugepages | |
| +---------------------------------------------------------------------------------------------+ |
| |
| host |
| |
+---------------------------------------------------------------------------------------------------+
```
## Prerequisites
Prior to running the test, the following steps need to be performed.
- Enable hugepages
- Install DPDK
- Install OVS
Here are some good references for detailing them.
- Red Hat
* https://wiki.qemu.org/Documentation/vhost-user-ovs-dpdk
- Ubuntu server
* https://help.ubuntu.com/lts/serverguide/DPDK.html
* https://software.intel.com/en-us/articles/set-up-open-vswitch-with-dpdk-on-ubuntu-server
## Test
The test runs with multiple queue (MQ) support enabled, using 2 pairs of TX/RX queues defined for both OVS and the virtual machine. Here are the details on how the test can be run.
_Setup OVS_
`ovs_test.sh` is created to setup and start OVS. OVS will provide the `dpdkvhostuser` backend running in server mode.
```bash
mkdir -p /var/run/openvswitch
modprobe openvswitch
killall ovsdb-server ovs-vswitchd
rm -f /var/run/openvswitch/vhost-user*
rm -f /etc/openvswitch/conf.db
export DB_SOCK=/var/run/openvswitch/db.sock
ovsdb-tool create /etc/openvswitch/conf.db /usr/share/openvswitch/vswitch.ovsschema
ovsdb-server --remote=punix:$DB_SOCK --remote=db:Open_vSwitch,Open_vSwitch,manager_options --pidfile --detach
ovs-vsctl --no-wait init
ovs-vsctl --no-wait set Open_vSwitch . other_config:dpdk-lcore-mask=0xf
ovs-vsctl --no-wait set Open_vSwitch . other_config:dpdk-socket-mem=1024
ovs-vsctl --no-wait set Open_vSwitch . other_config:dpdk-init=true
ovs-vsctl --no-wait set Open_vSwitch . other_config:pmd-cpu-mask=0xf
ovs-vswitchd unix:$DB_SOCK --pidfile --detach --log-file=/var/log/openvswitch/ovs-vswitchd.log
ovs-vsctl add-br ovsbr0 -- set bridge ovsbr0 datapath_type=netdev
ovs-vsctl add-port ovsbr0 vhost-user1 -- set Interface vhost-user1 type=dpdkvhostuser
ovs-vsctl add-port ovsbr0 vhost-user2 -- set Interface vhost-user2 type=dpdkvhostuser
ovs-vsctl set Interface vhost-user1 options:n_rxq=2
ovs-vsctl set Interface vhost-user2 options:n_rxq=2
```
_Run ovs_test.sh_
```bash
./ovs_test.sh
```
_Launch the VMs_
VMs run in client mode. They connect to the socket created by the `dpdkvhostuser` backend.
```bash
# From one terminal. We need to give the cloud-hypervisor binary the NET_ADMIN capabilities for it to set TAP interfaces up on the host.
./cloud-hypervisor \
--cpus boot=2 \
--memory size=512M,file=/dev/hugepages \
--kernel vmlinux \
--cmdline "reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3" \
--disk path=clear-kvm.img \
--net "mac=52:54:00:02:d9:01,vhost_user=true,socket=/var/run/openvswitch/vhost-user1,num_queues=4"
# From another terminal. We need to give the cloud-hypervisor binary the NET_ADMIN capabilities for it to set TAP interfaces up on the host.
./cloud-hypervisor \
--cpus boot=2 \
--memory size=512M,file=/dev/hugepages \
--kernel vmlinux \
--cmdline "reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda3" \
--disk path=clear-kvm.img \
--net "mac=52:54:20:11:C5:02,vhost_user=true,socket=/var/run/openvswitch/vhost-user2,num_queues=4"
```
_Setup VM1_
```bash
# From inside the guest
sudo ip addr add 172.100.0.1/24 dev enp0s3
```
_Setup VM2_
```bash
# From inside the guest
sudo ip addr add 172.100.0.2/24 dev enp0s3
```
_Ping VM1 from VM2_
```bash
# From inside the guest
sudo ping 172.100.0.1
```
_Ping VM2 from VM1_
```bash
# From inside the guest
sudo ping 172.100.0.2
```
__Result:__ At this point, VM1 and VM2 can ping each other successfully. We can now run `iperf3` test.
_Run VM1 as server_
```bash
# From inside the guest
iperf3 -s -p 4444
```
_Run VM2 as client_
```bash
# From inside the guest
iperf3 -c 172.100.0.1 -t 30 -p 4444 &
```

View File

@@ -4,4 +4,4 @@ version = "0.1.0"
authors = ["The Chromium OS Authors"]
[dependencies]
vmm-sys-util = "0.1.1"
vmm-sys-util = ">=0.3.1"

View File

@@ -4,14 +4,14 @@ version = "0.1.0"
authors = ["The Chromium OS Authors"]
[dependencies]
libc = "0.2.60"
rand = "0.7.0"
serde = "1.0.98"
vmm-sys-util = "0.1.1"
libc = "0.2.69"
rand = "0.7.3"
serde = "1.0.106"
vmm-sys-util = ">=0.3.1"
net_gen = { path = "../net_gen" }
[dev-dependencies]
lazy_static = "1.3.0"
pnet = "0.22.0"
serde_json = "1.0.40"
pnet = "0.25.0"
serde_json = "1.0.52"

View File

@@ -7,7 +7,9 @@
use rand::Rng;
use std::fmt;
use std::io;
use std::result::Result;
use std::str::FromStr;
use serde::de::{Deserialize, Deserializer, Error};
use serde::ser::{Serialize, Serializer};
@@ -20,23 +22,31 @@ pub struct MacAddr {
}
impl MacAddr {
// The error contains the str that failed to be parsed, for nicer error message generation.
pub fn parse_str<S>(s: &S) -> Result<MacAddr, &str>
pub fn parse_str<S>(s: &S) -> Result<MacAddr, io::Error>
where
S: AsRef<str> + ?Sized,
{
let v: Vec<&str> = s.as_ref().split(':').collect();
let mut bytes = [0u8; MAC_ADDR_LEN];
let common_err = Err(io::Error::new(
io::ErrorKind::Other,
format!("parsing of {} into a MAC address failed", s.as_ref()),
));
if v.len() != MAC_ADDR_LEN {
return Err(s.as_ref());
return common_err;
}
for i in 0..MAC_ADDR_LEN {
if v[i].len() != 2 {
return Err(s.as_ref());
return common_err;
}
bytes[i] = u8::from_str_radix(v[i], 16).map_err(|_| s.as_ref())?;
bytes[i] = u8::from_str_radix(v[i], 16).map_err(|e| {
io::Error::new(
io::ErrorKind::Other,
format!("parsing of {} into a MAC address failed: {}", s.as_ref(), e),
)
})?;
}
Ok(MacAddr { bytes })
@@ -106,7 +116,20 @@ impl<'de> Deserialize<'de> for MacAddr {
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
MacAddr::parse_str(&s).map_err(|_| D::Error::custom("The provided MAC address is invalid."))
MacAddr::parse_str(&s)
.map_err(|e| D::Error::custom(format!("The provided MAC address is invalid: {}", e)))
}
}
pub enum MacAddrParseError {
InvalidValue(String),
}
impl FromStr for MacAddr {
type Err = MacAddrParseError;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
MacAddr::parse_str(s).map_err(|_| MacAddrParseError::InvalidValue(s.to_owned()))
}
}

View File

@@ -20,8 +20,12 @@ use vmm_sys_util::ioctl::{ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val};
pub enum Error {
/// Couldn't open /dev/net/tun.
OpenTun(IoError),
/// Unable to create tap interface.
CreateTap(IoError),
/// Unable to configure tap interface.
ConfigureTap(IoError),
/// Unable to retrieve features.
GetFeatures(IoError),
/// Missing multiqueue support in the kernel.
MultiQueueKernelSupport,
/// ioctl failed.
IoctlError(IoError),
/// Failed to create a socket.
@@ -40,7 +44,7 @@ pub type Result<T> = ::std::result::Result<T, Error>;
#[derive(Debug)]
pub struct Tap {
tap_file: File,
if_name: [u8; 16usize],
if_name: Vec<u8>,
}
impl PartialEq for Tap {
@@ -53,7 +57,7 @@ impl std::clone::Clone for Tap {
fn clone(&self) -> Self {
Tap {
tap_file: self.tap_file.try_clone().unwrap(),
if_name: self.if_name,
if_name: self.if_name.clone(),
}
}
}
@@ -78,7 +82,7 @@ fn build_terminated_if_name(if_name: &str) -> Result<Vec<u8>> {
}
impl Tap {
pub fn open_named(if_name: &str) -> Result<Tap> {
pub fn open_named(if_name: &str, num_queue_pairs: usize) -> Result<Tap> {
let terminated_if_name = build_terminated_if_name(if_name)?;
let fd = unsafe {
@@ -96,6 +100,20 @@ impl Tap {
// We just checked that the fd is valid.
let tuntap = unsafe { File::from_raw_fd(fd) };
// Let's validate some features before going any further.
// ioctl is safe since we call it with a valid tap fd and check the return
// value.
let mut features = 0;
let ret = unsafe { ioctl_with_mut_ref(&tuntap, net_gen::TUNGETFEATURES(), &mut features) };
if ret < 0 {
return Err(Error::GetFeatures(IoError::last_os_error()));
}
// Check if the user parameters match the kernel support for MQ
if (features & net_gen::IFF_MULTI_QUEUE == 0) && num_queue_pairs > 1 {
return Err(Error::MultiQueueKernelSupport);
}
// This is pretty messy because of the unions used by ifreq. Since we
// don't call as_mut on the same union field more than once, this block
// is safe.
@@ -107,26 +125,31 @@ impl Tap {
name_slice.copy_from_slice(terminated_if_name.as_slice());
*ifru_flags =
(net_gen::IFF_TAP | net_gen::IFF_NO_PI | net_gen::IFF_VNET_HDR) as c_short;
if num_queue_pairs > 1 {
*ifru_flags |= net_gen::IFF_MULTI_QUEUE as c_short;
}
}
// ioctl is safe since we call it with a valid tap fd and check the return
// value.
let ret = unsafe { ioctl_with_mut_ref(&tuntap, net_gen::TUNSETIFF(), &mut ifreq) };
if ret < 0 {
return Err(Error::CreateTap(IoError::last_os_error()));
return Err(Error::ConfigureTap(IoError::last_os_error()));
}
let if_name_temp = unsafe { *ifreq.ifr_ifrn.ifrn_name.as_ref() };
let mut if_name = if_name_temp.to_vec();
if_name.truncate(terminated_if_name.len() - 1);
// Safe since only the name is accessed, and it's cloned out.
Ok(Tap {
tap_file: tuntap,
if_name: unsafe { *ifreq.ifr_ifrn.ifrn_name.as_ref() },
if_name,
})
}
/// Create a new tap interface.
pub fn new() -> Result<Tap> {
Self::open_named("vmtap%d")
pub fn new(num_queue_pairs: usize) -> Result<Tap> {
Self::open_named("vmtap%d", num_queue_pairs)
}
/// Set the host-side IP address for the tap interface.
@@ -232,11 +255,16 @@ impl Tap {
// in a single-field union.
unsafe {
let ifrn_name = ifreq.ifr_ifrn.ifrn_name.as_mut();
ifrn_name.clone_from_slice(&self.if_name);
let name_slice = &mut ifrn_name[..self.if_name.len()];
name_slice.copy_from_slice(&self.if_name);
}
ifreq
}
pub fn get_if_name(&self) -> Vec<u8> {
self.if_name.clone()
}
}
impl Read for Tap {
@@ -423,7 +451,7 @@ mod tests {
#[test]
fn test_tap_create() {
let t = Tap::new().unwrap();
let t = Tap::new(1).unwrap();
println!("created tap: {:?}", t);
}
@@ -435,7 +463,7 @@ mod tests {
// the end of the function.
let tap_ip_guard = TAP_IP_LOCK.lock().unwrap();
let tap = Tap::new().unwrap();
let tap = Tap::new(1).unwrap();
let ip_addr: net::Ipv4Addr = (*tap_ip_guard).parse().unwrap();
let netmask: net::Ipv4Addr = SUBNET_MASK.parse().unwrap();
@@ -448,21 +476,21 @@ mod tests {
#[test]
fn test_set_options() {
// This line will fail to provide an initialized FD if the test is not run as root.
let tap = Tap::new().unwrap();
let tap = Tap::new(1).unwrap();
tap.set_vnet_hdr_size(16).unwrap();
tap.set_offload(0).unwrap();
}
#[test]
fn test_tap_enable() {
let tap = Tap::new().unwrap();
let tap = Tap::new(1).unwrap();
let ret = tap.enable();
assert!(ret.is_ok());
}
#[test]
fn test_tap_get_ifreq() {
let tap = Tap::new().unwrap();
let tap = Tap::new(1).unwrap();
let ret = tap.get_ifreq();
assert_eq!(
"__BindgenUnionField",
@@ -472,7 +500,7 @@ mod tests {
#[test]
fn test_raw_fd() {
let tap = Tap::new().unwrap();
let tap = Tap::new(1).unwrap();
assert_eq!(tap.as_raw_fd(), tap.tap_file.as_raw_fd());
}
@@ -480,7 +508,7 @@ mod tests {
fn test_read() {
let tap_ip_guard = TAP_IP_LOCK.lock().unwrap();
let mut tap = Tap::new().unwrap();
let mut tap = Tap::new(1).unwrap();
tap.set_ip_addr((*tap_ip_guard).parse().unwrap()).unwrap();
tap.set_netmask(SUBNET_MASK.parse().unwrap()).unwrap();
tap.enable().unwrap();
@@ -541,7 +569,7 @@ mod tests {
fn test_write() {
let tap_ip_guard = TAP_IP_LOCK.lock().unwrap();
let mut tap = Tap::new().unwrap();
let mut tap = Tap::new(1).unwrap();
tap.set_ip_addr((*tap_ip_guard).parse().unwrap()).unwrap();
tap.set_netmask(SUBNET_MASK.parse().unwrap()).unwrap();
tap.enable().unwrap();

View File

@@ -6,11 +6,9 @@ edition = "2018"
[dependencies]
vm-allocator = { path = "../vm-allocator" }
byteorder = "1.3.2"
byteorder = "1.3.4"
devices = { path = "../devices" }
kvm-bindings = "0.1.1"
kvm-ioctls = { git = "https://github.com/rust-vmm/kvm-ioctls", branch = "master" }
libc = "0.2.60"
libc = "0.2.69"
log = "0.4.8"
vm-memory = { git = "https://github.com/rust-vmm/vm-memory" }
vmm-sys-util = "0.1.1"
vm-device = { path = "../vm-device" }
vm-memory = "0.2.0"

View File

@@ -5,16 +5,19 @@
use crate::configuration::{
PciBarRegionType, PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType,
};
use crate::device::{Error as PciDeviceError, PciDevice};
use crate::device::{DeviceRelocation, Error as PciDeviceError, PciDevice};
use byteorder::{ByteOrder, LittleEndian};
use devices::BusDevice;
use std;
use std::sync::Arc;
use std::sync::Mutex;
use std::any::Any;
use std::collections::HashMap;
use std::ops::DerefMut;
use std::sync::{Arc, Mutex};
use vm_memory::{Address, GuestAddress, GuestUsize};
const VENDOR_ID_INTEL: u16 = 0x8086;
const DEVICE_ID_INTEL_VIRT_PCIE_HOST: u16 = 0x0d57;
const NUM_DEVICE_IDS: usize = 32;
/// Errors for device manager.
#[derive(Debug)]
@@ -27,6 +30,10 @@ pub enum PciRootError {
PioInsert(devices::BusError),
/// Could not add a device to the mmio bus.
MmioInsert(devices::BusError),
/// Could not find an available device slot on the PCI bus.
NoPciDeviceSlotAvailable,
/// Invalid PCI device identifier provided.
InvalidPciDeviceSlot(usize),
}
pub type Result<T> = std::result::Result<T, PciRootError>;
@@ -46,6 +53,7 @@ impl PciRoot {
config: PciConfiguration::new(
VENDOR_ID_INTEL,
DEVICE_ID_INTEL_VIRT_PCIE_HOST,
0,
PciClassCode::BridgeDevice,
&PciBridgeSubclass::HostBridge,
None,
@@ -66,31 +74,43 @@ impl PciDevice for PciRoot {
self.config.write_config_register(reg_idx, offset, data);
}
fn read_config_register(&self, reg_idx: usize) -> u32 {
fn read_config_register(&mut self, reg_idx: usize) -> u32 {
self.config.read_reg(reg_idx)
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
pub struct PciBus {
/// Devices attached to this bus.
/// Device 0 is host bridge.
devices: Vec<Arc<Mutex<dyn PciDevice>>>,
devices: HashMap<u32, Arc<Mutex<dyn PciDevice>>>,
device_reloc: Arc<dyn DeviceRelocation>,
device_ids: Vec<bool>,
}
impl PciBus {
pub fn new(pci_root: PciRoot) -> Self {
let mut devices: Vec<Arc<Mutex<dyn PciDevice>>> = Vec::new();
pub fn new(pci_root: PciRoot, device_reloc: Arc<dyn DeviceRelocation>) -> Self {
let mut devices: HashMap<u32, Arc<Mutex<dyn PciDevice>>> = HashMap::new();
let mut device_ids: Vec<bool> = vec![false; NUM_DEVICE_IDS];
devices.push(Arc::new(Mutex::new(pci_root)));
devices.insert(0, Arc::new(Mutex::new(pci_root)));
device_ids[0] = true;
PciBus { devices }
PciBus {
devices,
device_reloc,
device_ids,
}
}
pub fn register_mapping(
&self,
dev: Arc<Mutex<dyn BusDevice>>,
io_bus: &mut devices::Bus,
mmio_bus: &mut devices::Bus,
io_bus: &devices::Bus,
mmio_bus: &devices::Bus,
bars: Vec<(GuestAddress, GuestUsize, PciBarRegionType)>,
) -> Result<()> {
for (address, size, type_) in bars {
@@ -110,13 +130,38 @@ impl PciBus {
Ok(())
}
pub fn add_device(&mut self, device: Arc<Mutex<dyn PciDevice>>) -> Result<()> {
self.devices.push(device);
pub fn add_device(
&mut self,
pci_device_bdf: u32,
device: Arc<Mutex<dyn PciDevice>>,
) -> Result<()> {
self.devices.insert(pci_device_bdf >> 3, device);
Ok(())
}
pub fn next_device_id(&self) -> u32 {
self.devices.len() as u32
pub fn remove_by_device(&mut self, device: &Arc<Mutex<dyn PciDevice>>) -> Result<()> {
self.devices.retain(|_, dev| !Arc::ptr_eq(dev, device));
Ok(())
}
pub fn next_device_id(&mut self) -> Result<u32> {
for (idx, device_id) in self.device_ids.iter_mut().enumerate() {
if !(*device_id) {
*device_id = true;
return Ok(idx as u32);
}
}
Err(PciRootError::NoPciDeviceSlotAvailable)
}
pub fn put_device_id(&mut self, id: usize) -> Result<()> {
if id < NUM_DEVICE_IDS {
self.device_ids[id] = false;
Ok(())
} else {
Err(PciRootError::InvalidPciDeviceSlot(id))
}
}
}
@@ -141,7 +186,7 @@ impl PciConfigIo {
}
let (bus, device, function, register) =
parse_config_address(self.config_address & !0x8000_0000);
parse_io_config_address(self.config_address & !0x8000_0000);
// Only support one bus.
if bus != 0 {
@@ -157,7 +202,7 @@ impl PciConfigIo {
.lock()
.unwrap()
.devices
.get(device)
.get(&(device as u32))
.map_or(0xffff_ffff, |d| {
d.lock().unwrap().read_config_register(register)
})
@@ -174,17 +219,36 @@ impl PciConfigIo {
}
let (bus, device, _function, register) =
parse_config_address(self.config_address & !0x8000_0000);
parse_io_config_address(self.config_address & !0x8000_0000);
// Only support one bus.
if bus != 0 {
return;
}
if let Some(d) = self.pci_bus.lock().unwrap().devices.get(device) {
d.lock()
.unwrap()
.write_config_register(register, offset, data);
let pci_bus = self.pci_bus.lock().unwrap();
if let Some(d) = pci_bus.devices.get(&(device as u32)) {
let mut device = d.lock().unwrap();
// Find out if one of the device's BAR is being reprogrammed, and
// reprogram it if needed.
if let Some(params) = device.detect_bar_reprogramming(register, data) {
if let Err(e) = pci_bus.device_reloc.move_bar(
params.old_base,
params.new_base,
params.len,
device.deref_mut(),
params.region_type,
) {
error!(
"Failed moving device BAR: {}: 0x{:x}->0x{:x}(0x{:x})",
e, params.old_base, params.new_base, params.len
);
}
}
// Update the register value
device.write_config_register(register, offset, data);
}
}
@@ -252,7 +316,7 @@ impl PciConfigMmio {
}
fn config_space_read(&self, config_address: u32) -> u32 {
let (bus, device, _function, register) = parse_config_address(config_address);
let (bus, device, _function, register) = parse_mmio_config_address(config_address);
// Only support one bus.
if bus != 0 {
@@ -263,7 +327,7 @@ impl PciConfigMmio {
.lock()
.unwrap()
.devices
.get(device)
.get(&(device as u32))
.map_or(0xffff_ffff, |d| {
d.lock().unwrap().read_config_register(register)
})
@@ -274,17 +338,36 @@ impl PciConfigMmio {
return;
}
let (bus, device, _function, register) = parse_config_address(config_address);
let (bus, device, _function, register) = parse_mmio_config_address(config_address);
// Only support one bus.
if bus != 0 {
return;
}
if let Some(d) = self.pci_bus.lock().unwrap().devices.get(device) {
d.lock()
.unwrap()
.write_config_register(register, offset, data);
let pci_bus = self.pci_bus.lock().unwrap();
if let Some(d) = pci_bus.devices.get(&(device as u32)) {
let mut device = d.lock().unwrap();
// Find out if one of the device's BAR is being reprogrammed, and
// reprogram it if needed.
if let Some(params) = device.detect_bar_reprogramming(register, data) {
if let Err(e) = pci_bus.device_reloc.move_bar(
params.old_base,
params.new_base,
params.len,
device.deref_mut(),
params.region_type,
) {
error!(
"Failed moving device BAR: {}: 0x{:x}->0x{:x}(0x{:x})",
e, params.old_base, params.new_base, params.len
);
}
}
// Update the register value
device.write_config_register(register, offset, data);
}
}
}
@@ -315,8 +398,33 @@ impl BusDevice for PciConfigMmio {
}
}
fn shift_and_mask(value: u32, offset: usize, mask: u32) -> usize {
((value >> offset) & mask) as usize
}
// Parse the MMIO address offset to a (bus, device, function, register) tuple.
// See section 7.2.2 PCI Express Enhanced Configuration Access Mechanism (ECAM)
// from the Pci Express Base Specification Revision 5.0 Version 1.0.
fn parse_mmio_config_address(config_address: u32) -> (usize, usize, usize, usize) {
const BUS_NUMBER_OFFSET: usize = 20;
const BUS_NUMBER_MASK: u32 = 0x00ff;
const DEVICE_NUMBER_OFFSET: usize = 15;
const DEVICE_NUMBER_MASK: u32 = 0x1f;
const FUNCTION_NUMBER_OFFSET: usize = 12;
const FUNCTION_NUMBER_MASK: u32 = 0x07;
const REGISTER_NUMBER_OFFSET: usize = 2;
const REGISTER_NUMBER_MASK: u32 = 0x3ff;
(
shift_and_mask(config_address, BUS_NUMBER_OFFSET, BUS_NUMBER_MASK),
shift_and_mask(config_address, DEVICE_NUMBER_OFFSET, DEVICE_NUMBER_MASK),
shift_and_mask(config_address, FUNCTION_NUMBER_OFFSET, FUNCTION_NUMBER_MASK),
shift_and_mask(config_address, REGISTER_NUMBER_OFFSET, REGISTER_NUMBER_MASK),
)
}
// Parse the CONFIG_ADDRESS register to a (bus, device, function, register) tuple.
fn parse_config_address(config_address: u32) -> (usize, usize, usize, usize) {
fn parse_io_config_address(config_address: u32) -> (usize, usize, usize, usize) {
const BUS_NUMBER_OFFSET: usize = 16;
const BUS_NUMBER_MASK: u32 = 0x00ff;
const DEVICE_NUMBER_OFFSET: usize = 11;
@@ -326,12 +434,10 @@ fn parse_config_address(config_address: u32) -> (usize, usize, usize, usize) {
const REGISTER_NUMBER_OFFSET: usize = 2;
const REGISTER_NUMBER_MASK: u32 = 0x3f;
let bus_number = ((config_address >> BUS_NUMBER_OFFSET) & BUS_NUMBER_MASK) as usize;
let device_number = ((config_address >> DEVICE_NUMBER_OFFSET) & DEVICE_NUMBER_MASK) as usize;
let function_number =
((config_address >> FUNCTION_NUMBER_OFFSET) & FUNCTION_NUMBER_MASK) as usize;
let register_number =
((config_address >> REGISTER_NUMBER_OFFSET) & REGISTER_NUMBER_MASK) as usize;
(bus_number, device_number, function_number, register_number)
(
shift_and_mask(config_address, BUS_NUMBER_OFFSET, BUS_NUMBER_MASK),
shift_and_mask(config_address, DEVICE_NUMBER_OFFSET, DEVICE_NUMBER_MASK),
shift_and_mask(config_address, FUNCTION_NUMBER_OFFSET, FUNCTION_NUMBER_MASK),
shift_and_mask(config_address, REGISTER_NUMBER_OFFSET, REGISTER_NUMBER_MASK),
)
}

View File

@@ -4,12 +4,13 @@
use std::sync::{Arc, Mutex};
use crate::device::BarReprogrammingParams;
use crate::{MsixConfig, PciInterruptPin};
use byteorder::{ByteOrder, LittleEndian};
use std::fmt::{self, Display};
// The number of 32bit registers in the config space, 256 bytes.
const NUM_CONFIGURATION_REGISTERS: usize = 64;
// The number of 32bit registers in the config space, 4096 bytes.
const NUM_CONFIGURATION_REGISTERS: usize = 1024;
const STATUS_REG: usize = 1;
const STATUS_REG_CAPABILITIES_USED_MASK: u32 = 0x0010_0000;
@@ -243,14 +244,49 @@ pub trait PciCapability {
fn id(&self) -> PciCapabilityID;
}
fn encode_32_bits_bar_size(bar_size: u32) -> Option<u32> {
if bar_size > 0 {
return Some(!(bar_size - 1));
}
None
}
fn decode_32_bits_bar_size(bar_size: u32) -> Option<u32> {
if bar_size > 0 {
return Some(!bar_size + 1);
}
None
}
fn encode_64_bits_bar_size(bar_size: u64) -> Option<(u32, u32)> {
if bar_size > 0 {
let result = !(bar_size - 1);
let result_hi = (result >> 32) as u32;
let result_lo = (result & 0xffff_ffff) as u32;
return Some((result_hi, result_lo));
}
None
}
fn decode_64_bits_bar_size(bar_size_hi: u32, bar_size_lo: u32) -> Option<u64> {
let bar_size: u64 = ((bar_size_hi as u64) << 32) | (bar_size_lo as u64);
if bar_size > 0 {
return Some(!bar_size + 1);
}
None
}
/// Contains the configuration space of a PCI node.
/// See the [specification](https://en.wikipedia.org/wiki/PCI_configuration_space).
/// The configuration space is accessed with DWORD reads and writes from the guest.
pub struct PciConfiguration {
registers: [u32; NUM_CONFIGURATION_REGISTERS],
writable_bits: [u32; NUM_CONFIGURATION_REGISTERS], // writable bits for each register.
bar_addr: [u32; NUM_BAR_REGS],
bar_size: [u32; NUM_BAR_REGS],
bar_used: [bool; NUM_BAR_REGS],
bar_type: [Option<PciBarRegionType>; NUM_BAR_REGS],
rom_bar_addr: u32,
rom_bar_size: u32,
rom_bar_used: bool,
// Contains the byte offset and size of the last capability.
@@ -260,7 +296,7 @@ pub struct PciConfiguration {
}
/// See pci_regs.h in kernel
#[derive(Copy, Clone)]
#[derive(Copy, Clone, PartialEq)]
pub enum PciBarRegionType {
Memory32BitRegion = 0,
IORegion = 0x01,
@@ -293,6 +329,10 @@ pub enum Error {
CapabilityEmpty,
CapabilityLengthInvalid(usize),
CapabilitySpaceFull(usize),
Decode32BarSize,
Decode64BarSize,
Encode32BarSize,
Encode64BarSize,
RomBarAddressInvalid(u64, u64),
RomBarInUse(usize),
RomBarInvalid(usize),
@@ -320,6 +360,10 @@ impl Display for Error {
CapabilityEmpty => write!(f, "empty capabilities are invalid"),
CapabilityLengthInvalid(l) => write!(f, "Invalid capability length {}", l),
CapabilitySpaceFull(s) => write!(f, "capability of size {} doesn't fit", s),
Decode32BarSize => write!(f, "failed to decode 32 bits BAR size"),
Decode64BarSize => write!(f, "failed to decode 64 bits BAR size"),
Encode32BarSize => write!(f, "failed to encode 32 bits BAR size"),
Encode64BarSize => write!(f, "failed to encode 64 bits BAR size"),
RomBarAddressInvalid(a, s) => write!(f, "address {} size {} too big", a, s),
RomBarInUse(b) => write!(f, "rom bar {} already used", b),
RomBarInvalid(b) => write!(f, "rom bar {} invalid, max {}", b, NUM_BAR_REGS - 1),
@@ -333,6 +377,7 @@ impl PciConfiguration {
pub fn new(
vendor_id: u16,
device_id: u16,
revision_id: u8,
class_code: PciClassCode,
subclass: &dyn PciSubclass,
programming_interface: Option<&dyn PciProgrammingInterface>,
@@ -343,6 +388,7 @@ impl PciConfiguration {
) -> Self {
let mut registers = [0u32; NUM_CONFIGURATION_REGISTERS];
let mut writable_bits = [0u32; NUM_CONFIGURATION_REGISTERS];
let bar_addr = [0u32; NUM_BAR_REGS];
let bar_size = [0u32; NUM_BAR_REGS];
registers[0] = u32::from(device_id) << 16 | u32::from(vendor_id);
// TODO(dverkamp): Status should be write-1-to-clear
@@ -354,7 +400,8 @@ impl PciConfiguration {
};
registers[2] = u32::from(class_code.get_register_value()) << 24
| u32::from(subclass.get_register_value()) << 16
| u32::from(pi) << 8;
| u32::from(pi) << 8
| u32::from(revision_id);
writable_bits[3] = 0x0000_00ff; // Cacheline size (r/w)
match header_type {
PciHeaderType::Device => {
@@ -372,8 +419,11 @@ impl PciConfiguration {
PciConfiguration {
registers,
writable_bits,
bar_addr,
bar_size,
bar_used: [false; NUM_BAR_REGS],
bar_type: [None; NUM_BAR_REGS],
rom_bar_addr: 0,
rom_bar_size: 0,
rom_bar_used: false,
last_capability: None,
@@ -390,15 +440,20 @@ impl PciConfiguration {
/// Writes a 32bit register to `reg_idx` in the register map.
pub fn write_reg(&mut self, reg_idx: usize, value: u32) {
let mut mask = self.writable_bits[reg_idx];
if reg_idx >= BAR0_REG
&& reg_idx < BAR0_REG + NUM_BAR_REGS
&& (value & BAR_MEM_ADDR_MASK) == BAR_MEM_ADDR_MASK
{
if reg_idx >= BAR0_REG && reg_idx < BAR0_REG + NUM_BAR_REGS {
// Handle very specific case where the BAR is being written with
// all 1's to retrieve the BAR size on next BAR reading.
mask = self.bar_size[reg_idx - 4];
} else if reg_idx == ROM_BAR_REG && (value & ROM_BAR_ADDR_MASK) == ROM_BAR_ADDR_MASK {
mask = self.rom_bar_size;
// all 1's to retrieve the BAR size during next BAR reading.
if value == 0xffff_ffff {
mask &= self.bar_size[reg_idx - 4];
}
} else if reg_idx == ROM_BAR_REG {
// Handle very specific case where the BAR is being written with
// all 1's on bits 31-11 to retrieve the BAR size during next BAR
// reading.
if value & ROM_BAR_ADDR_MASK == ROM_BAR_ADDR_MASK {
mask &= self.rom_bar_size;
}
}
if let Some(r) = self.registers.get_mut(reg_idx) {
@@ -481,6 +536,11 @@ impl PciConfiguration {
if end_addr > u64::from(u32::max_value()) {
return Err(Error::BarAddressInvalid(config.addr, config.size));
}
// Encode the BAR size as expected by the software running in
// the guest.
self.bar_size[config.reg_idx] =
encode_32_bits_bar_size(config.size as u32).ok_or(Error::Encode32BarSize)?;
}
PciBarRegionType::Memory64BitRegion => {
if config.reg_idx + 1 >= NUM_BAR_REGS {
@@ -495,9 +555,16 @@ impl PciConfiguration {
return Err(Error::BarInUse64(config.reg_idx));
}
// Encode the BAR size as expected by the software running in
// the guest.
let (bar_size_hi, bar_size_lo) =
encode_64_bits_bar_size(config.size).ok_or(Error::Encode64BarSize)?;
self.registers[bar_idx + 1] = (config.addr >> 32) as u32;
self.writable_bits[bar_idx + 1] = 0xffff_ffff;
self.bar_size[config.reg_idx + 1] = (config.size >> 32) as u32;
self.bar_addr[config.reg_idx + 1] = self.registers[bar_idx + 1];
self.bar_size[config.reg_idx] = bar_size_lo;
self.bar_size[config.reg_idx + 1] = bar_size_hi;
self.bar_used[config.reg_idx + 1] = true;
}
}
@@ -512,8 +579,9 @@ impl PciConfiguration {
self.registers[bar_idx] = ((config.addr as u32) & mask) | lower_bits;
self.writable_bits[bar_idx] = mask;
self.bar_size[config.reg_idx] = config.size as u32;
self.bar_addr[config.reg_idx] = self.registers[bar_idx];
self.bar_used[config.reg_idx] = true;
self.bar_type[config.reg_idx] = Some(config.region_type);
Ok(config.reg_idx)
}
@@ -542,24 +610,26 @@ impl PciConfiguration {
self.registers[config.reg_idx] = (config.addr as u32) | active;
self.writable_bits[config.reg_idx] = ROM_BAR_ADDR_MASK;
self.rom_bar_size = config.size as u32;
self.rom_bar_addr = self.registers[config.reg_idx];
self.rom_bar_size =
encode_32_bits_bar_size(config.size as u32).ok_or(Error::Encode32BarSize)?;
self.rom_bar_used = true;
Ok(config.reg_idx)
}
/// Returns the address of the given 32 bits BAR region.
pub fn get_bar32_addr(&self, bar_num: usize) -> u32 {
/// Returns the address of the given BAR region.
pub fn get_bar_addr(&self, bar_num: usize) -> u64 {
let bar_idx = BAR0_REG + bar_num;
self.registers[bar_idx] & BAR_MEM_ADDR_MASK
}
let mut addr = u64::from(self.bar_addr[bar_num] & self.writable_bits[bar_idx]);
/// Returns the address of the given 64 bits BAR region.
pub fn get_bar64_addr(&self, bar_num: usize) -> u64 {
let bar_idx = BAR0_REG + bar_num;
if let Some(bar_type) = self.bar_type[bar_num] {
if bar_type == PciBarRegionType::Memory64BitRegion {
addr |= u64::from(self.bar_addr[bar_num + 1]) << 32;
}
}
u64::from(self.registers[bar_idx] & BAR_MEM_ADDR_MASK)
| (u64::from(self.registers[bar_idx + 1]) << 32)
addr
}
/// Configures the IRQ line and pin used by this device.
@@ -645,6 +715,129 @@ impl PciConfiguration {
pub fn read_config_register(&self, reg_idx: usize) -> u32 {
self.read_reg(reg_idx)
}
pub fn detect_bar_reprogramming(
&mut self,
reg_idx: usize,
data: &[u8],
) -> Option<BarReprogrammingParams> {
if data.len() != 4 {
return None;
}
let value = LittleEndian::read_u32(data);
let mask = self.writable_bits[reg_idx];
if reg_idx >= BAR0_REG && reg_idx < BAR0_REG + NUM_BAR_REGS {
let bar_idx = reg_idx - 4;
if (value & mask) != (self.bar_addr[bar_idx] & mask) {
// Handle special case where the address being written is
// different from the address initially provided. This is a
// BAR reprogramming case which needs to be properly caught.
if let Some(bar_type) = self.bar_type[bar_idx] {
match bar_type {
PciBarRegionType::Memory64BitRegion => {}
_ => {
// Ignore the case where the BAR size is being
// asked for.
if value == 0xffff_ffff {
return None;
}
debug!(
"DETECT BAR REPROG: current 0x{:x}, new 0x{:x}",
self.registers[reg_idx], value
);
let old_base = u64::from(self.bar_addr[bar_idx] & mask);
let new_base = u64::from(value & mask);
let len = u64::from(
decode_32_bits_bar_size(self.bar_size[bar_idx])
.ok_or(Error::Decode32BarSize)
.unwrap(),
);
let region_type = bar_type;
self.bar_addr[bar_idx] = value;
return Some(BarReprogrammingParams {
old_base,
new_base,
len,
region_type,
});
}
}
} else if (reg_idx > BAR0_REG)
&& (self.registers[reg_idx - 1] & self.writable_bits[reg_idx - 1])
!= (self.bar_addr[bar_idx - 1] & self.writable_bits[reg_idx - 1])
{
// Ignore the case where the BAR size is being asked for.
// Because we are in the 64bits case here, we have to check
// if the lower 32bits of the current BAR have already been
// asked for the BAR size too.
if value == 0xffff_ffff
&& self.registers[reg_idx - 1] & self.writable_bits[reg_idx - 1]
== self.bar_size[bar_idx - 1] & self.writable_bits[reg_idx - 1]
{
return None;
}
debug!(
"DETECT BAR REPROG: current 0x{:x}, new 0x{:x}",
self.registers[reg_idx], value
);
let old_base = u64::from(self.bar_addr[bar_idx] & mask) << 32
| u64::from(self.bar_addr[bar_idx - 1] & self.writable_bits[reg_idx - 1]);
let new_base = u64::from(value & mask) << 32
| u64::from(self.registers[reg_idx - 1] & self.writable_bits[reg_idx - 1]);
let len =
decode_64_bits_bar_size(self.bar_size[bar_idx], self.bar_size[bar_idx - 1])
.ok_or(Error::Decode64BarSize)
.unwrap();
let region_type = PciBarRegionType::Memory64BitRegion;
self.bar_addr[bar_idx] = value;
self.bar_addr[bar_idx - 1] = self.registers[reg_idx - 1];
return Some(BarReprogrammingParams {
old_base,
new_base,
len,
region_type,
});
}
}
} else if reg_idx == ROM_BAR_REG && (value & mask) != (self.rom_bar_addr & mask) {
// Ignore the case where the BAR size is being asked for.
if value & ROM_BAR_ADDR_MASK == ROM_BAR_ADDR_MASK {
return None;
}
debug!(
"DETECT ROM BAR REPROG: current 0x{:x}, new 0x{:x}",
self.registers[reg_idx], value
);
let old_base = u64::from(self.rom_bar_addr & mask);
let new_base = u64::from(value & mask);
let len = u64::from(
decode_32_bits_bar_size(self.rom_bar_size)
.ok_or(Error::Decode32BarSize)
.unwrap(),
);
let region_type = PciBarRegionType::Memory32BitRegion;
self.rom_bar_addr = value;
return Some(BarReprogrammingParams {
old_base,
new_base,
len,
region_type,
});
}
None
}
}
impl Default for PciBarConfiguration {
@@ -732,6 +925,7 @@ mod tests {
let mut cfg = PciConfiguration::new(
0x1234,
0x5678,
0x1,
PciClassCode::MultimediaController,
&PciMultimediaSubclass::AudioController,
None,
@@ -787,6 +981,7 @@ mod tests {
let cfg = PciConfiguration::new(
0x1234,
0x5678,
0x1,
PciClassCode::MultimediaController,
&PciMultimediaSubclass::AudioController,
Some(&TestPI::Test),

View File

@@ -3,22 +3,12 @@
// found in the LICENSE-BSD-3-Clause file.
use crate::configuration::{self, PciBarRegionType};
use crate::msix::MsixTableEntry;
use crate::PciInterruptPin;
use devices::BusDevice;
use std;
use std::any::Any;
use std::fmt::{self, Display};
use std::sync::Arc;
use std::{self, io, result};
use vm_allocator::SystemAllocator;
use vm_memory::{GuestAddress, GuestUsize};
use vmm_sys_util::eventfd::EventFd;
pub struct InterruptParameters<'a> {
pub msix: Option<&'a MsixTableEntry>,
}
pub type InterruptDelivery =
Box<dyn Fn(InterruptParameters) -> std::result::Result<(), std::io::Error> + Send + Sync>;
#[derive(Debug)]
pub enum Error {
@@ -47,20 +37,15 @@ impl Display for Error {
}
}
#[derive(Clone, Copy)]
pub struct BarReprogrammingParams {
pub old_base: u64,
pub new_base: u64,
pub len: u64,
pub region_type: PciBarRegionType,
}
pub trait PciDevice: BusDevice {
/// Assign a legacy PCI IRQ to this device.
/// The device may write to `irq_evt` to trigger an interrupt.
fn assign_pin_irq(
&mut self,
_irq_cb: Arc<InterruptDelivery>,
_irq_num: u32,
_irq_pin: PciInterruptPin,
) {
}
/// Assign MSI-X to this device.
fn assign_msix(&mut self, _msi_cb: Arc<InterruptDelivery>) {}
/// Allocates the needed PCI BARs space using the `allocate` function which takes a size and
/// returns an address. Returns a Vec of (GuestAddress, GuestUsize) tuples.
fn allocate_bars(
@@ -70,18 +55,26 @@ pub trait PciDevice: BusDevice {
Ok(Vec::new())
}
/// Gets a list of ioeventfds that should be registered with the running VM. The list is
/// returned as a Vec of (eventfd, addr, datamatch) tuples.
fn ioeventfds(&self) -> Vec<(&EventFd, u64, u64)> {
Vec::new()
/// Frees the PCI BARs previously allocated with a call to allocate_bars().
fn free_bars(&mut self, _allocator: &mut SystemAllocator) -> Result<()> {
Ok(())
}
/// Sets a register in the configuration space.
/// * `reg_idx` - The index of the config register to modify.
/// * `offset` - Offset in to the register.
fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]);
/// Gets a register from the configuration space.
/// * `reg_idx` - The index of the config register to read.
fn read_config_register(&self, reg_idx: usize) -> u32;
fn read_config_register(&mut self, reg_idx: usize) -> u32;
/// Detects if a BAR is being reprogrammed.
fn detect_bar_reprogramming(
&mut self,
_reg_idx: usize,
_data: &[u8],
) -> Option<BarReprogrammingParams> {
None
}
/// Reads from a BAR region mapped in to the device.
/// * `addr` - The guest address inside the BAR.
/// * `data` - Filled with the data from `addr`.
@@ -90,4 +83,26 @@ pub trait PciDevice: BusDevice {
/// * `addr` - The guest address inside the BAR.
/// * `data` - The data to write.
fn write_bar(&mut self, _base: u64, _offset: u64, _data: &[u8]) {}
/// Relocates the BAR to a different address in guest address space.
fn move_bar(&mut self, _old_base: u64, _new_base: u64) -> result::Result<(), io::Error> {
Ok(())
}
/// Provides a mutable reference to the Any trait. This is useful to let
/// the caller have access to the underlying type behind the trait.
fn as_any(&mut self) -> &mut dyn Any;
}
/// This trait defines a set of functions which can be triggered whenever a
/// PCI device is modified in any way.
pub trait DeviceRelocation: Send + Sync {
/// The BAR needs to be moved to a different location in the guest address
/// space. This follows a decision from the software running in the guest.
fn move_bar(
&self,
old_base: u64,
new_base: u64,
len: u64,
pci_dev: &mut dyn PciDevice,
region_type: PciBarRegionType,
) -> result::Result<(), io::Error>;
}

View File

@@ -6,9 +6,7 @@
#[macro_use]
extern crate log;
extern crate devices;
extern crate kvm_ioctls;
extern crate vm_memory;
extern crate vmm_sys_util;
mod bus;
mod configuration;
@@ -23,9 +21,9 @@ pub use self::configuration::{
PciNetworkControllerSubclass, PciProgrammingInterface, PciSerialBusSubClass, PciSubclass,
};
pub use self::device::{
Error as PciDeviceError, InterruptDelivery, InterruptParameters, PciDevice,
BarReprogrammingParams, DeviceRelocation, Error as PciDeviceError, PciDevice,
};
pub use self::msi::MsiCap;
pub use self::msi::{msi_num_enabled_vectors, MsiCap, MsiConfig};
pub use self::msix::{MsixCap, MsixConfig, MsixTableEntry, MSIX_TABLE_ENTRY_SIZE};
/// PCI has four interrupt pins A->D.

View File

@@ -7,6 +7,10 @@ extern crate byteorder;
extern crate vm_memory;
use byteorder::{ByteOrder, LittleEndian};
use std::sync::Arc;
use vm_device::interrupt::{
InterruptIndex, InterruptSourceConfig, InterruptSourceGroup, MsiIrqSourceConfig,
};
// MSI control masks
const MSI_CTL_ENABLE: u16 = 0x1;
@@ -21,6 +25,16 @@ const MSI_MSG_ADDR_LO_OFFSET: u64 = 0x4;
// MSI message masks
const MSI_MSG_ADDR_LO_MASK: u32 = 0xffff_fffc;
pub fn msi_num_enabled_vectors(msg_ctl: u16) -> usize {
let field = (msg_ctl >> 4) & 0x7;
if field > 5 {
return 0;
}
1 << field
}
#[derive(Clone, Copy, Default)]
pub struct MsiCap {
// Message Control Register
@@ -58,21 +72,15 @@ impl MsiCap {
self.msg_ctl & MSI_CTL_PER_VECTOR == MSI_CTL_PER_VECTOR
}
pub fn enabled(&self) -> bool {
fn enabled(&self) -> bool {
self.msg_ctl & MSI_CTL_ENABLE == MSI_CTL_ENABLE
}
pub fn num_enabled_vectors(&self) -> usize {
let field = (self.msg_ctl >> 4) & 0x7;
if field > 5 {
return 0;
}
1 << field
fn num_enabled_vectors(&self) -> usize {
msi_num_enabled_vectors(self.msg_ctl)
}
pub fn vector_masked(&self, vector: usize) -> bool {
fn vector_masked(&self, vector: usize) -> bool {
if !self.per_vector_mask() {
return false;
}
@@ -80,7 +88,7 @@ impl MsiCap {
(self.mask_bits >> vector) & 0x1 == 0x1
}
pub fn size(&self) -> u64 {
fn size(&self) -> u64 {
let mut size: u64 = 0xa;
if self.addr_64_bits() {
@@ -93,7 +101,7 @@ impl MsiCap {
size
}
pub fn update(&mut self, offset: u64, data: &[u8]) {
fn update(&mut self, offset: u64, data: &[u8]) {
// Calculate message data offset depending on the address being 32 or
// 64 bits.
// Calculate upper address offset if the address is 64 bits.
@@ -132,7 +140,7 @@ impl MsiCap {
4 => {
let value = LittleEndian::read_u32(data);
match offset {
MSI_MSG_CTL_OFFSET => {
0x0 => {
self.msg_ctl = (self.msg_ctl & !(MSI_CTL_ENABLE | MSI_CTL_MULTI_MSG_ENABLE))
| ((value >> 16) as u16 & (MSI_CTL_ENABLE | MSI_CTL_MULTI_MSG_ENABLE))
}
@@ -151,3 +159,75 @@ impl MsiCap {
}
}
}
pub struct MsiConfig {
cap: MsiCap,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
}
impl MsiConfig {
pub fn new(msg_ctl: u16, interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>) -> Self {
let cap = MsiCap {
msg_ctl,
..Default::default()
};
MsiConfig {
cap,
interrupt_source_group,
}
}
pub fn enabled(&self) -> bool {
self.cap.enabled()
}
pub fn size(&self) -> u64 {
self.cap.size()
}
pub fn num_enabled_vectors(&self) -> usize {
self.cap.num_enabled_vectors()
}
pub fn update(&mut self, offset: u64, data: &[u8]) {
let old_enabled = self.cap.enabled();
self.cap.update(offset, data);
if self.cap.enabled() {
for idx in 0..self.num_enabled_vectors() {
let config = MsiIrqSourceConfig {
high_addr: self.cap.msg_addr_hi,
low_addr: self.cap.msg_addr_lo,
data: self.cap.msg_data as u32,
};
if let Err(e) = self
.interrupt_source_group
.update(idx as InterruptIndex, InterruptSourceConfig::MsiIrq(config))
{
error!("Failed updating vector: {:?}", e);
}
if self.cap.vector_masked(idx) {
if let Err(e) = self.interrupt_source_group.mask(idx as InterruptIndex) {
error!("Failed masking vector: {:?}", e);
}
} else if let Err(e) = self.interrupt_source_group.unmask(idx as InterruptIndex) {
error!("Failed unmasking vector: {:?}", e);
}
}
if !old_enabled {
if let Err(e) = self.interrupt_source_group.enable() {
error!("Failed enabling irq_fd: {:?}", e);
}
}
} else if old_enabled {
if let Err(e) = self.interrupt_source_group.disable() {
error!("Failed disabling irq_fd: {:?}", e);
}
}
}
}

View File

@@ -8,9 +8,11 @@ extern crate vm_memory;
use std::sync::Arc;
use crate::device::InterruptParameters;
use crate::{InterruptDelivery, PciCapability, PciCapabilityID};
use crate::{PciCapability, PciCapabilityID};
use byteorder::{ByteOrder, LittleEndian};
use vm_device::interrupt::{
InterruptIndex, InterruptSourceConfig, InterruptSourceGroup, MsiIrqSourceConfig,
};
use vm_memory::ByteValued;
const MAX_MSIX_VECTORS_PER_DEVICE: u16 = 2048;
@@ -51,13 +53,16 @@ impl Default for MsixTableEntry {
pub struct MsixConfig {
pub table_entries: Vec<MsixTableEntry>,
pub pba_entries: Vec<u64>,
interrupt_cb: Option<Arc<InterruptDelivery>>,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
masked: bool,
enabled: bool,
}
impl MsixConfig {
pub fn new(msix_vectors: u16) -> Self {
pub fn new(
msix_vectors: u16,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
) -> Self {
assert!(msix_vectors <= MAX_MSIX_VECTORS_PER_DEVICE);
let mut table_entries: Vec<MsixTableEntry> = Vec::new();
@@ -69,16 +74,12 @@ impl MsixConfig {
MsixConfig {
table_entries,
pba_entries,
interrupt_cb: None,
interrupt_source_group,
masked: false,
enabled: false,
}
}
pub fn register_interrupt_cb(&mut self, cb: Arc<InterruptDelivery>) {
self.interrupt_cb = Some(cb);
}
pub fn masked(&self) -> bool {
self.masked
}
@@ -89,10 +90,50 @@ impl MsixConfig {
pub fn set_msg_ctl(&mut self, reg: u16) {
let old_masked = self.masked;
let old_enabled = self.enabled;
self.masked = ((reg >> FUNCTION_MASK_BIT) & 1u16) == 1u16;
self.enabled = ((reg >> MSIX_ENABLE_BIT) & 1u16) == 1u16;
// Update KVM routes
if old_masked != self.masked || old_enabled != self.enabled {
if self.enabled && !self.masked {
for (idx, table_entry) in self.table_entries.iter().enumerate() {
let config = MsiIrqSourceConfig {
high_addr: table_entry.msg_addr_hi,
low_addr: table_entry.msg_addr_lo,
data: table_entry.msg_data,
};
if let Err(e) = self
.interrupt_source_group
.update(idx as InterruptIndex, InterruptSourceConfig::MsiIrq(config))
{
error!("Failed updating vector: {:?}", e);
}
if table_entry.masked() {
if let Err(e) = self.interrupt_source_group.mask(idx as InterruptIndex) {
error!("Failed masking vector: {:?}", e);
}
} else if let Err(e) = self.interrupt_source_group.unmask(idx as InterruptIndex)
{
error!("Failed unmasking vector: {:?}", e);
}
}
if !old_enabled || old_masked {
if let Err(e) = self.interrupt_source_group.enable() {
error!("Failed enabling irq_fd: {:?}", e);
}
}
} else if old_enabled || !old_masked {
if let Err(e) = self.interrupt_source_group.disable() {
error!("Failed disabling irq_fd: {:?}", e);
}
}
}
// If the Function Mask bit was set, and has just been cleared, it's
// important to go through the entire PBA to check if there was any
// pending MSI-X message to inject, given that the vector is not
@@ -198,6 +239,32 @@ impl MsixConfig {
_ => error!("invalid data length"),
};
// Update interrupt routes
if self.enabled && !self.masked {
let table_entry = &self.table_entries[index];
let config = MsiIrqSourceConfig {
high_addr: table_entry.msg_addr_hi,
low_addr: table_entry.msg_addr_lo,
data: table_entry.msg_data,
};
if let Err(e) = self.interrupt_source_group.update(
index as InterruptIndex,
InterruptSourceConfig::MsiIrq(config),
) {
error!("Failed updating vector: {:?}", e);
}
if table_entry.masked() {
if let Err(e) = self.interrupt_source_group.mask(index as InterruptIndex) {
error!("Failed masking vector: {:?}", e);
}
} else if let Err(e) = self.interrupt_source_group.unmask(index as InterruptIndex) {
error!("Failed unmasking vector: {:?}", e);
}
}
// After the MSI-X table entry has been updated, it is necessary to
// check if the vector control masking bit has changed. In case the
// bit has been flipped from 1 to 0, we need to inject a MSI message
@@ -285,13 +352,12 @@ impl MsixConfig {
fn inject_msix_and_clear_pba(&mut self, vector: usize) {
// Inject the MSI message
if let Some(cb) = &self.interrupt_cb {
match (cb)(InterruptParameters {
msix: Some(&self.table_entries[vector]),
}) {
Ok(_) => debug!("MSI-X injected on vector control flip"),
Err(e) => error!("failed to inject MSI-X: {}", e),
};
match self
.interrupt_source_group
.trigger(vector as InterruptIndex)
{
Ok(_) => debug!("MSI-X injected on vector control flip"),
Err(e) => error!("failed to inject MSI-X: {}", e),
}
// Clear the bit from PBA

9
qcow/Cargo.toml Executable file → Normal file
View File

@@ -9,11 +9,12 @@ license = "BSD-3-Clause"
path = "src/qcow.rs"
[dependencies]
byteorder = "1.3.2"
libc = "0.2.60"
byteorder = "1.3.4"
libc = "0.2.69"
log = "0.4.8"
remain = "0.1.3"
vmm-sys-util = "0.1.1"
remain = "0.2.1"
vmm-sys-util = ">=0.3.1"
vm-virtio = { path = "../vm-virtio" }
[dev-dependencies]
tempfile = "3.1.0"

View File

@@ -12,6 +12,7 @@ mod vec_cache;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use libc::{EINVAL, ENOSPC, ENOTSUP};
use remain::sorted;
use vm_virtio::RawFile;
use vmm_sys_util::{
file_traits::FileSetLen, file_traits::FileSync, seek_hole::SeekHole, write_zeroes::PunchHole,
write_zeroes::WriteZeroes,
@@ -19,10 +20,8 @@ use vmm_sys_util::{
use std::cmp::{max, min};
use std::fmt::{self, Display};
use std::fs::File;
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::mem::size_of;
use std::os::unix::io::{AsRawFd, RawFd};
use crate::qcow_raw_file::QcowRawFile;
use crate::refcount::RefCount;
@@ -190,7 +189,7 @@ pub struct QcowHeader {
impl QcowHeader {
/// Creates a QcowHeader from a reference to a file.
pub fn new(f: &mut File) -> Result<QcowHeader> {
pub fn new(f: &mut RawFile) -> Result<QcowHeader> {
f.seek(SeekFrom::Start(0)).map_err(Error::ReadingHeader)?;
let magic = f.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?;
if magic != QCOW_MAGIC {
@@ -198,12 +197,12 @@ impl QcowHeader {
}
// Reads the next u32 from the file.
fn read_u32_from_file(f: &mut File) -> Result<u32> {
fn read_u32_from_file(f: &mut RawFile) -> Result<u32> {
f.read_u32::<BigEndian>().map_err(Error::ReadingHeader)
}
// Reads the next u64 from the file.
fn read_u64_from_file(f: &mut File) -> Result<u64> {
fn read_u64_from_file(f: &mut RawFile) -> Result<u64> {
f.read_u64::<BigEndian>().map_err(Error::ReadingHeader)
}
@@ -368,9 +367,11 @@ fn max_refcount_clusters(refcount_order: u32, cluster_size: u32, num_clusters: u
///
/// ```
/// # use std::io::{Read, Seek, SeekFrom};
/// # use vm_virtio::RawFile;
/// # use qcow::{self, QcowFile};
/// # fn test(file: std::fs::File) -> std::io::Result<()> {
/// let mut q = QcowFile::from(file).expect("Can't open qcow file");
/// let mut raw_img = RawFile::new(file, false);
/// let mut q = QcowFile::from(raw_img).expect("Can't open qcow file");
/// let mut buf = [0u8; 12];
/// q.seek(SeekFrom::Start(10 as u64))?;
/// q.read(&mut buf[..])?;
@@ -395,7 +396,7 @@ pub struct QcowFile {
impl QcowFile {
/// Creates a QcowFile from `file`. File must be a valid qcow2 image.
pub fn from(mut file: File) -> Result<QcowFile> {
pub fn from(mut file: RawFile) -> Result<QcowFile> {
let header = QcowHeader::new(&mut file)?;
// Only v2 and v3 files are supported.
@@ -544,7 +545,7 @@ impl QcowFile {
}
/// Creates a new QcowFile at the given path.
pub fn new(mut file: File, version: u32, virtual_size: u64) -> Result<QcowFile> {
pub fn new(mut file: RawFile, version: u32, virtual_size: u64) -> Result<QcowFile> {
let header = QcowHeader::create_for_size(version, virtual_size);
file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?;
header.write_to(&mut file)?;
@@ -1220,7 +1221,12 @@ impl QcowFile {
let refcount = self
.refcounts
.get_cluster_refcount(&mut self.raw_file, cluster_addr)
.map_err(|_| std::io::Error::from_raw_os_error(EINVAL))?;
.map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("failed to get cluster refcount: {}", e),
)
})?;
if refcount == 0 {
return Err(std::io::Error::from_raw_os_error(EINVAL));
}
@@ -1394,12 +1400,6 @@ impl Drop for QcowFile {
}
}
impl AsRawFd for QcowFile {
fn as_raw_fd(&self) -> RawFd {
self.raw_file.file().as_raw_fd()
}
}
impl Read for QcowFile {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let address: u64 = self.current_offset as u64;
@@ -1634,7 +1634,7 @@ where
Ok(())
}
fn convert_reader<R>(reader: &mut R, dst_file: File, dst_type: ImageType) -> Result<()>
fn convert_reader<R>(reader: &mut R, dst_file: RawFile, dst_type: ImageType) -> Result<()>
where
R: Read + Seek + SeekHole,
{
@@ -1666,8 +1666,8 @@ where
/// Copy the contents of a disk image in `src_file` into `dst_file`.
/// The type of `src_file` is automatically detected, and the output file type is
/// determined by `dst_type`.
pub fn convert(src_file: File, dst_file: File, dst_type: ImageType) -> Result<()> {
let src_type = detect_image_type(&src_file)?;
pub fn convert(mut src_file: RawFile, dst_file: RawFile, dst_type: ImageType) -> Result<()> {
let src_type = detect_image_type(&mut src_file)?;
match src_type {
ImageType::Qcow2 => {
let mut src_reader = QcowFile::from(src_file)?;
@@ -1682,17 +1682,18 @@ pub fn convert(src_file: File, dst_file: File, dst_type: ImageType) -> Result<()
}
/// Detect the type of an image file by checking for a valid qcow2 header.
pub fn detect_image_type(file: &File) -> Result<ImageType> {
let mut f = file;
let orig_seek = f.seek(SeekFrom::Current(0)).map_err(Error::SeekingFile)?;
f.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?;
let magic = f.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?;
pub fn detect_image_type(file: &mut RawFile) -> Result<ImageType> {
let orig_seek = file
.seek(SeekFrom::Current(0))
.map_err(Error::SeekingFile)?;
file.seek(SeekFrom::Start(0)).map_err(Error::SeekingFile)?;
let magic = file.read_u32::<BigEndian>().map_err(Error::ReadingHeader)?;
let image_type = if magic == QCOW_MAGIC {
ImageType::Qcow2
} else {
ImageType::Raw
};
f.seek(SeekFrom::Start(orig_seek))
file.seek(SeekFrom::Start(orig_seek))
.map_err(Error::SeekingFile)?;
Ok(image_type)
}
@@ -1700,9 +1701,9 @@ pub fn detect_image_type(file: &File) -> Result<ImageType> {
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use tempfile::tempfile;
use vm_virtio::RawFile;
fn valid_header_v3() -> Vec<u8> {
vec![
@@ -1771,9 +1772,9 @@ mod tests {
fn with_basic_file<F>(header: &[u8], mut testfn: F)
where
F: FnMut(File),
F: FnMut(RawFile),
{
let mut disk_file: File = tempfile().unwrap();
let mut disk_file: RawFile = RawFile::new(tempfile().unwrap(), false);
disk_file.write_all(&header).unwrap();
disk_file.set_len(0x1_0000_0000).unwrap();
disk_file.seek(SeekFrom::Start(0)).unwrap();
@@ -1781,11 +1782,11 @@ mod tests {
testfn(disk_file); // File closed when the function exits.
}
fn with_default_file<F>(file_size: u64, mut testfn: F)
fn with_default_file<F>(file_size: u64, direct: bool, mut testfn: F)
where
F: FnMut(QcowFile),
{
let tmp = tempfile().unwrap();
let tmp: RawFile = RawFile::new(tempfile().unwrap(), direct);
let qcow_file = QcowFile::new(tmp, 3, file_size).unwrap();
testfn(qcow_file); // File closed when the function exits.
@@ -1794,7 +1795,7 @@ mod tests {
#[test]
fn default_header_v2() {
let header = QcowHeader::create_for_size(2, 0x10_0000);
let mut disk_file: File = tempfile().unwrap();
let mut disk_file: RawFile = RawFile::new(tempfile().unwrap(), false);
header
.write_to(&mut disk_file)
.expect("Failed to write header to temporary file.");
@@ -1805,7 +1806,7 @@ mod tests {
#[test]
fn default_header_v3() {
let header = QcowHeader::create_for_size(3, 0x10_0000);
let mut disk_file: File = tempfile().unwrap();
let mut disk_file: RawFile = RawFile::new(tempfile().unwrap(), false);
header
.write_to(&mut disk_file)
.expect("Failed to write header to temporary file.");
@@ -1815,13 +1816,13 @@ mod tests {
#[test]
fn header_read() {
with_basic_file(&valid_header_v2(), |mut disk_file: File| {
with_basic_file(&valid_header_v2(), |mut disk_file: RawFile| {
let header = QcowHeader::new(&mut disk_file).expect("Failed to create Header.");
assert_eq!(header.version, 2);
assert_eq!(header.refcount_order, DEFAULT_REFCOUNT_ORDER);
assert_eq!(header.header_size, V2_BARE_HEADER_SIZE);
});
with_basic_file(&valid_header_v3(), |mut disk_file: File| {
with_basic_file(&valid_header_v3(), |mut disk_file: RawFile| {
let header = QcowHeader::new(&mut disk_file).expect("Failed to create Header.");
assert_eq!(header.version, 3);
assert_eq!(header.refcount_order, DEFAULT_REFCOUNT_ORDER);
@@ -1832,7 +1833,7 @@ mod tests {
#[test]
fn invalid_magic() {
let invalid_header = vec![0x51u8, 0x46, 0x4a, 0xfb];
with_basic_file(&invalid_header, |mut disk_file: File| {
with_basic_file(&invalid_header, |mut disk_file: RawFile| {
QcowHeader::new(&mut disk_file).expect_err("Invalid header worked.");
});
}
@@ -1841,7 +1842,7 @@ mod tests {
fn invalid_refcount_order() {
let mut header = valid_header_v3();
header[99] = 2;
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Invalid refcount order worked.");
});
}
@@ -1850,7 +1851,7 @@ mod tests {
fn invalid_cluster_bits() {
let mut header = valid_header_v3();
header[23] = 3;
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Failed to create file.");
});
}
@@ -1858,7 +1859,7 @@ mod tests {
#[test]
fn test_header_huge_file() {
let header = test_huge_header();
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Failed to create file.");
});
}
@@ -1867,7 +1868,7 @@ mod tests {
fn test_header_crazy_file_size_rejected() {
let mut header = valid_header_v3();
&mut header[24..32].copy_from_slice(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1e]);
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Failed to create file.");
});
}
@@ -1876,7 +1877,7 @@ mod tests {
fn test_huge_l1_table() {
let mut header = valid_header_v3();
header[36] = 0x12;
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Failed to create file.");
});
}
@@ -1888,7 +1889,7 @@ mod tests {
header[26] = 1;
header[31] = 0;
// 1 TB with the min cluster size makes the arrays too big, it should fail.
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Failed to create file.");
});
}
@@ -1902,7 +1903,7 @@ mod tests {
header[31] = 0;
// set cluster_bits
header[23] = 16;
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
let mut qcow = QcowFile::from(disk_file).expect("Failed to create file.");
qcow.seek(SeekFrom::Start(0x100_0000_0000 - 8))
.expect("Failed to seek.");
@@ -1916,7 +1917,7 @@ mod tests {
fn test_header_huge_num_refcounts() {
let mut header = valid_header_v3();
&mut header[56..60].copy_from_slice(&[0x02, 0x00, 0xe8, 0xff]);
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Created disk with crazy refcount clusters");
});
}
@@ -1925,14 +1926,14 @@ mod tests {
fn test_header_huge_refcount_offset() {
let mut header = valid_header_v3();
&mut header[48..56].copy_from_slice(&[0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x02, 0x00]);
with_basic_file(&header, |disk_file: File| {
with_basic_file(&header, |disk_file: RawFile| {
QcowFile::from(disk_file).expect_err("Created disk with crazy refcount offset");
});
}
#[test]
fn write_read_start() {
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
q.write(b"test first bytes")
.expect("Failed to write test string.");
@@ -1945,7 +1946,7 @@ mod tests {
#[test]
fn offset_write_read() {
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
let b = [0x55u8; 0x1000];
q.seek(SeekFrom::Start(0xfff2000)).expect("Failed to seek.");
@@ -1959,7 +1960,7 @@ mod tests {
#[test]
fn write_zeroes_read() {
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
// Write some test data.
let b = [0x55u8; 0x1000];
@@ -1985,7 +1986,7 @@ mod tests {
// Choose a size that is larger than a cluster.
// valid_header uses cluster_bits = 12, which corresponds to a cluster size of 4096.
const CHUNK_SIZE: usize = 4096 * 2 + 512;
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
// Write some test data.
let b = [0x55u8; CHUNK_SIZE];
@@ -2006,11 +2007,11 @@ mod tests {
#[test]
fn test_header() {
with_basic_file(&valid_header_v2(), |disk_file: File| {
with_basic_file(&valid_header_v2(), |disk_file: RawFile| {
let q = QcowFile::from(disk_file).unwrap();
assert_eq!(q.virtual_size(), 0x20_0000_0000);
});
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let q = QcowFile::from(disk_file).unwrap();
assert_eq!(q.virtual_size(), 0x20_0000_0000);
});
@@ -2018,7 +2019,7 @@ mod tests {
#[test]
fn read_small_buffer() {
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
let mut b = [5u8; 16];
q.seek(SeekFrom::Start(1000)).expect("Failed to seek.");
@@ -2030,7 +2031,7 @@ mod tests {
#[test]
fn replay_ext4() {
with_basic_file(&valid_header_v3(), |disk_file: File| {
with_basic_file(&valid_header_v3(), |disk_file: RawFile| {
let mut q = QcowFile::from(disk_file).unwrap();
const BUF_SIZE: usize = 0x1000;
let mut b = [0u8; BUF_SIZE];
@@ -2406,7 +2407,16 @@ mod tests {
#[test]
fn combo_write_read() {
with_default_file(1024 * 1024 * 1024 * 256, |mut qcow_file| {
combo_write_read_common(false);
}
#[test]
fn combo_write_read_direct() {
combo_write_read_common(true);
}
fn combo_write_read_common(direct: bool) {
with_default_file(1024 * 1024 * 1024 * 256, direct, |mut qcow_file| {
const NUM_BLOCKS: usize = 555;
const BLOCK_SIZE: usize = 0x1_0000;
const OFFSET: usize = 0x1_0000_0020;
@@ -2459,7 +2469,16 @@ mod tests {
#[test]
fn seek_data() {
with_default_file(0x30000, |mut file| {
seek_data_common(false);
}
#[test]
fn seek_data_direct() {
seek_data_common(true);
}
fn seek_data_common(direct: bool) {
with_default_file(0x30000, direct, |mut file| {
// seek_data at or after the end of the file should return None
assert_eq!(file.seek_data(0x10000).unwrap(), None);
assert_eq!(seek_cur(&mut file), 0);
@@ -2492,7 +2511,16 @@ mod tests {
#[test]
fn seek_hole() {
with_default_file(0x30000, |mut file| {
seek_hole_common(false);
}
#[test]
fn seek_hole_direct() {
seek_hole_common(true);
}
fn seek_hole_common(direct: bool) {
with_default_file(0x30000, direct, |mut file| {
// File consisting entirely of a hole
assert_eq!(file.seek_hole(0).unwrap(), Some(0));
assert_eq!(seek_cur(&mut file), 0);
@@ -2566,7 +2594,7 @@ mod tests {
#[test]
fn rebuild_refcounts() {
with_basic_file(&valid_header_v3(), |mut disk_file: File| {
with_basic_file(&valid_header_v3(), |mut disk_file: RawFile| {
let header = QcowHeader::new(&mut disk_file).expect("Failed to create Header.");
let cluster_size = 65536;
let mut raw_file =

View File

@@ -2,17 +2,17 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD-3-Clause file.
use std::fs::File;
use std::io::{self, BufWriter, Seek, SeekFrom};
use std::mem::size_of;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use vm_virtio::RawFile;
use vmm_sys_util::write_zeroes::WriteZeroes;
/// A qcow file. Allows reading/writing clusters and appending clusters.
#[derive(Debug)]
pub struct QcowRawFile {
file: File,
file: RawFile,
cluster_size: u64,
cluster_mask: u64,
}
@@ -20,7 +20,7 @@ pub struct QcowRawFile {
impl QcowRawFile {
/// Creates a `QcowRawFile` from the given `File`, `None` is returned if `cluster_size` is not
/// a power of two.
pub fn from(file: File, cluster_size: u64) -> Option<Self> {
pub fn from(file: RawFile, cluster_size: u64) -> Option<Self> {
if cluster_size.count_ones() != 1 {
return None;
}
@@ -67,7 +67,7 @@ impl QcowRawFile {
non_zero_flags: u64,
) -> io::Result<()> {
self.file.seek(SeekFrom::Start(offset))?;
let mut buffer = BufWriter::with_capacity(table.len() * size_of::<u64>(), &self.file);
let mut buffer = BufWriter::with_capacity(table.len() * size_of::<u64>(), &mut self.file);
for addr in table {
let val = if *addr == 0 {
0
@@ -92,7 +92,7 @@ impl QcowRawFile {
/// Writes a refcount block to the file.
pub fn write_refcount_block(&mut self, offset: u64, table: &[u16]) -> io::Result<()> {
self.file.seek(SeekFrom::Start(offset))?;
let mut buffer = BufWriter::with_capacity(table.len() * size_of::<u16>(), &self.file);
let mut buffer = BufWriter::with_capacity(table.len() * size_of::<u16>(), &mut self.file);
for count in table {
buffer.write_u16::<BigEndian>(*count)?;
}
@@ -115,13 +115,8 @@ impl QcowRawFile {
Ok(Some(new_cluster_address))
}
/// Returns a reference to the underlying file.
pub fn file(&self) -> &File {
&self.file
}
/// Returns a mutable reference to the underlying file.
pub fn file_mut(&mut self) -> &mut File {
pub fn file_mut(&mut self) -> &mut RawFile {
&mut self.file
}

View File

@@ -120,7 +120,7 @@ impl<T: Cacheable> CacheMap<T> {
{
if self.map.len() == self.capacity {
// TODO(dgreid) - smarter eviction strategy.
let to_evict = *self.map.iter().nth(0).unwrap().0;
let to_evict = *self.map.iter().next().unwrap().0;
if let Some(evicted) = self.map.remove(&to_evict) {
if evicted.dirty() {
write_callback(to_evict, evicted)?;

View File

@@ -1,32 +1,383 @@
- [v0.7.0](#v070)
- [Block, Network, Persistent Memory (PMEM), VirtioFS and Vsock hotplug](#block-network-persistent-memory-pmem-virtiofs-and-vsock-hotplug)
- [Alternative `libc` Support](#alternative-libc-support)
- [Multithreaded Multi Queued `vhost-user` Backends](#multithreaded-multi-queued-vhost-user-backends)
- [Initial RamFS Support](#initial-ramfs-support)
- [Alternative Memory Hotplug: `virtio-mem`](#alternative-memory-hotplug-virtio-mem)
- [`Seccomp` Sandboxing](#seccomp-sandboxing)
- [Updated Distribution Support](#updated-distribution-support)
- [Command Line and API Changes](#command-line-and-api-changes)
- [Contributors](#contributors)
- [v0.6.0](#v060)
- [Directly Assigned Devices Hotplug](#directly-assigned-devices-hotplug)
- [Shared Filesystem Improvements](#shared-filesystem-improvements)
- [Block and Networking IO Self Offloading](#block-and-networking-io-self-offloading)
- [Command Line Interface](#command-line-interface)
- [PVH Boot](#pvh-boot)
- [Contributors](#contributors-1)
- [v0.5.1](#v051)
- [v0.5.0](#v050)
- [Virtual Machine Dynamic Resizing](#virtual-machine-dynamic-resizing)
- [Multi-Queue, Multi-Threaded Paravirtualization](#multi-queue-multi-threaded-paravirtualization)
- [New Interrupt Management Framework](#new-interrupt-management-framework)
- [Development Tools](#development-tools)
- [Kata Containers Integration](#kata-containers-integration)
- [Contributors](#contributors-2)
- [v0.4.0](#v040)
- [Dynamic virtual CPUs addition](#dynamic-virtual-cpus-addition)
- [Programmatic firmware tables generation](#programmatic-firmware-tables-generation)
- [Filesystem and block devices vhost-user backends](#filesystem-and-block-devices-vhost-user-backends)
- [Guest pause and resume](#guest-pause-and-resume)
- [Userspace IOAPIC by default](#userspace-ioapic-by-default)
- [PCI BAR reprogramming](#pci-bar-reprogramming)
- [New `cloud-hypervisor` organization](#new-cloud-hypervisor-organization)
- [Contributors](#contributors-3)
- [v0.3.0](#v030)
+ [Block device offloading](#block-device-offloading)
+ [Network device backend](#network-device-backend)
+ [Virtual sockets](#virtual-sockets)
+ [HTTP based API](#http-based-api)
+ [Memory mapped virtio transport](#memory-mapped-virtio-transport)
+ [Paravirtualized IOMMU](#paravirtualized-iommu)
+ [Ubuntu 19.10](#ubuntu-1910)
+ [Guest large memory](#guest-large-memory)
- [Block device offloading](#block-device-offloading)
- [Network device backend](#network-device-backend)
- [Virtual sockets](#virtual-sockets)
- [HTTP based API](#http-based-api)
- [Memory mapped virtio transport](#memory-mapped-virtio-transport)
- [Paravirtualized IOMMU](#paravirtualized-iommu)
- [Ubuntu 19.10](#ubuntu-1910)
- [Large memory guests](#large-memory-guests)
- [v0.2.0](#v020)
+ [Network device offloading](#network-device-offloading)
+ [Minimal hardware-reduced ACPI](#minimal-hardware-reduced-acpi)
+ [Debug I/O port](#debug-i-o-port)
+ [Improved direct device assignment](#improved-direct-device-assignment)
+ [Improved shared filesystem](#improved-shared-filesystem)
+ [Ubuntu bionic based CI](#ubuntu-bionic-based-ci)
- [Network device offloading](#network-device-offloading)
- [Minimal hardware-reduced ACPI](#minimal-hardware-reduced-acpi)
- [Debug I/O port](#debug-io-port)
- [Improved direct device assignment](#improved-direct-device-assignment)
- [Improved shared filesystem](#improved-shared-filesystem)
- [Ubuntu bionic based CI](#ubuntu-bionic-based-ci)
- [v0.1.0](#v010)
+ [Shared filesystem](#shared-filesystem)
+ [Initial direct device assignment support](#initial-direct-device-assignment-support)
+ [Userspace IOAPIC](#userspace-ioapic)
+ [Virtual persistent memory](#virtual-persistent-memory)
+ [Linux kernel bzImage](#linux-kernel-bzimage)
+ [Console over virtio](#console-over-virtio)
+ [Unit testing](#unit-testing)
+ [Integration tests parallelization](#integration-tests-parallelization)
- [Shared filesystem](#shared-filesystem)
- [Initial direct device assignment support](#initial-direct-device-assignment-support)
- [Userspace IOAPIC](#userspace-ioapic)
- [Virtual persistent memory](#virtual-persistent-memory)
- [Linux kernel bzImage](#linux-kernel-bzimage)
- [Console over virtio](#console-over-virtio)
- [Unit testing](#unit-testing)
- [Integration tests parallelization](#integration-tests-parallelization)
# v0.7.0
This release has been tracked through the [0.7.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/7).
Highlights for `cloud-hypervisor` version 0.7.0 include:
### Block, Network, Persistent Memory (PMEM), VirtioFS and Vsock hotplug
Further to our effort to support modifying a running guest we now support
hotplug and unplug of the following virtio backed devices: block, network,
pmem, virtio-fs and vsock. This functionality is available on the (default) PCI
based tranport and is exposed through the HTTP API. The `ch-remote` utility
provides a CLI for adding or removing these device types after the VM has
booted. User can use the `id` parameter on the devices to choose names for
devices to ease their removal.
### Alternative `libc` Support
Cloud Hypervisor can now be compiled with the `musl` C library and this release
contains a static binary compiled using that toolchain.
### Multithreaded Multi Queued `vhost-user` Backends
The `vhost-user` backends for network and block support that are shipped by
Cloud Hypervisor have been enhanced to support multiple threads and queues to
improve throughput. These backends are used automatically if `vhost_user=true`
is passed when the devices are created.
### Initial RamFS Support
By passing the `--initramfs` command line option the user can specify a file to
be loaded into the guest memory to be used as the kernel initial filesystem.
This is usually used to allow the loading of drivers needed to be able to
access the real root filesystem but it can also be used standalone for a very
minimal image.
### Alternative Memory Hotplug: `virtio-mem`
As well as supporting ACPI based hotplug Cloud Hypervisor now supports using
the `virtio-mem` hotplug alternative. This can be controlled by the
`hotplug_method` parameter on the `--memory` command line option. It currently
requires kernel patches to be able to support it.
### `Seccomp` Sandboxing
Cloud Hypervisor now has support for restricting the system calls that the
process can use via the `seccomp` security API. This on by default and is
controlled by the `--seccomp` command line option.
### Updated Distribution Support
With the release of Ubuntu 20.04 we have added that to the list of supported
distributions and is part of our regular testing programme.
### Command Line and API Changes
This is non exhaustive list of HTTP API and command line changes
* New `id` fields added for devices to allow them to be named to ease removal.
If no name is specified the VMM chooses one.
* Use `--memory`'s `shared` and `hugepages` controls for determining backing
memory instead of providing a path.
* The `--vsock` parameter only takes one device as the Linux kernel only
supports a single Vsock device. The REST API has removed the vector for this
option and replaced it with a single optional field.
* There is enhanced validation of the command line and API provided
configurations to ensure that the provided options are compatible e.g. that
shared memory is in use if any attempt is made to used a `vhost-user` backed
device.
* `ch-remote` has added `add-disk`, `add-fs`, `add-net`, `add-pmem` and
`add-vsock` subcommands. For removal `remove-device` is used. The REST API
has appropriate new HTTP endpoints too.
* Specifying a `size` with `--pmem` is no longer required and instead the size
will be obtained from the file. A `discard_writes` option has also been added
to provide the equivalent of a read-only file.
* The parameters to `--block-backend` have been changed to more closely align
with those used by `--disk`.
### Contributors
Many thanks to everyone who has contributed to our 0.7.0 release including some new faces.
* Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
* Bo Chen <chen.bo@intel.com>
* Cathy Zhang <cathy.zhang@intel.com>
* Damjan Georgievski <gdamjan@gmail.com>
* Dean Sheather <dean@coder.com>
* Eryu Guan <eguan@linux.alibaba.com>
* Hui Zhu <teawater@antfin.com>
* Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
* Martin Xu <martin.xu@intel.com>
* Muminul Islam <muislam@microsoft.com>
* Rob Bradford <robert.bradford@intel.com>
* Samuel Ortiz <sameo@linux.intel.com>
* Sebastien Boeuf <sebastien.boeuf@intel.com>
* Sergio Lopez <slp@redhat.com>
* Yang Zhong <yang.zhong@intel.com>
* Yi Sun <yi.y.sun@linux.intel.com>
# v0.6.0
This release has been tracked through the [0.6.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/7).
Highlights for `cloud-hypervisor` version 0.6.0 include:
### Directly Assigned Devices Hotplug
We continued our efforts around supporting dynamically changing the guest
resources. After adding support for CPU and memory hotplug, Cloud Hypervisor
now supports hot plugging and hot unplugging directly assigned (a.k.a. `VFIO`)
devices into an already running guest. This closes the features gap for
providing a complete Kata Containers workloads support with Cloud Hypervisor.
### Shared Filesystem Improvements
We enhanced our shared filesystem support through many `virtio-fs` improvements.
By adding support for DAX, parallel processing of multiple requests, `FS_IO`,
`LSEEK` and the `MMIO` virtio transport layer to our `vhost_user_fs` daemon, we
improved our filesystem sharing performance, but also made it more stable and
compatible with other `virtio-fs` implementations.
### Block and Networking IO Self Offloading
When choosing to offload the paravirtualized block and networking I/O to an
external process (through the `vhost-user` protocol), Cloud Hypervisor now
automatically spawns its default `vhost-user-blk` and `vhost-user-net` backends
into their own, separate processes.
This provides a seamless parvirtualized I/O user experience for those who want
to run their guest I/O into separate executions contexts.
### Command Line Interface
More and more Cloud Hypervisor services are exposed through the
[Rest API](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/vmm/src/api/openapi/cloud-hypervisor.yaml)
and thus only accessible via relatively cumbersome HTTP calls. In order
to abstract those calls into a more user friendly tool, we created a Cloud
Hypervisor Command Line Interface (CLI) called `ch-remote`.
The `ch-remote` binary is created with each build and available e.g. at
`cloud-hypervisor/target/debug/ch-remote` when doing a debug build.
Please check `ch-remote --help` for a complete description of all available
commands.
### PVH Boot
In addition to the traditional Linux boot protocol, Cloud Hypervisor now
supports direct kernel booting through the [PVH ABI](https://xenbits.xen.org/docs/unstable/misc/pvh.html).
### Contributors
With the 0.6.0 release, we are welcoming a few new contributors. Many thanks
to them and to everyone that contributed to this release:
* Alejandro Jimenez <alejandro.j.jimenez@oracle.com>
* Arron Wang <arron.wang@intel.com>
* Bin Liu <liubin0329@gmail.com>
* Bo Chen <chen.bo@intel.com>
* Cathy Zhang <cathy.zhang@intel.com>
* Eryu Guan <eguan@linux.alibaba.com>
* Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
* Liu Bo <bo.liu@linux.alibaba.com>
* Qiu Wenbo <qiuwenbo@phytium.com.cn>
* Rob Bradford <robert.bradford@intel.com>
* Samuel Ortiz <sameo@linux.intel.com>
* Sebastien Boeuf <sebastien.boeuf@intel.com>
* Sergio Lopez <slp@redhat.com>
# v0.5.1
This is a bugfix release branched off v0.5.0. It contains the following fixes:
* Update DiskConfig to contain missing disk control features (#790) - Samuel Ortiz and Sergio Lopez
* Prevent memory overcommit via virtio-fs (#763) - Sebastien Boeuf
* Fixed error reporting for resize command - Samuel Ortiz
* Double reboot workaround (#783) - Rob Bradford
* Various CI and development tooling fixes - Sebastien Boeuf, Samuel Ortiz, Rob Bradford
# v0.5.0
This release has been tracked through the [0.5.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/6).
Highlights for `cloud-hypervisor` version 0.5.0 include:
### Virtual Machine Dynamic Resizing
With 0.4.0 we added support for CPU hot plug, and 0.5.0 adds CPU hot unplug and
memory hot plug as well. This allows to dynamically resize Cloud Hypervisor
guests which is needed for e.g. Kubernetes related use cases.
The memory hot plug implementation is based on the same framework as the CPU hot
plug/unplug one, i.e. hardware-reduced ACPI notifications to the guest.
Next on our VM resizing roadmap is the PCI devices hotplug feature.
### Multi-Queue, Multi-Threaded Paravirtualization
We enhanced our virtio networking and block support by having both devices use
multiple I/O queues handled by multiple threads. This improves our default
paravirtualized networking and block devices throughput.
### New Interrupt Management Framework
We improved our interrupt management implementation by introducing an Interrupt
Manager framework, based on the currently on-going [rust-vmm vm-device](https://github.com/rust-vmm/vm-device)
crates discussions. This move made the code significantly cleaner, and allowed
us to remove several KVM related dependencies from crates like the PCI and
virtio ones.
### Development Tools
In order to provide a better developer experience, we worked on improving our
build, development and testing tools.
Somehow similar to the excellent
[Firecracker's devtool](https://github.com/firecracker-microvm/firecracker/blob/master/tools/devtool),
we now provide a [dev_cli script](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/scripts/dev_cli.sh).
With this new tool, our users and contributors will be able to build and test
Cloud Hypervisor through a containerized environment.
### Kata Containers Integration
We spent some significant time and efforts debugging and fixing our integration
with the [Kata Containers](https://github.com/kata-containers) project. Cloud
Hypervisor is now a fully supported Kata Containers hypervisor, and is
integrated into the project's CI.
### Contributors
Many thanks to everyone that contributed to the 0.5.0 release:
* Bo Chen <chen.bo@intel.com>
* Cathy Zhang <cathy.zhang@intel.com>
* Qiu Wenbo <qiuwenbo@phytium.com.cn>
* Rob Bradford <robert.bradford@intel.com>
* Samuel Ortiz <sameo@linux.intel.com>
* Sebastien Boeuf <sebastien.boeuf@intel.com>
* Sergio Lopez <slp@redhat.com>
* Yang Zhong <yang.zhong@intel.com>
# v0.4.0
This release has been tracked through the [0.4.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/4).
Highlights for `cloud-hypervisor` version 0.4.0 include:
### Dynamic virtual CPUs addition
As a way to vertically scale Cloud-Hypervisor guests, we now support dynamically
adding virtual CPUs to the guests, a mechanism also known as CPU hot plug.
Through hardware-reduced ACPI notifications, Cloud Hypervisor can now add CPUs
to an already running guest and the high level operations for that process are
documented [here](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/hotplug.md)
During the next release cycles we are planning to extend Cloud Hypervisor
hot plug framework to other resources, namely PCI devices and memory.
### Programmatic firmware tables generation
As part of the CPU hot plug feature enablement, and as a requirement for hot
plugging other resources like devices or RAM, we added support for
programmatically generating the needed ACPI tables. Through a dedicated
`acpi-tables` crate, we now have a flexible and clean way of generating those
tables based on the VMM device model and topology.
### Filesystem and block devices vhost-user backends
Our objective of running all Cloud Hypervisor paravirtualized I/O to a
vhost-user based framework is getting closer as we've added Rust based
implementations for vhost-user-blk and virtiofs backends. Together with the
vhost-user-net backend that came with the 0.3.0 release, this will form the
default Cloud Hypervisor I/O architecture.
### Guest pause and resume
As an initial requiremnt for enabling live migration, we added support for
pausing and resuming any VMM components. As an intermediate step towards live
migration, the upcoming guest snapshotting feature will be based on the pause
and resume capabilities.
### Userspace IOAPIC by default
As a way to simplify our device manager implementation, but also in order to
stay away from privileged rings as often as possible, any device that relies on
pin based interrupts will be using the userspace IOAPIC implementation by
default.
### PCI BAR reprogramming
In order to allow for a more flexible device model, and also support guests
that would want to move PCI devices, we added support for PCI devices BAR
reprogramming.
### New `cloud-hypervisor` organization
As we wanted to be more flexible on how we manage the Cloud Hypervisor project,
we decided to move it under a [dedicated GitHub organization](https://github.com/cloud-hypervisor).
Together with the [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor)
project, this new organization also now hosts our [kernel](https://github.com/cloud-hypervisor/linux)
and [firmware](https://github.com/cloud-hypervisor/rust-hypervisor-firmware)
repositories. We may also use it to host any rust-vmm that we'd need to
temporarily fork.
Thanks to GitHub's seamless repository redirections, the move is completely
transparent to all Cloud Hypervisor contributors, users and followers.
### Contributors
Many thanks to everyone that contributed to the 0.4.0 release:
* Cathy Zhang <cathy.zhang@intel.com>
* Emin Ghuliev <drmint80@gmail.com>
* Jose Carlos Venegas Munoz <jose.carlos.venegas.munoz@intel.com>
* Qiu Wenbo <qiuwenbo@phytium.com.cn>
* Rob Bradford <robert.bradford@intel.com>
* Samuel Ortiz <sameo@linux.intel.com>
* Sebastien Boeuf <sebastien.boeuf@intel.com>
* Sergio Lopez <slp@redhat.com>
* Wu Zongyong <wuzongyong@linux.alibaba.com>
# v0.3.0
This release has been tracked through the [0.3.0 project](https://github.com/intel/cloud-hypervisor/projects/3).
This release has been tracked through the [0.3.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/3).
Highlights for `cloud-hypervisor` version 0.3.0 include:
@@ -73,7 +424,7 @@ configurations that do not require a PCI bus emulation.
### Paravirtualized IOMMU
As we want to improve our nested guests support, we added support for exposing
a [paravirtualized IOMMU](https://github.com/intel/cloud-hypervisor/blob/master/docs/iommu.md)
a [paravirtualized IOMMU](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/iommu.md)
device through virtio. This allows for a safer nested virtio and directly
assigned devices support.
@@ -85,7 +436,7 @@ setting.
### Ubuntu 19.10
With the latest [hypervisor firmware](https://github.com/intel/rust-hypervisor-firmware),
With the latest [hypervisor firmware](https://github.com/cloud-hypervisor/rust-hypervisor-firmware),
we can now support the latest
[Ubuntu 19.10 (Eoan Ermine)](http://releases.ubuntu.com/19.10/) cloud images.
@@ -96,7 +447,7 @@ support guests with large amount of memory (more than 64GB).
# v0.2.0
This release has been tracked through the [0.2.0 project](https://github.com/intel/cloud-hypervisor/projects/2).
This release has been tracked through the [0.2.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/2).
Highlights for `cloud-hypervisor` version 0.2.0 include:
@@ -124,7 +475,7 @@ Based on the Firecracker idea of using a dedicated I/O port to measure guest
boot times, we added support for logging guest events through the
[0x80](https://www.intel.com/content/www/us/en/support/articles/000005500/boards-and-kits.html)
PC debug port. This allows, among other things, for granular guest boot time
measurements. See our [debug port documentation](https://github.com/intel/cloud-hypervisor/blob/master/docs/debug-port.md)
measurements. See our [debug port documentation](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/debug-port.md)
for more details.
### Improved direct device assignment
@@ -144,13 +495,13 @@ memory footprint.
### Ubuntu bionic based CI
Thanks to our [simple KVM firmware](https://github.com/intel/rust-hypervisor-firmware)
Thanks to our [simple KVM firmware](https://github.com/cloud-hypervisor/rust-hypervisor-firmware)
improvements, we are now able to boot Ubuntu bionic images. We added those to
our CI pipeline.
# v0.1.0
This release has been tracked through the [0.1.0 project](https://github.com/intel/cloud-hypervisor/projects/1).
This release has been tracked through the [0.1.0 project](https://github.com/cloud-hypervisor/cloud-hypervisor/projects/1).
Highlights for `cloud-hypervisor` version 0.1.0 include:
@@ -160,7 +511,7 @@ We added support for the [virtio-fs](https://virtio-fs.gitlab.io/) shared file
system, allowing for an efficient and reliable way of sharing a filesystem
between the host and the `cloud-hypervisor` guest.
See our [filesystem sharing](https://github.com/intel/cloud-hypervisor/blob/master/docs/fs.md)
See our [filesystem sharing](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/fs.md)
documentation for more details on how to use virtio-fs with `cloud-hypervisor`.
### Initial direct device assignment support
@@ -169,7 +520,7 @@ VFIO (Virtual Function I/O) is a kernel framework that exposes direct device
access to userspace. `cloud-hypervisor` uses VFIO to directly assign host
physical devices into its guest.
See our [VFIO](https://github.com/intel/cloud-hypervisor/blob/master/docs/vfio.md)
See our [VFIO](https://github.com/cloud-hypervisor/cloud-hypervisor/blob/master/docs/vfio.md)
documentation for more detail on how to directly assign host devices to
`cloud-hypervisor` guests.

65
resources/Dockerfile Normal file
View File

@@ -0,0 +1,65 @@
FROM ubuntu:18.04 as dev
ARG RUST_TOOLCHAIN="1.42.0"
ARG CLH_SRC_DIR="/cloud-hypervisor"
ARG CLH_BUILD_DIR="$CLH_SRC_DIR/build"
ARG CARGO_REGISTRY_DIR="$CLH_BUILD_DIR/cargo_registry"
ARG CARGO_GIT_REGISTRY_DIR="$CLH_BUILD_DIR/cargo_git_registry"
ENV CARGO_HOME=/usr/local/rust
ENV RUSTUP_HOME=$CARGO_HOME
ENV PATH="$PATH:$CARGO_HOME/bin"
# Install all CI dependencies
RUN apt-get update
RUN apt-get -yq upgrade
RUN DEBIAN_FRONTEND=noninteractive apt-get install -yq \
build-essential \
bc \
docker.io \
curl \
wget \
sudo \
mtools \
musl-tools \
libssl-dev \
pkg-config \
flex \
bison \
libelf-dev \
qemu-utils \
qemu-system \
libglib2.0-dev \
libpixman-1-dev \
libseccomp-dev \
libcap-ng-dev \
socat \
dosfstools \
cpio \
bsdtar \
gcc-multilib \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
# Fix the libssl-dev install
RUN cp /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl/
ENV OPENSSL_DIR=/usr/lib/x86_64-linux-gnu/
ENV OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu/
ENV OPENSSL_INCLUDE_DIR=/usr/include/
# Install the rust toolchain
RUN nohup curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain "$RUST_TOOLCHAIN" \
&& rustup target add x86_64-unknown-linux-musl --toolchain "$RUST_TOOLCHAIN" \
&& rustup toolchain add $RUST_TOOLCHAIN-x86_64-unknown-linux-musl \
&& rustup component add rustfmt \
&& rustup component add clippy \
&& cargo install cargo-audit \
&& rm -rf "$CARGO_HOME/registry" \
&& ln -s "$CARGO_REGISTRY_DIR" "$CARGO_HOME/registry" \
&& rm -rf "$CARGO_HOME/git" \
&& ln -s "$CARGO_GIT_REGISTRY_DIR" "$CARGO_HOME/git"
# Set the rust environment
RUN echo 'source $CARGO_HOME/env' >> $HOME/.bashrc \
&& mkdir $HOME/.cargo \
&& ln -s $CARGO_HOME/env $HOME/.cargo/env

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
#
# Automatically generated file; DO NOT EDIT.
# Linux/x86 5.3.0-rc3 Kernel Configuration
# Linux/x86 5.6.0-rc4 Kernel Configuration
#
#
@@ -11,9 +11,10 @@ CONFIG_GCC_VERSION=80300
CONFIG_CLANG_VERSION=0
CONFIG_CC_CAN_LINK=y
CONFIG_CC_HAS_ASM_GOTO=y
CONFIG_CC_HAS_ASM_INLINE=y
CONFIG_CC_HAS_WARN_MAYBE_UNINITIALIZED=y
CONFIG_IRQ_WORK=y
CONFIG_BUILDTIME_EXTABLE_SORT=y
CONFIG_BUILDTIME_TABLE_SORT=y
CONFIG_THREAD_INFO_IN_TASK=y
#
@@ -21,7 +22,6 @@ CONFIG_THREAD_INFO_IN_TASK=y
#
CONFIG_INIT_ENV_ARG_LIMIT=32
# CONFIG_COMPILE_TEST is not set
# CONFIG_HEADER_TEST is not set
CONFIG_LOCALVERSION=""
# CONFIG_LOCALVERSION_AUTO is not set
CONFIG_BUILD_SALT=""
@@ -139,6 +139,7 @@ CONFIG_HAVE_UNSTABLE_SCHED_CLOCK=y
CONFIG_ARCH_SUPPORTS_NUMA_BALANCING=y
CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH=y
CONFIG_CC_HAS_INT128=y
CONFIG_ARCH_SUPPORTS_INT128=y
CONFIG_NUMA_BALANCING=y
# CONFIG_NUMA_BALANCING_DEFAULT_ENABLED is not set
@@ -168,6 +169,7 @@ CONFIG_CGROUP_BPF=y
CONFIG_SOCK_CGROUP_DATA=y
CONFIG_NAMESPACES=y
CONFIG_UTS_NS=y
# CONFIG_TIME_NS is not set
CONFIG_IPC_NS=y
CONFIG_USER_NS=y
CONFIG_PID_NS=y
@@ -176,14 +178,22 @@ CONFIG_NET_NS=y
CONFIG_SCHED_AUTOGROUP=y
# CONFIG_SYSFS_DEPRECATED is not set
CONFIG_RELAY=y
# CONFIG_BLK_DEV_INITRD is not set
CONFIG_BLK_DEV_INITRD=y
CONFIG_INITRAMFS_SOURCE=""
CONFIG_RD_GZIP=y
CONFIG_RD_BZIP2=y
CONFIG_RD_LZMA=y
CONFIG_RD_XZ=y
CONFIG_RD_LZO=y
CONFIG_RD_LZ4=y
# CONFIG_BOOT_CONFIG is not set
CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE=y
# CONFIG_CC_OPTIMIZE_FOR_SIZE is not set
CONFIG_SYSCTL=y
CONFIG_SYSCTL_EXCEPTION_TRACE=y
CONFIG_HAVE_PCSPKR_PLATFORM=y
CONFIG_BPF=y
# CONFIG_EXPERT is not set
CONFIG_EXPERT=y
CONFIG_MULTIUSER=y
CONFIG_SGETMASK_SYSCALL=y
CONFIG_SYSFS_SYSCALL=y
@@ -211,11 +221,14 @@ CONFIG_KALLSYMS=y
CONFIG_KALLSYMS_ABSOLUTE_PERCPU=y
CONFIG_KALLSYMS_BASE_RELATIVE=y
CONFIG_BPF_SYSCALL=y
CONFIG_ARCH_WANT_DEFAULT_BPF_JIT=y
CONFIG_USERFAULTFD=y
CONFIG_ARCH_HAS_MEMBARRIER_SYNC_CORE=y
CONFIG_RSEQ=y
# CONFIG_DEBUG_RSEQ is not set
# CONFIG_EMBEDDED is not set
CONFIG_HAVE_PERF_EVENTS=y
# CONFIG_PC104 is not set
#
# Kernel Performance Events And Counters
@@ -226,9 +239,11 @@ CONFIG_PERF_EVENTS=y
CONFIG_VM_EVENT_COUNTERS=y
CONFIG_SLUB_DEBUG=y
# CONFIG_SLUB_MEMCG_SYSFS_ON is not set
# CONFIG_COMPAT_BRK is not set
# CONFIG_SLAB is not set
CONFIG_SLUB=y
# CONFIG_SLOB is not set
CONFIG_SLAB_MERGE_DEFAULT=y
# CONFIG_SLAB_FREELIST_RANDOM is not set
CONFIG_SLAB_FREELIST_HARDENED=y
@@ -296,6 +311,7 @@ CONFIG_PARAVIRT=y
CONFIG_PARAVIRT_SPINLOCKS=y
# CONFIG_XEN is not set
CONFIG_KVM_GUEST=y
CONFIG_ARCH_CPUIDLE_HALTPOLL=y
CONFIG_PVH=y
CONFIG_KVM_DEBUG_FS=y
CONFIG_PARAVIRT_TIME_ACCOUNTING=y
@@ -314,6 +330,9 @@ CONFIG_X86_CMPXCHG64=y
CONFIG_X86_CMOV=y
CONFIG_X86_MINIMUM_CPU_FAMILY=64
CONFIG_X86_DEBUGCTLMSR=y
CONFIG_IA32_FEAT_CTL=y
CONFIG_X86_VMX_FEATURE_NAMES=y
# CONFIG_PROCESSOR_SELECT is not set
CONFIG_CPU_SUP_INTEL=y
CONFIG_CPU_SUP_AMD=y
CONFIG_CPU_SUP_HYGON=y
@@ -322,7 +341,6 @@ CONFIG_CPU_SUP_ZHAOXIN=y
CONFIG_HPET_TIMER=y
CONFIG_DMI=y
# CONFIG_GART_IOMMU is not set
# CONFIG_CALGARY_IOMMU is not set
# CONFIG_MAXSMP is not set
CONFIG_NR_CPUS_RANGE_BEGIN=2
CONFIG_NR_CPUS_RANGE_END=512
@@ -348,6 +366,7 @@ CONFIG_PERF_EVENTS_INTEL_CSTATE=y
CONFIG_X86_16BIT=y
CONFIG_X86_ESPFIX64=y
CONFIG_X86_VSYSCALL_EMULATION=y
# CONFIG_X86_IOPL_IOPERM is not set
# CONFIG_I8K is not set
# CONFIG_MICROCODE is not set
CONFIG_X86_MSR=y
@@ -355,7 +374,6 @@ CONFIG_X86_CPUID=y
# CONFIG_X86_5LEVEL is not set
CONFIG_X86_DIRECT_GBPAGES=y
# CONFIG_X86_CPA_STATISTICS is not set
CONFIG_ARCH_HAS_MEM_ENCRYPT=y
CONFIG_AMD_MEM_ENCRYPT=y
# CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT is not set
CONFIG_NUMA=y
@@ -382,9 +400,11 @@ CONFIG_X86_PAT=y
CONFIG_ARCH_USES_PG_UNCACHED=y
CONFIG_ARCH_RANDOM=y
CONFIG_X86_SMAP=y
CONFIG_X86_INTEL_UMIP=y
# CONFIG_X86_INTEL_MPX is not set
# CONFIG_X86_UMIP is not set
# CONFIG_X86_INTEL_MEMORY_PROTECTION_KEYS is not set
CONFIG_X86_INTEL_TSX_MODE_OFF=y
# CONFIG_X86_INTEL_TSX_MODE_ON is not set
# CONFIG_X86_INTEL_TSX_MODE_AUTO is not set
CONFIG_EFI=y
CONFIG_EFI_STUB=y
# CONFIG_EFI_MIXED is not set
@@ -398,12 +418,16 @@ CONFIG_SCHED_HRTICK=y
# CONFIG_KEXEC is not set
CONFIG_KEXEC_FILE=y
CONFIG_ARCH_HAS_KEXEC_PURGATORY=y
CONFIG_KEXEC_VERIFY_SIG=y
# CONFIG_KEXEC_SIG is not set
# CONFIG_CRASH_DUMP is not set
CONFIG_PHYSICAL_START=0x1000000
CONFIG_RELOCATABLE=y
# CONFIG_RANDOMIZE_BASE is not set
CONFIG_RANDOMIZE_BASE=y
CONFIG_X86_NEED_RELOCS=y
CONFIG_PHYSICAL_ALIGN=0x1000000
CONFIG_DYNAMIC_MEMORY_LAYOUT=y
CONFIG_RANDOMIZE_MEMORY=y
CONFIG_RANDOMIZE_MEMORY_PHYSICAL_PADDING=0xa
CONFIG_HOTPLUG_CPU=y
# CONFIG_BOOTPARAM_HOTPLUG_CPU0 is not set
# CONFIG_DEBUG_HOTPLUG_CPU0 is not set
@@ -467,18 +491,20 @@ CONFIG_ACPI_PROCESSOR=y
CONFIG_ACPI_HOTPLUG_CPU=y
# CONFIG_ACPI_PROCESSOR_AGGREGATOR is not set
CONFIG_ACPI_THERMAL=y
CONFIG_ACPI_NUMA=y
CONFIG_ARCH_HAS_ACPI_TABLE_UPGRADE=y
CONFIG_ACPI_TABLE_UPGRADE=y
# CONFIG_ACPI_DEBUG is not set
# CONFIG_ACPI_PCI_SLOT is not set
CONFIG_ACPI_CONTAINER=y
# CONFIG_ACPI_HOTPLUG_MEMORY is not set
CONFIG_ACPI_HOTPLUG_MEMORY=y
CONFIG_ACPI_HOTPLUG_IOAPIC=y
# CONFIG_ACPI_SBS is not set
# CONFIG_ACPI_HED is not set
# CONFIG_ACPI_CUSTOM_METHOD is not set
# CONFIG_ACPI_BGRT is not set
CONFIG_ACPI_REDUCED_HARDWARE_ONLY=y
# CONFIG_ACPI_NFIT is not set
CONFIG_ACPI_NUMA=y
# CONFIG_ACPI_HMAT is not set
CONFIG_HAVE_ACPI_APEI=y
CONFIG_HAVE_ACPI_APEI_NMI=y
@@ -486,7 +512,6 @@ CONFIG_HAVE_ACPI_APEI_NMI=y
# CONFIG_DPTF_POWER is not set
# CONFIG_PMIC_OPREGION is not set
# CONFIG_ACPI_CONFIGFS is not set
CONFIG_ACPI_IORT=y
CONFIG_X86_PM_TIMER=y
# CONFIG_SFI is not set
@@ -529,6 +554,8 @@ CONFIG_CPU_IDLE=y
CONFIG_CPU_IDLE_GOV_LADDER=y
CONFIG_CPU_IDLE_GOV_MENU=y
# CONFIG_CPU_IDLE_GOV_TEO is not set
# CONFIG_CPU_IDLE_GOV_HALTPOLL is not set
# CONFIG_HALTPOLL_CPUIDLE is not set
# end of CPU Idle
CONFIG_INTEL_IDLE=y
@@ -540,6 +567,8 @@ CONFIG_INTEL_IDLE=y
CONFIG_PCI_DIRECT=y
CONFIG_PCI_MMCONFIG=y
CONFIG_MMCONF_FAM10H=y
# CONFIG_PCI_CNB20LE_QUIRK is not set
# CONFIG_ISA_BUS is not set
CONFIG_ISA_DMA_API=y
CONFIG_AMD_NB=y
# CONFIG_X86_SYSFB is not set
@@ -575,6 +604,8 @@ CONFIG_EFI_RUNTIME_WRAPPERS=y
# CONFIG_EFI_TEST is not set
# CONFIG_APPLE_PROPERTIES is not set
# CONFIG_RESET_ATTACK_MITIGATION is not set
# CONFIG_EFI_RCI2_TABLE is not set
# CONFIG_EFI_DISABLE_PCI_DMA is not set
# end of EFI (Extensible Firmware Interface) Support
CONFIG_EFI_EARLYCON=y
@@ -600,6 +631,7 @@ CONFIG_HAVE_KVM_IRQ_BYPASS=y
CONFIG_HAVE_KVM_NO_POLL=y
CONFIG_VIRTUALIZATION=y
CONFIG_KVM=y
# CONFIG_KVM_WERROR is not set
CONFIG_KVM_INTEL=y
# CONFIG_KVM_AMD is not set
# CONFIG_VHOST_NET is not set
@@ -634,6 +666,7 @@ CONFIG_ARCH_HAS_SET_MEMORY=y
CONFIG_ARCH_HAS_SET_DIRECT_MAP=y
CONFIG_HAVE_ARCH_THREAD_STRUCT_WHITELIST=y
CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT=y
CONFIG_HAVE_ASM_MODVERSIONS=y
CONFIG_HAVE_REGS_AND_STACK_ACCESS_API=y
CONFIG_HAVE_RSEQ=y
CONFIG_HAVE_FUNCTION_ARG_ACCESS_API=y
@@ -647,7 +680,8 @@ CONFIG_HAVE_PERF_REGS=y
CONFIG_HAVE_PERF_USER_STACK_DUMP=y
CONFIG_HAVE_ARCH_JUMP_LABEL=y
CONFIG_HAVE_ARCH_JUMP_LABEL_RELATIVE=y
CONFIG_HAVE_RCU_TABLE_FREE=y
CONFIG_MMU_GATHER_TABLE_FREE=y
CONFIG_MMU_GATHER_RCU_TABLE_FREE=y
CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG=y
CONFIG_HAVE_ALIGNED_STRUCT_PAGE=y
CONFIG_HAVE_CMPXCHG_LOCAL=y
@@ -679,17 +713,16 @@ CONFIG_ARCH_MMAP_RND_BITS=28
CONFIG_HAVE_COPY_THREAD_TLS=y
CONFIG_HAVE_STACK_VALIDATION=y
CONFIG_HAVE_RELIABLE_STACKTRACE=y
CONFIG_64BIT_TIME=y
# CONFIG_COMPAT_32BIT_TIME is not set
CONFIG_HAVE_ARCH_VMAP_STACK=y
CONFIG_VMAP_STACK=y
CONFIG_ARCH_HAS_STRICT_KERNEL_RWX=y
CONFIG_STRICT_KERNEL_RWX=y
CONFIG_ARCH_HAS_STRICT_MODULE_RWX=y
CONFIG_ARCH_HAS_REFCOUNT=y
# CONFIG_REFCOUNT_FULL is not set
CONFIG_HAVE_ARCH_PREL32_RELOCATIONS=y
CONFIG_ARCH_USE_MEMREMAP_PROT=y
# CONFIG_LOCK_EVENT_COUNTS is not set
CONFIG_ARCH_HAS_MEM_ENCRYPT=y
#
# GCOV-based kernel profiling
@@ -708,6 +741,7 @@ CONFIG_BASE_SMALL=0
CONFIG_MODULES_TREE_LOOKUP=y
CONFIG_BLOCK=y
CONFIG_BLK_SCSI_REQUEST=y
CONFIG_BLK_CGROUP_RWSTAT=y
CONFIG_BLK_DEV_BSG=y
CONFIG_BLK_DEV_BSGLIB=y
CONFIG_BLK_DEV_INTEGRITY=y
@@ -717,6 +751,7 @@ CONFIG_BLK_DEV_THROTTLING=y
CONFIG_BLK_CMDLINE_PARSER=y
CONFIG_BLK_WBT=y
# CONFIG_BLK_CGROUP_IOLATENCY is not set
# CONFIG_BLK_CGROUP_IOCOST is not set
CONFIG_BLK_WBT_MQ=y
CONFIG_BLK_DEBUG_FS=y
# CONFIG_BLK_SED_OPAL is not set
@@ -836,10 +871,10 @@ CONFIG_GENERIC_EARLY_IOREMAP=y
CONFIG_ARCH_HAS_PTE_DEVMAP=y
CONFIG_ZONE_DEVICE=y
CONFIG_DEV_PAGEMAP_OPS=y
# CONFIG_HMM_MIRROR is not set
# CONFIG_DEVICE_PRIVATE is not set
CONFIG_PERCPU_STATS=y
# CONFIG_GUP_BENCHMARK is not set
# CONFIG_READ_ONLY_THP_FOR_FS is not set
CONFIG_ARCH_HAS_PTE_SPECIAL=y
# end of Memory Management options
@@ -856,6 +891,7 @@ CONFIG_UNIX_SCM=y
CONFIG_UNIX_DIAG=y
CONFIG_TLS=y
# CONFIG_TLS_DEVICE is not set
# CONFIG_TLS_TOE is not set
CONFIG_XFRM=y
CONFIG_XFRM_ALGO=y
CONFIG_XFRM_USER=y
@@ -890,6 +926,7 @@ CONFIG_TCP_CONG_CUBIC=y
CONFIG_DEFAULT_TCP_CONG="cubic"
# CONFIG_TCP_MD5SIG is not set
# CONFIG_IPV6 is not set
# CONFIG_MPTCP is not set
# CONFIG_NETWORK_SECMARK is not set
CONFIG_NET_PTP_CLASSIFY=y
# CONFIG_NETWORK_PHY_TIMESTAMPING is not set
@@ -919,6 +956,7 @@ CONFIG_HAVE_NET_DSA=y
# CONFIG_OPENVSWITCH is not set
CONFIG_VSOCKETS=y
CONFIG_VSOCKETS_DIAG=y
# CONFIG_VSOCKETS_LOOPBACK is not set
CONFIG_VIRTIO_VSOCKETS=y
CONFIG_VIRTIO_VSOCKETS_COMMON=y
# CONFIG_NETLINK_DIAG is not set
@@ -964,6 +1002,7 @@ CONFIG_STREAM_PARSER=y
CONFIG_GRO_CELLS=y
CONFIG_NET_SOCK_MSG=y
CONFIG_FAILOVER=y
# CONFIG_ETHTOOL_NETLINK is not set
CONFIG_HAVE_EBPF_JIT=y
#
@@ -975,11 +1014,11 @@ CONFIG_HAVE_PCI=y
CONFIG_PCI=y
CONFIG_PCI_DOMAINS=y
CONFIG_PCIEPORTBUS=y
# CONFIG_HOTPLUG_PCI_PCIE is not set
CONFIG_PCIEAER=y
# CONFIG_PCIEAER_INJECT is not set
# CONFIG_PCIE_ECRC is not set
CONFIG_PCIEASPM=y
# CONFIG_PCIEASPM_DEBUG is not set
CONFIG_PCIEASPM_DEFAULT=y
# CONFIG_PCIEASPM_POWERSAVE is not set
# CONFIG_PCIEASPM_POWER_SUPERSAVE is not set
@@ -999,17 +1038,15 @@ CONFIG_PCI_LOCKLESS_CONFIG=y
# CONFIG_PCI_PASID is not set
# CONFIG_PCI_P2PDMA is not set
CONFIG_PCI_LABEL=y
# CONFIG_HOTPLUG_PCI is not set
CONFIG_HOTPLUG_PCI=y
CONFIG_HOTPLUG_PCI_ACPI=y
# CONFIG_HOTPLUG_PCI_ACPI_IBM is not set
# CONFIG_HOTPLUG_PCI_CPCI is not set
# CONFIG_HOTPLUG_PCI_SHPC is not set
#
# PCI controller drivers
#
#
# Cadence PCIe controllers support
#
# end of Cadence PCIe controllers support
# CONFIG_VMD is not set
#
@@ -1018,6 +1055,11 @@ CONFIG_PCI_LABEL=y
# CONFIG_PCIE_DW_PLAT_HOST is not set
# CONFIG_PCI_MESON is not set
# end of DesignWare PCI Core Support
#
# Cadence PCIe controllers support
#
# end of Cadence PCIe controllers support
# end of PCI controller drivers
#
@@ -1054,6 +1096,7 @@ CONFIG_EXTRA_FIRMWARE=""
CONFIG_FW_LOADER_USER_HELPER=y
# CONFIG_FW_LOADER_USER_HELPER_FALLBACK is not set
# CONFIG_FW_LOADER_COMPRESS is not set
# CONFIG_FW_CACHE is not set
# end of Firmware loader
CONFIG_ALLOW_DEV_COREDUMP=y
@@ -1104,7 +1147,6 @@ CONFIG_BLK_DEV_RAM_SIZE=16384
# CONFIG_CDROM_PKTCDVD is not set
# CONFIG_ATA_OVER_ETH is not set
CONFIG_VIRTIO_BLK=y
# CONFIG_VIRTIO_BLK_SCSI is not set
# CONFIG_BLK_DEV_RBD is not set
# CONFIG_BLK_DEV_RSXX is not set
@@ -1122,7 +1164,6 @@ CONFIG_VIRTIO_BLK=y
# CONFIG_DUMMY_IRQ is not set
# CONFIG_IBM_ASM is not set
# CONFIG_PHANTOM is not set
# CONFIG_SGI_IOC4 is not set
# CONFIG_TIFM_CORE is not set
# CONFIG_ENCLOSURE_SERVICES is not set
# CONFIG_HP_ILO is not set
@@ -1156,41 +1197,9 @@ CONFIG_VIRTIO_BLK=y
#
# Intel MIC & related support
#
#
# Intel MIC Bus Driver
#
# CONFIG_INTEL_MIC_BUS is not set
#
# SCIF Bus Driver
#
# CONFIG_SCIF_BUS is not set
#
# VOP Bus Driver
#
# CONFIG_VOP_BUS is not set
#
# Intel MIC Host Driver
#
#
# Intel MIC Card Driver
#
#
# SCIF Driver
#
#
# Intel MIC Coprocessor State Management (COSM) Drivers
#
#
# VOP Driver
#
# end of Intel MIC & related support
# CONFIG_GENWQE is not set
@@ -1228,6 +1237,7 @@ CONFIG_NETDEVICES=y
CONFIG_NET_CORE=y
# CONFIG_BONDING is not set
# CONFIG_DUMMY is not set
# CONFIG_WIREGUARD is not set
# CONFIG_EQUALIZER is not set
# CONFIG_NET_TEAM is not set
# CONFIG_MACVLAN is not set
@@ -1244,10 +1254,6 @@ CONFIG_VIRTIO_NET=y
# CONFIG_NLMON is not set
# CONFIG_ARCNET is not set
#
# CAIF transport drivers
#
#
# Distributed Switch Architecture drivers
#
@@ -1362,6 +1368,7 @@ CONFIG_SERIAL_EARLYCON=y
CONFIG_SERIAL_8250=y
# CONFIG_SERIAL_8250_DEPRECATED_OPTIONS is not set
CONFIG_SERIAL_8250_PNP=y
# CONFIG_SERIAL_8250_16550A_VARIANTS is not set
# CONFIG_SERIAL_8250_FINTEK is not set
CONFIG_SERIAL_8250_CONSOLE=y
CONFIG_SERIAL_8250_DMA=y
@@ -1370,11 +1377,11 @@ CONFIG_SERIAL_8250_EXAR=y
CONFIG_SERIAL_8250_NR_UARTS=1
CONFIG_SERIAL_8250_RUNTIME_UARTS=1
# CONFIG_SERIAL_8250_EXTENDED is not set
CONFIG_SERIAL_8250_DWLIB=y
# CONFIG_SERIAL_8250_DW is not set
# CONFIG_SERIAL_8250_RT288X is not set
CONFIG_SERIAL_8250_LPSS=y
CONFIG_SERIAL_8250_MID=y
# CONFIG_SERIAL_8250_MOXA is not set
#
# Non-8250 serial port support
@@ -1391,10 +1398,12 @@ CONFIG_SERIAL_ARC=y
CONFIG_SERIAL_ARC_NR_PORTS=1
# CONFIG_SERIAL_RP2 is not set
# CONFIG_SERIAL_FSL_LPUART is not set
# CONFIG_SERIAL_FSL_LINFLEXUART is not set
# end of Serial drivers
CONFIG_SERIAL_DEV_BUS=y
CONFIG_SERIAL_DEV_CTRL_TTYPORT=y
# CONFIG_TTY_PRINTK is not set
CONFIG_HVC_DRIVER=y
CONFIG_VIRTIO_CONSOLE=y
# CONFIG_IPMI_HANDLER is not set
@@ -1418,6 +1427,7 @@ CONFIG_DEVPORT=y
# end of Character devices
# CONFIG_RANDOM_TRUST_CPU is not set
# CONFIG_RANDOM_TRUST_BOOTLOADER is not set
#
# I2C support
@@ -1468,12 +1478,10 @@ CONFIG_THERMAL_WRITABLE_TRIPS=y
CONFIG_THERMAL_DEFAULT_GOV_STEP_WISE=y
# CONFIG_THERMAL_DEFAULT_GOV_FAIR_SHARE is not set
# CONFIG_THERMAL_DEFAULT_GOV_USER_SPACE is not set
# CONFIG_THERMAL_DEFAULT_GOV_POWER_ALLOCATOR is not set
CONFIG_THERMAL_GOV_FAIR_SHARE=y
CONFIG_THERMAL_GOV_STEP_WISE=y
# CONFIG_THERMAL_GOV_BANG_BANG is not set
CONFIG_THERMAL_GOV_USER_SPACE=y
# CONFIG_THERMAL_GOV_POWER_ALLOCATOR is not set
# CONFIG_THERMAL_EMULATION is not set
#
@@ -1500,7 +1508,6 @@ CONFIG_BCMA_POSSIBLE=y
#
# Multifunction device drivers
#
# CONFIG_MFD_CROS_EC is not set
# CONFIG_MFD_MADERA is not set
# CONFIG_HTC_PASIC3 is not set
# CONFIG_MFD_INTEL_QUARK_I2C_GPIO is not set
@@ -1533,7 +1540,6 @@ CONFIG_VGA_ARB=y
CONFIG_VGA_ARB_MAX_GPUS=16
# CONFIG_VGA_SWITCHEROO is not set
# CONFIG_DRM is not set
# CONFIG_DRM_DP_CEC is not set
#
# ARM devices
@@ -1609,7 +1615,7 @@ CONFIG_LCD_CLASS_DEVICE=y
CONFIG_BACKLIGHT_CLASS_DEVICE=y
CONFIG_BACKLIGHT_GENERIC=y
# CONFIG_BACKLIGHT_APPLE is not set
# CONFIG_BACKLIGHT_PM8941_WLED is not set
# CONFIG_BACKLIGHT_QCOM_WLED is not set
# CONFIG_BACKLIGHT_SAHARA is not set
# end of Backlight & LCD device support
@@ -1673,7 +1679,6 @@ CONFIG_HID_GENERIC=y
# CONFIG_HID_KENSINGTON is not set
# CONFIG_HID_LCPOWER is not set
# CONFIG_HID_LENOVO is not set
# CONFIG_HID_LOGITECH is not set
# CONFIG_HID_MAGICMOUSE is not set
# CONFIG_HID_MALTRON is not set
# CONFIG_HID_MAYFLASH is not set
@@ -1717,7 +1722,6 @@ CONFIG_HID_REDRAGON=y
CONFIG_USB_OHCI_LITTLE_ENDIAN=y
# CONFIG_USB_SUPPORT is not set
# CONFIG_UWB is not set
# CONFIG_MMC is not set
# CONFIG_MEMSTICK is not set
# CONFIG_NEW_LEDS is not set
@@ -1740,7 +1744,9 @@ CONFIG_DMA_VIRTUAL_CHANNELS=y
CONFIG_DMA_ACPI=y
# CONFIG_ALTERA_MSGDMA is not set
# CONFIG_INTEL_IDMA64 is not set
# CONFIG_INTEL_IDXD is not set
# CONFIG_INTEL_IOATDMA is not set
# CONFIG_PLX_DMA is not set
# CONFIG_QCOM_HIDMA_MGMT is not set
# CONFIG_QCOM_HIDMA is not set
CONFIG_DW_DMAC_CORE=y
@@ -1749,6 +1755,7 @@ CONFIG_DW_DMAC_CORE=y
# CONFIG_DW_EDMA is not set
# CONFIG_DW_EDMA_PCIE is not set
CONFIG_HSU_DMA=y
# CONFIG_SF_PDMA is not set
#
# DMA Clients
@@ -1760,6 +1767,7 @@ CONFIG_HSU_DMA=y
# DMABUF options
#
# CONFIG_SYNC_FILE is not set
# CONFIG_DMABUF_HEAPS is not set
# end of DMABUF options
# CONFIG_AUXDISPLAY is not set
@@ -1791,6 +1799,7 @@ CONFIG_VIRTIO_PCI=y
CONFIG_VIRTIO_PCI_LEGACY=y
CONFIG_VIRTIO_PMEM=y
CONFIG_VIRTIO_BALLOON=y
CONFIG_VIRTIO_MEM=y
CONFIG_VIRTIO_INPUT=y
CONFIG_VIRTIO_MMIO=y
CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y
@@ -1801,9 +1810,11 @@ CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES=y
# CONFIG_HYPERV is not set
# end of Microsoft Hyper-V guest support
# CONFIG_GREYBUS is not set
# CONFIG_STAGING is not set
# CONFIG_X86_PLATFORM_DEVICES is not set
CONFIG_PMC_ATOM=y
# CONFIG_MFD_CROS_EC is not set
# CONFIG_CHROME_PLATFORMS is not set
# CONFIG_MELLANOX_PLATFORM is not set
CONFIG_CLKDEV_LOOKUP=y
@@ -1844,6 +1855,7 @@ CONFIG_IOMMU_DMA=y
# CONFIG_INTEL_IOMMU is not set
# CONFIG_IRQ_REMAP is not set
CONFIG_VIRTIO_IOMMU=y
CONFIG_VIRTIO_IOMMU_TOPOLOGY=y
#
# Remoteproc drivers
@@ -1889,13 +1901,6 @@ CONFIG_VIRTIO_IOMMU=y
#
# end of i.MX SoC drivers
#
# IXP4xx SoC drivers
#
# CONFIG_IXP4XX_QMGR is not set
# CONFIG_IXP4XX_NPE is not set
# end of IXP4xx SoC drivers
#
# Qualcomm SoC drivers
#
@@ -1933,6 +1938,7 @@ CONFIG_VIRTIO_IOMMU=y
# CONFIG_BCM_KONA_USB2_PHY is not set
# CONFIG_PHY_PXA_28NM_HSIC is not set
# CONFIG_PHY_PXA_28NM_USB2 is not set
# CONFIG_PHY_INTEL_EMMC is not set
# end of PHY Subsystem
# CONFIG_POWERCAP is not set
@@ -1944,7 +1950,7 @@ CONFIG_VIRTIO_IOMMU=y
# end of Performance monitor support
CONFIG_RAS=y
# CONFIG_THUNDERBOLT is not set
# CONFIG_USB4 is not set
#
# Android
@@ -1974,6 +1980,7 @@ CONFIG_DAX=y
# end of HW tracing support
# CONFIG_FPGA is not set
# CONFIG_TEE is not set
# CONFIG_UNISYS_VISORBUS is not set
# CONFIG_SIOX is not set
# CONFIG_SLIMBUS is not set
@@ -2013,6 +2020,8 @@ CONFIG_EXPORTFS=y
CONFIG_FILE_LOCKING=y
CONFIG_MANDATORY_FILE_LOCKING=y
CONFIG_FS_ENCRYPTION=y
CONFIG_FS_ENCRYPTION_ALGS=y
# CONFIG_FS_VERITY is not set
CONFIG_FSNOTIFY=y
CONFIG_DNOTIFY=y
CONFIG_INOTIFY_USER=y
@@ -2139,6 +2148,7 @@ CONFIG_NLS_MAC_TURKISH=y
CONFIG_NLS_UTF8=y
# CONFIG_DLM is not set
# CONFIG_UNICODE is not set
CONFIG_IO_WQ=y
# end of File systems
#
@@ -2185,8 +2195,8 @@ CONFIG_CRYPTO_ALGAPI=y
CONFIG_CRYPTO_ALGAPI2=y
CONFIG_CRYPTO_AEAD=y
CONFIG_CRYPTO_AEAD2=y
CONFIG_CRYPTO_BLKCIPHER=y
CONFIG_CRYPTO_BLKCIPHER2=y
CONFIG_CRYPTO_SKCIPHER=y
CONFIG_CRYPTO_SKCIPHER2=y
CONFIG_CRYPTO_HASH=y
CONFIG_CRYPTO_HASH2=y
CONFIG_CRYPTO_RNG=y
@@ -2216,6 +2226,8 @@ CONFIG_CRYPTO_GLUE_HELPER_X86=y
# CONFIG_CRYPTO_DH is not set
# CONFIG_CRYPTO_ECDH is not set
# CONFIG_CRYPTO_ECRDSA is not set
# CONFIG_CRYPTO_CURVE25519 is not set
# CONFIG_CRYPTO_CURVE25519_X86 is not set
#
# Authenticated Encryption with Associated Data
@@ -2224,16 +2236,7 @@ CONFIG_CRYPTO_GLUE_HELPER_X86=y
CONFIG_CRYPTO_GCM=y
# CONFIG_CRYPTO_CHACHA20POLY1305 is not set
# CONFIG_CRYPTO_AEGIS128 is not set
# CONFIG_CRYPTO_AEGIS128L is not set
# CONFIG_CRYPTO_AEGIS256 is not set
# CONFIG_CRYPTO_AEGIS128_AESNI_SSE2 is not set
# CONFIG_CRYPTO_AEGIS128L_AESNI_SSE2 is not set
# CONFIG_CRYPTO_AEGIS256_AESNI_SSE2 is not set
# CONFIG_CRYPTO_MORUS640 is not set
# CONFIG_CRYPTO_MORUS640_SSE2 is not set
# CONFIG_CRYPTO_MORUS1280 is not set
# CONFIG_CRYPTO_MORUS1280_SSE2 is not set
# CONFIG_CRYPTO_MORUS1280_AVX2 is not set
CONFIG_CRYPTO_SEQIV=y
CONFIG_CRYPTO_ECHAINIV=y
@@ -2253,6 +2256,7 @@ CONFIG_CRYPTO_XTS=y
# CONFIG_CRYPTO_NHPOLY1305_SSE2 is not set
# CONFIG_CRYPTO_NHPOLY1305_AVX2 is not set
# CONFIG_CRYPTO_ADIANTUM is not set
# CONFIG_CRYPTO_ESSIV is not set
#
# Hash modes
@@ -2270,6 +2274,9 @@ CONFIG_CRYPTO_CRC32C_INTEL=y
# CONFIG_CRYPTO_CRC32 is not set
# CONFIG_CRYPTO_CRC32_PCLMUL is not set
# CONFIG_CRYPTO_XXHASH is not set
# CONFIG_CRYPTO_BLAKE2B is not set
# CONFIG_CRYPTO_BLAKE2S is not set
# CONFIG_CRYPTO_BLAKE2S_X86 is not set
CONFIG_CRYPTO_CRCT10DIF=y
# CONFIG_CRYPTO_CRCT10DIF_PCLMUL is not set
CONFIG_CRYPTO_GHASH=y
@@ -2300,10 +2307,8 @@ CONFIG_CRYPTO_SHA512=y
#
CONFIG_CRYPTO_AES=y
# CONFIG_CRYPTO_AES_TI is not set
CONFIG_CRYPTO_AES_X86_64=y
CONFIG_CRYPTO_AES_NI_INTEL=y
# CONFIG_CRYPTO_ANUBIS is not set
CONFIG_CRYPTO_LIB_ARC4=y
CONFIG_CRYPTO_ARC4=y
# CONFIG_CRYPTO_BLOWFISH is not set
# CONFIG_CRYPTO_BLOWFISH_X86_64 is not set
@@ -2360,6 +2365,21 @@ CONFIG_CRYPTO_USER_API=y
# CONFIG_CRYPTO_USER_API_SKCIPHER is not set
CONFIG_CRYPTO_USER_API_RNG=y
# CONFIG_CRYPTO_USER_API_AEAD is not set
#
# Crypto library routines
#
CONFIG_CRYPTO_LIB_AES=y
CONFIG_CRYPTO_LIB_ARC4=y
# CONFIG_CRYPTO_LIB_BLAKE2S is not set
# CONFIG_CRYPTO_LIB_CHACHA is not set
# CONFIG_CRYPTO_LIB_CURVE25519 is not set
CONFIG_CRYPTO_LIB_DES=y
CONFIG_CRYPTO_LIB_POLY1305_RSIZE=11
CONFIG_CRYPTO_LIB_POLY1305_GENERIC=y
# CONFIG_CRYPTO_LIB_POLY1305 is not set
# CONFIG_CRYPTO_LIB_CHACHA20POLY1305 is not set
CONFIG_CRYPTO_LIB_SHA256=y
# CONFIG_CRYPTO_HW is not set
# CONFIG_ASYMMETRIC_KEY_TYPE is not set
@@ -2406,7 +2426,22 @@ CONFIG_ZLIB_INFLATE=y
CONFIG_ZLIB_DEFLATE=y
CONFIG_LZO_COMPRESS=y
CONFIG_LZO_DECOMPRESS=y
# CONFIG_XZ_DEC is not set
CONFIG_LZ4_DECOMPRESS=y
CONFIG_XZ_DEC=y
CONFIG_XZ_DEC_X86=y
CONFIG_XZ_DEC_POWERPC=y
CONFIG_XZ_DEC_IA64=y
CONFIG_XZ_DEC_ARM=y
CONFIG_XZ_DEC_ARMTHUMB=y
CONFIG_XZ_DEC_SPARC=y
CONFIG_XZ_DEC_BCJ=y
# CONFIG_XZ_DEC_TEST is not set
CONFIG_DECOMPRESS_GZIP=y
CONFIG_DECOMPRESS_BZIP2=y
CONFIG_DECOMPRESS_LZMA=y
CONFIG_DECOMPRESS_XZ=y
CONFIG_DECOMPRESS_LZO=y
CONFIG_DECOMPRESS_LZ4=y
CONFIG_INTERVAL_TREE=y
CONFIG_XARRAY_MULTI=y
CONFIG_ASSOCIATIVE_ARRAY=y
@@ -2424,15 +2459,16 @@ CONFIG_CPU_RMAP=y
CONFIG_DQL=y
CONFIG_NLATTR=y
CONFIG_IRQ_POLL=y
# CONFIG_DIMLIB is not set
CONFIG_UCS2_STRING=y
CONFIG_HAVE_GENERIC_VDSO=y
CONFIG_GENERIC_GETTIMEOFDAY=y
CONFIG_GENERIC_VDSO_TIME_NS=y
CONFIG_FONT_SUPPORT=y
# CONFIG_FONTS is not set
CONFIG_FONT_8x8=y
CONFIG_FONT_8x16=y
CONFIG_ARCH_HAS_PMEM_API=y
CONFIG_MEMREGION=y
CONFIG_ARCH_HAS_UACCESS_FLUSHCACHE=y
CONFIG_ARCH_STACKWALK=y
CONFIG_SBITMAP=y
@@ -2453,6 +2489,8 @@ CONFIG_CONSOLE_LOGLEVEL_QUIET=4
CONFIG_MESSAGE_LOGLEVEL_DEFAULT=4
# CONFIG_BOOT_PRINTK_DELAY is not set
CONFIG_DYNAMIC_DEBUG=y
CONFIG_SYMBOLIC_ERRNAME=y
# CONFIG_DEBUG_BUGVERBOSE is not set
# end of printk and dmesg options
#
@@ -2463,8 +2501,6 @@ CONFIG_DYNAMIC_DEBUG=y
CONFIG_FRAME_WARN=2048
CONFIG_STRIP_ASM_SYMS=y
# CONFIG_READABLE_ASM is not set
CONFIG_UNUSED_SYMBOLS=y
CONFIG_DEBUG_FS=y
# CONFIG_HEADERS_INSTALL is not set
CONFIG_OPTIMIZE_INLINING=y
CONFIG_DEBUG_SECTION_MISMATCH=y
@@ -2474,9 +2510,20 @@ CONFIG_STACK_VALIDATION=y
# CONFIG_DEBUG_FORCE_WEAK_PER_CPU is not set
# end of Compile-time checks and compiler options
#
# Generic Kernel Debugging Instruments
#
CONFIG_MAGIC_SYSRQ=y
CONFIG_MAGIC_SYSRQ_DEFAULT_ENABLE=0x1
CONFIG_MAGIC_SYSRQ_SERIAL=y
CONFIG_DEBUG_FS=y
CONFIG_HAVE_ARCH_KGDB=y
# CONFIG_KGDB is not set
CONFIG_ARCH_HAS_UBSAN_SANITIZE_ALL=y
# CONFIG_UBSAN is not set
CONFIG_UBSAN_ALIGNMENT=y
# end of Generic Kernel Debugging Instruments
CONFIG_DEBUG_KERNEL=y
CONFIG_DEBUG_MISC=y
@@ -2488,45 +2535,50 @@ CONFIG_DEBUG_MISC=y
# CONFIG_PAGE_OWNER is not set
# CONFIG_PAGE_POISONING is not set
# CONFIG_DEBUG_RODATA_TEST is not set
CONFIG_GENERIC_PTDUMP=y
# CONFIG_PTDUMP_DEBUGFS is not set
# CONFIG_DEBUG_OBJECTS is not set
# CONFIG_SLUB_DEBUG_ON is not set
# CONFIG_SLUB_STATS is not set
CONFIG_HAVE_DEBUG_KMEMLEAK=y
# CONFIG_DEBUG_KMEMLEAK is not set
# CONFIG_DEBUG_STACK_USAGE is not set
# CONFIG_SCHED_STACK_END_CHECK is not set
# CONFIG_DEBUG_VM is not set
CONFIG_ARCH_HAS_DEBUG_VIRTUAL=y
# CONFIG_DEBUG_VIRTUAL is not set
CONFIG_DEBUG_MEMORY_INIT=y
# CONFIG_DEBUG_PER_CPU_MAPS is not set
CONFIG_HAVE_ARCH_KASAN=y
CONFIG_HAVE_ARCH_KASAN_VMALLOC=y
CONFIG_CC_HAS_KASAN_GENERIC=y
# CONFIG_KASAN is not set
CONFIG_KASAN_STACK=1
# end of Memory Debugging
CONFIG_ARCH_HAS_KCOV=y
CONFIG_CC_HAS_SANCOV_TRACE_PC=y
# CONFIG_KCOV is not set
# CONFIG_DEBUG_SHIRQ is not set
#
# Debug Lockups and Hangs
# Debug Oops, Lockups and Hangs
#
# CONFIG_PANIC_ON_OOPS is not set
CONFIG_PANIC_ON_OOPS_VALUE=0
CONFIG_PANIC_TIMEOUT=0
# CONFIG_SOFTLOCKUP_DETECTOR is not set
CONFIG_HARDLOCKUP_CHECK_TIMESTAMP=y
# CONFIG_HARDLOCKUP_DETECTOR is not set
# CONFIG_DETECT_HUNG_TASK is not set
# CONFIG_WQ_WATCHDOG is not set
# end of Debug Lockups and Hangs
# end of Debug Oops, Lockups and Hangs
# CONFIG_PANIC_ON_OOPS is not set
CONFIG_PANIC_ON_OOPS_VALUE=0
CONFIG_PANIC_TIMEOUT=0
#
# Scheduler Debugging
#
# CONFIG_SCHED_DEBUG is not set
CONFIG_SCHED_INFO=y
# CONFIG_SCHEDSTATS is not set
# CONFIG_SCHED_STACK_END_CHECK is not set
# end of Scheduler Debugging
# CONFIG_DEBUG_TIMEKEEPING is not set
#
@@ -2550,11 +2602,17 @@ CONFIG_LOCK_DEBUGGING_SUPPORT=y
CONFIG_STACKTRACE=y
# CONFIG_WARN_ALL_UNSEEDED_RANDOM is not set
# CONFIG_DEBUG_KOBJECT is not set
CONFIG_DEBUG_BUGVERBOSE=y
#
# Debug kernel data structures
#
CONFIG_DEBUG_LIST=y
# CONFIG_DEBUG_PLIST is not set
# CONFIG_DEBUG_SG is not set
# CONFIG_DEBUG_NOTIFIERS is not set
CONFIG_BUG_ON_DATA_CORRUPTION=y
# end of Debug kernel data structures
# CONFIG_DEBUG_CREDENTIALS is not set
#
@@ -2570,14 +2628,13 @@ CONFIG_RCU_CPU_STALL_TIMEOUT=59
# CONFIG_DEBUG_WQ_FORCE_RR_CPU is not set
# CONFIG_DEBUG_BLOCK_EXT_DEVT is not set
# CONFIG_CPU_HOTPLUG_STATE_CONTROL is not set
# CONFIG_NOTIFIER_ERROR_INJECTION is not set
# CONFIG_FAULT_INJECTION is not set
# CONFIG_LATENCYTOP is not set
CONFIG_USER_STACKTRACE_SUPPORT=y
CONFIG_HAVE_FUNCTION_TRACER=y
CONFIG_HAVE_FUNCTION_GRAPH_TRACER=y
CONFIG_HAVE_DYNAMIC_FTRACE=y
CONFIG_HAVE_DYNAMIC_FTRACE_WITH_REGS=y
CONFIG_HAVE_DYNAMIC_FTRACE_WITH_DIRECT_CALLS=y
CONFIG_HAVE_FTRACE_MCOUNT_RECORD=y
CONFIG_HAVE_SYSCALL_TRACEPOINTS=y
CONFIG_HAVE_FENTRY=y
@@ -2585,6 +2642,49 @@ CONFIG_HAVE_C_RECORDMCOUNT=y
CONFIG_TRACING_SUPPORT=y
# CONFIG_FTRACE is not set
# CONFIG_PROVIDE_OHCI1394_DMA_INIT is not set
# CONFIG_SAMPLES is not set
CONFIG_ARCH_HAS_DEVMEM_IS_ALLOWED=y
CONFIG_STRICT_DEVMEM=y
# CONFIG_IO_STRICT_DEVMEM is not set
#
# x86 Debugging
#
CONFIG_TRACE_IRQFLAGS_SUPPORT=y
CONFIG_X86_VERBOSE_BOOTUP=y
CONFIG_EARLY_PRINTK=y
# CONFIG_EARLY_PRINTK_DBGP is not set
# CONFIG_EARLY_PRINTK_USB_XDBC is not set
# CONFIG_EFI_PGT_DUMP is not set
# CONFIG_DEBUG_WX is not set
CONFIG_DOUBLEFAULT=y
# CONFIG_DEBUG_TLBFLUSH is not set
CONFIG_HAVE_MMIOTRACE_SUPPORT=y
# CONFIG_X86_DECODER_SELFTEST is not set
CONFIG_IO_DELAY_0X80=y
# CONFIG_IO_DELAY_0XED is not set
# CONFIG_IO_DELAY_UDELAY is not set
# CONFIG_IO_DELAY_NONE is not set
# CONFIG_DEBUG_BOOT_PARAMS is not set
# CONFIG_CPA_DEBUG is not set
# CONFIG_DEBUG_ENTRY is not set
# CONFIG_DEBUG_NMI_SELFTEST is not set
# CONFIG_X86_DEBUG_FPU is not set
# CONFIG_PUNIT_ATOM_DEBUG is not set
# CONFIG_UNWINDER_ORC is not set
CONFIG_UNWINDER_FRAME_POINTER=y
# CONFIG_UNWINDER_GUESS is not set
# end of x86 Debugging
#
# Kernel Testing and Coverage
#
# CONFIG_KUNIT is not set
# CONFIG_NOTIFIER_ERROR_INJECTION is not set
# CONFIG_FAULT_INJECTION is not set
CONFIG_ARCH_HAS_KCOV=y
CONFIG_CC_HAS_SANCOV_TRACE_PC=y
# CONFIG_KCOV is not set
CONFIG_RUNTIME_TESTING_MENU=y
# CONFIG_LKDTM is not set
# CONFIG_TEST_LIST_SORT is not set
@@ -2615,37 +2715,5 @@ CONFIG_RUNTIME_TESTING_MENU=y
# CONFIG_TEST_STACKINIT is not set
# CONFIG_TEST_MEMINIT is not set
# CONFIG_MEMTEST is not set
CONFIG_BUG_ON_DATA_CORRUPTION=y
# CONFIG_SAMPLES is not set
CONFIG_HAVE_ARCH_KGDB=y
# CONFIG_KGDB is not set
CONFIG_ARCH_HAS_UBSAN_SANITIZE_ALL=y
# CONFIG_UBSAN is not set
CONFIG_UBSAN_ALIGNMENT=y
CONFIG_ARCH_HAS_DEVMEM_IS_ALLOWED=y
CONFIG_STRICT_DEVMEM=y
# CONFIG_IO_STRICT_DEVMEM is not set
CONFIG_TRACE_IRQFLAGS_SUPPORT=y
CONFIG_X86_VERBOSE_BOOTUP=y
CONFIG_EARLY_PRINTK=y
# CONFIG_EARLY_PRINTK_DBGP is not set
# CONFIG_EARLY_PRINTK_USB_XDBC is not set
# CONFIG_X86_PTDUMP is not set
# CONFIG_EFI_PGT_DUMP is not set
# CONFIG_DEBUG_WX is not set
CONFIG_DOUBLEFAULT=y
# CONFIG_DEBUG_TLBFLUSH is not set
CONFIG_HAVE_MMIOTRACE_SUPPORT=y
CONFIG_IO_DELAY_0X80=y
# CONFIG_IO_DELAY_0XED is not set
# CONFIG_IO_DELAY_UDELAY is not set
# CONFIG_IO_DELAY_NONE is not set
# CONFIG_DEBUG_BOOT_PARAMS is not set
# CONFIG_CPA_DEBUG is not set
# CONFIG_DEBUG_ENTRY is not set
# CONFIG_DEBUG_NMI_SELFTEST is not set
# CONFIG_X86_DEBUG_FPU is not set
# CONFIG_PUNIT_ATOM_DEBUG is not set
# CONFIG_UNWINDER_ORC is not set
CONFIG_UNWINDER_FRAME_POINTER=y
# end of Kernel Testing and Coverage
# end of Kernel hacking

370
scripts/dev_cli.sh Executable file
View File

@@ -0,0 +1,370 @@
#!/bin/bash
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Copyright © 2020 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
CLI_NAME="Cloud Hypervisor"
CTR_IMAGE_TAG="cloudhypervisor/dev"
CTR_IMAGE_VERSION="v2"
CTR_IMAGE="${CTR_IMAGE_TAG}:${CTR_IMAGE_VERSION}"
DOCKER_RUNTIME="docker"
# Host paths
CLH_SCRIPTS_DIR=$(cd "$(dirname "$0")" && pwd)
CLH_ROOT_DIR=$(cd "${CLH_SCRIPTS_DIR}/.." && pwd)
CLH_BUILD_DIR="${CLH_ROOT_DIR}/build"
CLH_CARGO_TARGET="${CLH_BUILD_DIR}/cargo_target"
CLH_DOCKERFILE="${CLH_SCRIPTS_DIR}/../resources/Dockerfile"
CLH_CTR_BUILD_DIR="/tmp/cloud-hypervisor/ctr-build"
CLH_INTEGRATION_WORKLOADS="${HOME}/workloads"
# Container paths
CTR_CLH_ROOT_DIR="/cloud-hypervisor"
CTR_CLH_CARGO_BUILT_DIR="${CTR_CLH_ROOT_DIR}/build"
CTR_CLH_CARGO_TARGET="${CTR_CLH_CARGO_BUILT_DIR}/cargo_target"
CTR_CLH_INTEGRATION_WORKLOADS="/root/workloads"
# Cargo paths
# Full path to the cargo registry dir on the host. This appears on the host
# because we want to persist the cargo registry across container invocations.
# Otherwise, any rust crates from crates.io would be downloaded again each time
# we build or test.
CARGO_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_registry"
# Full path to the cargo git registry on the host. This serves the same purpose
# as CARGO_REGISTRY_DIR, for crates downloaded from GitHub repos instead of
# crates.io.
CARGO_GIT_REGISTRY_DIR="${CLH_BUILD_DIR}/cargo_git_registry"
# Full path to the cargo target dir on the host.
CARGO_TARGET_DIR="${CLH_BUILD_DIR}/cargo_target"
# Send a decorated message to stdout, followed by a new line
#
say() {
[ -t 1 ] && [ -n "$TERM" ] \
&& echo "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" \
|| echo "[$CLI_NAME] $*"
}
# Send a decorated message to stdout, without a trailing new line
#
say_noln() {
[ -t 1 ] && [ -n "$TERM" ] \
&& echo -n "$(tput setaf 2)[$CLI_NAME]$(tput sgr0) $*" \
|| echo "[$CLI_NAME] $*"
}
# Send a text message to stderr
#
say_err() {
[ -t 2 ] && [ -n "$TERM" ] \
&& echo "$(tput setaf 1)[$CLI_NAME] $*$(tput sgr0)" 1>&2 \
|| echo "[$CLI_NAME] $*" 1>&2
}
# Send a warning-highlighted text to stdout
say_warn() {
[ -t 1 ] && [ -n "$TERM" ] \
&& echo "$(tput setaf 3)[$CLI_NAME] $*$(tput sgr0)" \
|| echo "[$CLI_NAME] $*"
}
# Exit with an error message and (optional) code
# Usage: die [-c <error code>] <error message>
#
die() {
code=1
[[ "$1" = "-c" ]] && {
code="$2"
shift 2
}
say_err "$@"
exit $code
}
# Exit with an error message if the last exit code is not 0
#
ok_or_die() {
code=$?
[[ $code -eq 0 ]] || die -c $code "$@"
}
# Make sure the build/ dirs are available. Exit if we can't create them.
# Upon returning from this call, the caller can be certain the build/ dirs exist.
#
ensure_build_dir() {
for dir in "$CLH_BUILD_DIR" \
"$CLH_INTEGRATION_WORKLOADS" \
"$CLH_CTR_BUILD_DIR" \
"$CARGO_TARGET_DIR" \
"$CARGO_REGISTRY_DIR" \
"$CARGO_GIT_REGISTRY_DIR"; do
mkdir -p "$dir" || die "Error: cannot create dir $dir"
[ -x "$dir" ] && [ -w "$dir" ] || \
{
say "Wrong permissions for $dir. Attempting to fix them ..."
chmod +x+w "$dir"
} || \
die "Error: wrong permissions for $dir. Should be +x+w"
done
}
# Make sure we're using the latest dev container, by just pulling it.
ensure_latest_ctr() {
$DOCKER_RUNTIME pull "$CTR_IMAGE"
ok_or_die "Error pulling container image. Aborting."
}
# Fix main directory permissions after a container ran as root.
# Since the container ran as root, any files it creates will be owned by root.
# This fixes that by recursively changing the ownership of /cloud-hypervisor to the
# current user.
#
fix_dir_perms() {
# Yes, running Docker to get elevated privileges, just to chown some files
# is a dirty hack.
$DOCKER_RUNTIME run \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--volume /dev:/dev \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
"$CTR_IMAGE" \
chown -R "$(id -u):$(id -g)" "$CTR_CLH_ROOT_DIR"
return $1
}
cmd_help() {
echo ""
echo "Cloud Hypervisor $(basename $0)"
echo "Usage: $(basename $0) <command> [<command args>]"
echo ""
echo "Available commands:"
echo ""
echo " build [--debug|--release] [--libc musl|gnu] [-- [<cargo args>]]"
echo " Build the Cloud Hypervisor binaries."
echo " --debug Build the debug binaries. This is the default."
echo " --release Build the release binaries."
echo " --libc Select the C library Cloud Hypervisor will be built against. Default is gnu"
echo ""
echo " tests [--unit|--cargo|--all] [--libc musl|gnu] [-- [<cargo test args>]]"
echo " Run the Cloud Hypervisor tests."
echo " --unit Run the unit tests."
echo " --cargo Run the cargo tests."
echo " --integration Run the integration tests."
echo " --libc Select the C library Cloud Hypervisor will be built against. Default is gnu"
echo " --all Run all tests."
echo ""
echo " build-container [--type]"
echo " Build the Cloud Hypervisor container."
echo " --dev Build dev container. This is the default."
echo ""
echo " clean [<cargo args>]]"
echo " Remove the Cloud Hypervisor artifacts."
echo ""
echo " help"
echo " Display this help message."
echo ""
}
cmd_build() {
build="debug"
libc="gnu"
while [ $# -gt 0 ]; do
case "$1" in
"-h"|"--help") { cmd_help; exit 1; } ;;
"--debug") { build="debug"; } ;;
"--release") { build="release"; } ;;
"--libc")
shift
[[ "$1" =~ ^(musl|gnu)$ ]] || \
die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
libc="$1"
;;
"--") { shift; break; } ;;
*)
die "Unknown build argument: $1. Please use --help for help."
;;
esac
shift
done
target="$(uname -m)-unknown-linux-${libc}"
cargo_args=("$@")
[ $build = "release" ] && cargo_args+=("--release")
cargo_args+=(--target "$target")
$DOCKER_RUNTIME run \
--user "$(id -u):$(id -g)" \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--volume /dev:/dev \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
"$CTR_IMAGE" \
cargo build \
--target-dir "$CTR_CLH_CARGO_TARGET" \
"${cargo_args[@]}" && say "Binaries placed under $CLH_CARGO_TARGET/$target/$build"
}
cmd_clean() {
cargo_args=("$@")
$DOCKER_RUNTIME run \
--user "$(id -u):$(id -g)" \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
"$CTR_IMAGE" \
cargo clean \
--target-dir "$CTR_CLH_CARGO_TARGET" \
"${cargo_args[@]}"
}
cmd_tests() {
unit=false
cargo=false
integration=false
libc="gnu"
while [ $# -gt 0 ]; do
case "$1" in
"-h"|"--help") { cmd_help; exit 1; } ;;
"--unit") { unit=true; } ;;
"--cargo") { cargo=true; } ;;
"--integration") { integration=true; } ;;
"--libc")
shift
[[ "$1" =~ ^(musl|gnu)$ ]] || \
die "Invalid libc: $1. Valid options are \"musl\" and \"gnu\"."
libc="$1"
;;
"--all") { cargo=true; unit=true; integration=true; } ;;
"--") { shift; break; } ;;
*)
die "Unknown tests argument: $1. Please use --help for help."
;;
esac
shift
done
target="$(uname -m)-unknown-linux-${libc}"
cflags=""
target_cc=""
if [[ "$target" == "x86_64-unknown-linux-musl" ]]; then
target_cc="musl-gcc"
cflags="-I /usr/include/x86_64-linux-musl/ -idirafter /usr/include/"
fi
if [ "$unit" = true ] ; then
say "Running unit tests for $target..."
$DOCKER_RUNTIME run \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--device /dev/kvm \
--device /dev/net/tun \
--cap-add net_admin \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
--env BUILD_TARGET="$target" \
--env CFLAGS="$cflags" \
--env TARGET_CC="$target_cc" \
"$CTR_IMAGE" \
./scripts/run_unit_tests.sh "$@" || fix_dir_perms $? || exit $?
fi
if [ "$cargo" = true ] ; then
say "Running cargo tests..."
$DOCKER_RUNTIME run \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
"$CTR_IMAGE" \
./scripts/run_cargo_tests.sh || fix_dir_perms $? || exit $?
fi
if [ "$integration" = true ] ; then
say "Running integration tests for $target..."
$DOCKER_RUNTIME run \
--workdir "$CTR_CLH_ROOT_DIR" \
--rm \
--privileged \
--security-opt seccomp=unconfined \
--ipc=host \
--net=host \
--mount type=tmpfs,destination=/tmp \
--volume /dev:/dev \
--volume "$CLH_ROOT_DIR:$CTR_CLH_ROOT_DIR" \
--volume "$CLH_INTEGRATION_WORKLOADS:$CTR_CLH_INTEGRATION_WORKLOADS" \
--env USER="root" \
--env BUILD_TARGET="$target" \
--env CFLAGS="$cflags" \
--env TARGET_CC="$target_cc" \
"$CTR_IMAGE" \
./scripts/run_integration_tests.sh "$@" || fix_dir_perms $? || exit $?
fi
fix_dir_perms $?
}
cmd_build-container() {
container_type="dev"
while [ $# -gt 0 ]; do
case "$1" in
"-h"|"--help") { cmd_help; exit 1; } ;;
"--dev") { container_type="dev"; } ;;
"--") { shift; break; } ;;
*)
die "Unknown build-container argument: $1. Please use --help for help."
;;
esac
shift
done
BUILD_DIR=/tmp/cloud-hypervisor/container/
mkdir -p $BUILD_DIR
cp $CLH_DOCKERFILE $BUILD_DIR
$DOCKER_RUNTIME build \
--target $container_type \
-t $CTR_IMAGE \
-f $BUILD_DIR/Dockerfile \
$BUILD_DIR
}
# Parse main command line args.
#
while [ $# -gt 0 ]; do
case "$1" in
-h|--help) { cmd_help; exit 1; } ;;
-y|--unattended) { OPT_UNATTENDED=true; } ;;
-*)
die "Unknown arg: $1. Please use \`$0 help\` for help."
;;
*)
break
;;
esac
shift
done
# $1 is now a command name. Check if it is a valid command and, if so,
# run it.
#
declare -f "cmd_$1" > /dev/null
ok_or_die "Unknown command: $1. Please use \`$0 help\` for help."
cmd=cmd_$1
shift
ensure_build_dir
ensure_latest_ctr
$cmd "$@"

28
scripts/run_cargo_tests.sh Executable file
View File

@@ -0,0 +1,28 @@
#!/bin/bash
set -e
set -x
source $HOME/.cargo/env
# Install cargo components
time rustup component add clippy
time rustup component add rustfmt
time which cargo-audit || cargo install cargo-audit
# Run cargo builds and checks
time cargo clippy --all-targets --all-features -- -D warnings
time cargo rustc --bin cloud-hypervisor -- -D warnings
time cargo rustc --bin vhost_user_net -- -D warnings
time cargo test
time cargo audit
time cargo clippy --all-targets --no-default-features --features "pci,acpi" -- -D warnings
time cargo rustc --bin cloud-hypervisor --no-default-features --features "pci,acpi" -- -D warnings
time cargo rustc --bin vhost_user_net --no-default-features --features "pci,acpi" -- -D warnings
time cargo clippy --all-targets --no-default-features --features "pci" -- -D warnings
time cargo rustc --bin cloud-hypervisor --no-default-features --features "pci" -- -D warnings
time cargo rustc --bin vhost_user_net --no-default-features --features "pci" -- -D warnings
time cargo clippy --all-targets --no-default-features --features "mmio" -- -D warnings
time cargo rustc --bin cloud-hypervisor --no-default-features --features "mmio" -- -D warnings
time cargo rustc --bin vhost_user_net --no-default-features --features "mmio" -- -D warnings
time cargo fmt -- --check
time cargo build --release

View File

@@ -3,31 +3,35 @@ set -x
source $HOME/.cargo/env
export BUILD_TARGET=${BUILD_TARGET-x86_64-unknown-linux-gnu}
WORKLOADS_DIR="$HOME/workloads"
mkdir -p "$WORKLOADS_DIR"
FW_URL=$(curl --silent https://api.github.com/repos/intel/rust-hypervisor-firmware/releases/latest | grep "browser_download_url" | grep -o 'https://.*[^ "]')
cp scripts/sha1sums $WORKLOADS_DIR
FW_URL=$(curl --silent https://api.github.com/repos/cloud-hypervisor/rust-hypervisor-firmware/releases/latest | grep "browser_download_url" | grep -o 'https://.*[^ "]')
FW="$WORKLOADS_DIR/hypervisor-fw"
if [ ! -f "$FW" ]; then
pushd $WORKLOADS_DIR
wget --quiet $FW_URL
time wget --quiet $FW_URL || exit 1
popd
fi
CLEAR_OS_IMAGE_NAME="clear-cloudguest.img"
CLEAR_OS_IMAGE_NAME="clear-31311-cloudguest.img"
CLEAR_OS_IMAGE_URL="https://cloudhypervisorstorage.blob.core.windows.net/images/$CLEAR_OS_IMAGE_NAME"
CLEAR_OS_IMAGE="$WORKLOADS_DIR/$CLEAR_OS_IMAGE_NAME"
if [ ! -f "$CLEAR_OS_IMAGE" ]; then
pushd $WORKLOADS_DIR
wget --quiet $CLEAR_OS_IMAGE_URL
time wget --quiet $CLEAR_OS_IMAGE_URL || exit 1
popd
fi
CLEAR_OS_RAW_IMAGE_NAME="clear-cloudguest-raw.img"
CLEAR_OS_RAW_IMAGE_NAME="clear-31311-cloudguest-raw.img"
CLEAR_OS_RAW_IMAGE="$WORKLOADS_DIR/$CLEAR_OS_RAW_IMAGE_NAME"
if [ ! -f "$CLEAR_OS_RAW_IMAGE" ]; then
pushd $WORKLOADS_DIR
qemu-img convert -p -f qcow2 -O raw $CLEAR_OS_IMAGE_NAME $CLEAR_OS_RAW_IMAGE_NAME
time qemu-img convert -p -f qcow2 -O raw $CLEAR_OS_IMAGE_NAME $CLEAR_OS_RAW_IMAGE_NAME || exit 1
popd
fi
@@ -36,7 +40,7 @@ BIONIC_OS_IMAGE_URL="https://cloudhypervisorstorage.blob.core.windows.net/images
BIONIC_OS_IMAGE="$WORKLOADS_DIR/$BIONIC_OS_IMAGE_NAME"
if [ ! -f "$BIONIC_OS_IMAGE" ]; then
pushd $WORKLOADS_DIR
wget --quiet $BIONIC_OS_IMAGE_URL
time wget --quiet $BIONIC_OS_IMAGE_URL || exit 1
popd
fi
@@ -44,63 +48,110 @@ BIONIC_OS_RAW_IMAGE_NAME="bionic-server-cloudimg-amd64-raw.img"
BIONIC_OS_RAW_IMAGE="$WORKLOADS_DIR/$BIONIC_OS_RAW_IMAGE_NAME"
if [ ! -f "$BIONIC_OS_RAW_IMAGE" ]; then
pushd $WORKLOADS_DIR
qemu-img convert -p -f qcow2 -O raw $BIONIC_OS_IMAGE_NAME $BIONIC_OS_RAW_IMAGE_NAME
time qemu-img convert -p -f qcow2 -O raw $BIONIC_OS_IMAGE_NAME $BIONIC_OS_RAW_IMAGE_NAME || exit 1
popd
fi
EOAN_OS_IMAGE_NAME="eoan-server-cloudimg-amd64.img"
EOAN_OS_IMAGE_URL="https://cloudhypervisorstorage.blob.core.windows.net/images/$EOAN_OS_IMAGE_NAME"
EOAN_OS_IMAGE="$WORKLOADS_DIR/$EOAN_OS_IMAGE_NAME"
if [ ! -f "$EOAN_OS_IMAGE" ]; then
FOCAL_OS_IMAGE_NAME="focal-server-cloudimg-amd64.img"
FOCAL_OS_IMAGE_URL="https://cloudhypervisorstorage.blob.core.windows.net/images/$FOCAL_OS_IMAGE_NAME"
FOCAL_OS_IMAGE="$WORKLOADS_DIR/$FOCAL_OS_IMAGE_NAME"
if [ ! -f "$FOCAL_OS_IMAGE" ]; then
pushd $WORKLOADS_DIR
wget --quiet $EOAN_OS_IMAGE_URL
time wget --quiet $FOCAL_OS_IMAGE_URL || exit 1
popd
fi
EOAN_OS_RAW_IMAGE_NAME="eoan-server-cloudimg-amd64-raw.img"
EOAN_OS_RAW_IMAGE="$WORKLOADS_DIR/$EOAN_OS_RAW_IMAGE_NAME"
if [ ! -f "$EOAN_OS_RAW_IMAGE" ]; then
FOCAL_OS_RAW_IMAGE_NAME="focal-server-cloudimg-amd64-raw.img"
FOCAL_OS_RAW_IMAGE="$WORKLOADS_DIR/$FOCAL_OS_RAW_IMAGE_NAME"
if [ ! -f "$FOCAL_OS_RAW_IMAGE" ]; then
pushd $WORKLOADS_DIR
qemu-img convert -p -f qcow2 -O raw $EOAN_OS_IMAGE_NAME $EOAN_OS_RAW_IMAGE_NAME
time qemu-img convert -p -f qcow2 -O raw $FOCAL_OS_IMAGE_NAME $FOCAL_OS_RAW_IMAGE_NAME || exit 1
popd
fi
ALPINE_MINIROOTFS_URL="http://dl-cdn.alpinelinux.org/alpine/v3.11/releases/x86_64/alpine-minirootfs-3.11.3-x86_64.tar.gz"
ALPINE_MINIROOTFS_TARBALL="$WORKLOADS_DIR/alpine-minirootfs-x86_64.tar.gz"
if [ ! -f "$ALPINE_MINIROOTFS_TARBALL" ]; then
pushd $WORKLOADS_DIR
time wget --quiet $ALPINE_MINIROOTFS_URL -O $ALPINE_MINIROOTFS_TARBALL || exit 1
popd
fi
ALPINE_INITRAMFS_IMAGE="$WORKLOADS_DIR/alpine_initramfs.img"
if [ ! -f "$ALPINE_INITRAMFS_IMAGE" ]; then
pushd $WORKLOADS_DIR
mkdir alpine-minirootfs
tar xf "$ALPINE_MINIROOTFS_TARBALL" -C alpine-minirootfs
cat > alpine-minirootfs/init <<-EOF
#! /bin/sh
mount -t devtmpfs dev /dev
echo \$TEST_STRING > /dev/console
poweroff -f
EOF
chmod +x alpine-minirootfs/init
cd alpine-minirootfs
find . -print0 |
cpio --null --create --verbose --owner root:root --format=newc > "$ALPINE_INITRAMFS_IMAGE"
popd
fi
pushd $WORKLOADS_DIR
sha1sum sha1sums --check
if [ $? -ne 0 ]; then
echo "sha1sum validation of images failed, remove invalid images to fix the issue."
exit 1
fi
popd
# Build custom kernel based on virtio-pmem and virtio-fs upstream patches
VMLINUX_IMAGE="$WORKLOADS_DIR/vmlinux"
VMLINUX_PVH_IMAGE="$WORKLOADS_DIR/vmlinux.pvh"
BZIMAGE_IMAGE="$WORKLOADS_DIR/bzImage"
LINUX_CUSTOM_DIR="linux-custom"
LINUX_CUSTOM_DIR="$WORKLOADS_DIR/linux-custom"
if [ ! -f "$VMLINUX_IMAGE" ]; then
if [ ! -f "$VMLINUX_IMAGE" ] || [ ! -f "$VMLINUX_PVH_IMAGE" ]; then
SRCDIR=$PWD
pushd $WORKLOADS_DIR
git clone --depth 1 "https://github.com/sboeuf/linux.git" -b "virtio-fs-virtio-iommu" $LINUX_CUSTOM_DIR
pushd $LINUX_CUSTOM_DIR
cp $SRCDIR/resources/linux-virtio-fs-virtio-iommu-config .config
make bzImage -j `nproc`
cp vmlinux $VMLINUX_IMAGE
cp arch/x86/boot/bzImage $BZIMAGE_IMAGE
popd
rm -rf $LINUX_CUSTOM_DIR
time git clone --depth 1 "https://github.com/cloud-hypervisor/linux.git" -b "virtio-fs-virtio-iommu-virtio-mem-5.6-rc4" $LINUX_CUSTOM_DIR
cp $SRCDIR/resources/linux-config $LINUX_CUSTOM_DIR/.config
popd
fi
if [ ! -f "$VMLINUX_IMAGE" ]; then
pushd $LINUX_CUSTOM_DIR
scripts/config --disable "CONFIG_PVH"
time make bzImage -j `nproc`
cp vmlinux $VMLINUX_IMAGE || exit 1
cp arch/x86/boot/bzImage $BZIMAGE_IMAGE || exit 1
popd
fi
if [ ! -f "$VMLINUX_PVH_IMAGE" ]; then
pushd $LINUX_CUSTOM_DIR
scripts/config --enable "CONFIG_PVH"
time make bzImage -j `nproc`
cp vmlinux $VMLINUX_PVH_IMAGE || exit 1
popd
fi
if [ -d "$LINUX_CUSTOM_DIR" ]; then
rm -rf $LINUX_CUSTOM_DIR
fi
VIRTIOFSD="$WORKLOADS_DIR/virtiofsd"
VUBD="$WORKLOADS_DIR/vubd"
QEMU_DIR="qemu_build"
if [ ! -f "$VIRTIOFSD" ] || [ ! -f "$VUBD" ]; then
if [ ! -f "$VIRTIOFSD" ]; then
pushd $WORKLOADS_DIR
git clone --depth 1 "https://github.com/sboeuf/qemu.git" -b "virtio-fs" $QEMU_DIR
pushd $QEMU_DIR
./configure --prefix=$PWD --target-list=x86_64-softmmu
make virtiofsd vhost-user-blk -j `nproc`
cp virtiofsd $VIRTIOFSD
cp vhost-user-blk $VUBD
time ./configure --prefix=$PWD --target-list=x86_64-softmmu
time make virtiofsd -j `nproc`
cp virtiofsd $VIRTIOFSD || exit 1
popd
rm -rf $QEMU_DIR
sudo setcap cap_dac_override,cap_sys_admin+epi "virtiofsd"
sudo setcap cap_dac_override,cap_sys_admin+epi "virtiofsd" || exit 1
popd
fi
@@ -112,7 +163,7 @@ if [ ! -f "$BLK_IMAGE" ]; then
mkfs.ext4 -j $BLK_IMAGE
mkdir $MNT_DIR
sudo mount -t ext4 $BLK_IMAGE $MNT_DIR
sudo bash -c "echo bar > $MNT_DIR/foo"
sudo bash -c "echo bar > $MNT_DIR/foo" || exit 1
sudo umount $BLK_IMAGE
rm -r $MNT_DIR
popd
@@ -122,16 +173,15 @@ SHARED_DIR="$WORKLOADS_DIR/shared_dir"
if [ ! -d "$SHARED_DIR" ]; then
mkdir -p $SHARED_DIR
echo "foo" > "$SHARED_DIR/file1"
echo "bar" > "$SHARED_DIR/file3"
echo "bar" > "$SHARED_DIR/file3" || exit 1
fi
VFIO_DIR="$WORKLOADS_DIR/vfio"
if [ ! -d "$VFIO_DIR" ]; then
mkdir -p $VFIO_DIR
cp $CLEAR_OS_IMAGE $VFIO_DIR
cp $FW $VFIO_DIR
cp $VMLINUX_IMAGE $VFIO_DIR
fi
rm -rf $VFIO_DIR
mkdir -p $VFIO_DIR
cp $CLEAR_OS_IMAGE $VFIO_DIR
cp $FW $VFIO_DIR
cp $VMLINUX_IMAGE $VFIO_DIR || exit 1
# VFIO test network setup.
# We reserve a different IP class for it: 172.17.0.0/24.
@@ -147,28 +197,60 @@ sudo ip tuntap add vfio-tap1 mode tap
sudo ip link set vfio-tap1 master vfio-br0
sudo ip link set vfio-tap1 up
cargo build
sudo setcap cap_net_admin+ep target/debug/cloud-hypervisor
sudo setcap cap_net_admin+ep target/debug/vhost_user_net
sudo ip tuntap add vfio-tap2 mode tap
sudo ip link set vfio-tap2 master vfio-br0
sudo ip link set vfio-tap2 up
sudo ip tuntap add vfio-tap3 mode tap
sudo ip link set vfio-tap3 master vfio-br0
sudo ip link set vfio-tap3 up
# Create tap interface without multipe queues support for vhost_user_net test.
sudo ip tuntap add name vunet-tap0 mode tap
# Create tap interface with multipe queues support for vhost_user_net test.
sudo ip tuntap add name vunet-tap1 mode tap multi_queue
cargo build --release --target $BUILD_TARGET
sudo setcap cap_net_admin+ep target/$BUILD_TARGET/release/cloud-hypervisor
sudo setcap cap_net_admin+ep target/$BUILD_TARGET/release/vhost_user_net
# We always copy a fresh version of our binary for our L2 guest.
cp target/debug/cloud-hypervisor $VFIO_DIR
cp target/$BUILD_TARGET/release/cloud-hypervisor $VFIO_DIR
cp target/$BUILD_TARGET/release/ch-remote $VFIO_DIR
# Enable KSM with some reasonable parameters so that it won't take too long
# for the memory to be merged between two processes.
sudo bash -c "echo 1000000 > /sys/kernel/mm/ksm/pages_to_scan"
sudo bash -c "echo 10 > /sys/kernel/mm/ksm/sleep_millisecs"
sudo bash -c "echo 1 > /sys/kernel/mm/ksm/run"
# Ensure test binary has the same caps as the cloud-hypervisor one
time cargo test --no-run --features "integration_tests" -- --nocapture || exit 1
ls target/debug/deps/cloud_hypervisor-* | xargs -n 1 sudo setcap cap_net_admin+ep
# test_vfio relies on hugepages
echo 4096 | sudo tee /proc/sys/vm/nr_hugepages
sudo chmod a+rwX /dev/hugepages
sudo adduser $USER kvm
newgrp kvm << EOF
export RUST_BACKTRACE=1
cargo test --features "integration_tests" -- --nocapture
time cargo test --features "integration_tests" "$@" -- --nocapture
EOF
RES=$?
if [ $RES -eq 0 ]; then
# virtio-mmio based testing
cargo build --no-default-features --features "mmio"
sudo setcap cap_net_admin+ep target/debug/cloud-hypervisor
cargo build --release --target $BUILD_TARGET --no-default-features --features "mmio"
sudo setcap cap_net_admin+ep target/$BUILD_TARGET/release/cloud-hypervisor
# Ensure test binary has the same caps as the cloud-hypervisor one
time cargo test --no-run --features "integration_tests,mmio" -- --nocapture || exit 1
ls target/debug/deps/cloud_hypervisor-* | xargs -n 1 sudo setcap cap_net_admin+ep
newgrp kvm << EOF
export RUST_BACKTRACE=1
cargo test --features "integration_tests,mmio" -- --nocapture
time cargo test --features "integration_tests,mmio" "$@" -- --nocapture
EOF
RES=$?
@@ -178,5 +260,11 @@ fi
sudo ip link del vfio-br0
sudo ip link del vfio-tap0
sudo ip link del vfio-tap1
sudo ip link del vfio-tap2
sudo ip link del vfio-tap3
# Tear vhost_user_net test network down
sudo ip link del vunet-tap0
sudo ip link del vunet-tap1
exit $RES

5
scripts/run_openapi_tests.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/bin/bash
set -e
set -x
sudo docker run --rm -v ${PWD}:/local openapitools/openapi-generator-cli validate -i /local/vmm/src/api/openapi/cloud-hypervisor.yaml

View File

@@ -2,23 +2,15 @@
source $HOME/.cargo/env
# More effective than just cargo test --all as it captures crates within crates
for f in $(find . -name Cargo.toml -printf '%h\n' | sort -u); do
pushd $f > /dev/null;
cargo test --no-run || exit 1;
popd > /dev/null;
done
BUILD_TARGET=${BUILD_TARGET-x86_64-unknown-linux-gnu}
pushd target/debug
cargo test --target $BUILD_TARGET --workspace --no-run
pushd target/$BUILD_TARGET/debug
ls | grep net_util | grep -v "\.d" | xargs -n 1 sudo setcap cap_net_admin,cap_net_raw+ep
popd
sudo adduser $USER kvm
newgrp kvm << EOF || exit 1
for f in \$(find . -name Cargo.toml -printf '%h\n' | sort -u); do
pushd \$f > /dev/null;
export RUST_BACKTRACE=1
cargo test || exit 1;
popd > /dev/null;
done
cargo test --target $BUILD_TARGET --workspace "$@" || exit 1;
EOF

7
scripts/sha1sums Normal file
View File

@@ -0,0 +1,7 @@
cf7cfa783082fc4d6b4d1c0a53e4402648c14b82 clear-31311-cloudguest.img
142a410546b592ff9536b46bb410faf8ac11edee clear-31311-cloudguest-raw.img
27f3b17962ace69b51f0ddc2012095e3109e6ed8 bionic-server-cloudimg-amd64.img
8db9cc58b01452ce2d06c313177e6e74d8582d93 bionic-server-cloudimg-amd64-raw.img
d4a44acc6014d5f83dea1c625c43d677a95fa75f alpine-minirootfs-x86_64.tar.gz
3cab64475048383e70a38550734e98961cfe0fd6 focal-server-cloudimg-amd64-raw.img
c74a95665b189f93cb16a2c1770820c6a6a43fb0 focal-server-cloudimg-amd64.img

515
src/bin/ch-remote.rs Normal file
View File

@@ -0,0 +1,515 @@
// Copyright © 2020 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
#[macro_use(crate_authors)]
extern crate clap;
extern crate serde_json;
extern crate vmm;
use clap::{App, AppSettings, Arg, ArgMatches, SubCommand};
use std::io::{Read, Write};
use std::os::unix::net::UnixStream;
use std::process;
#[derive(Debug)]
enum Error {
Socket(std::io::Error),
StatusCodeParsing(std::num::ParseIntError),
MissingProtocol,
ContentLengthParsing(std::num::ParseIntError),
ServerResponse(StatusCode),
InvalidCPUCount(std::num::ParseIntError),
InvalidMemorySize(std::num::ParseIntError),
AddDeviceConfig(vmm::config::Error),
AddDiskConfig(vmm::config::Error),
AddFsConfig(vmm::config::Error),
AddPmemConfig(vmm::config::Error),
AddNetConfig(vmm::config::Error),
AddVsockConfig(vmm::config::Error),
Restore(vmm::config::Error),
}
#[derive(Clone, Copy, Debug)]
pub enum StatusCode {
Continue,
OK,
NoContent,
BadRequest,
NotFound,
InternalServerError,
NotImplemented,
Unknown,
}
impl StatusCode {
fn from_raw(code: usize) -> StatusCode {
match code {
100 => StatusCode::Continue,
200 => StatusCode::OK,
204 => StatusCode::NoContent,
400 => StatusCode::BadRequest,
404 => StatusCode::NotFound,
500 => StatusCode::InternalServerError,
501 => StatusCode::NotImplemented,
_ => StatusCode::Unknown,
}
}
fn parse(code: &str) -> Result<StatusCode, Error> {
Ok(StatusCode::from_raw(
code.trim().parse().map_err(Error::StatusCodeParsing)?,
))
}
fn check(self) -> Result<(), Error> {
match self {
StatusCode::OK | StatusCode::Continue | StatusCode::NoContent => Ok(()),
_ => Err(Error::ServerResponse(self)),
}
}
}
fn get_header<'a>(res: &'a str, header: &'a str) -> Option<&'a str> {
let header_str = format!("{}: ", header);
if let Some(o) = res.find(&header_str) {
Some(&res[o + header_str.len()..o + res[o..].find('\r').unwrap()])
} else {
None
}
}
fn get_status_code(res: &str) -> Result<StatusCode, Error> {
if let Some(o) = res.find("HTTP/1.1") {
Ok(StatusCode::parse(
&res[o + "HTTP/1.1 ".len()..res[o..].find('\r').unwrap()],
)?)
} else {
Err(Error::MissingProtocol)
}
}
fn parse_http_response(socket: &mut UnixStream) -> Result<Option<String>, Error> {
let mut res = String::new();
let mut body_offset = None;
let mut content_length: Option<usize> = None;
loop {
let mut bytes = vec![0; 256];
let count = socket.read(&mut bytes).map_err(Error::Socket)?;
res.push_str(std::str::from_utf8(&bytes[0..count]).unwrap());
// End of headers
if let Some(o) = res.find("\r\n\r\n") {
body_offset = Some(o + "\r\n\r\n".len());
// With all headers available we can see if there is any body
content_length = if let Some(length) = get_header(&res, "Content-Length") {
Some(length.trim().parse().map_err(Error::ContentLengthParsing)?)
} else {
None
};
if content_length.is_none() {
break;
}
}
if let Some(body_offset) = body_offset {
if let Some(content_length) = content_length {
if res.len() >= content_length + body_offset {
break;
}
}
}
}
get_status_code(&res)?.check()?;
Ok(content_length.and(Some(String::from(&res[body_offset.unwrap()..]))))
}
fn simple_api_command(
socket: &mut UnixStream,
method: &str,
c: &str,
request_body: Option<&str>,
) -> Result<(), Error> {
socket
.write_all(
format!(
"{} /api/v1/vm.{} HTTP/1.1\r\nHost: localhost\r\nAccept: */*\r\n",
method, c
)
.as_bytes(),
)
.map_err(Error::Socket)?;
if let Some(request_body) = request_body {
socket
.write_all(format!("Content-Length: {}\r\n", request_body.len()).as_bytes())
.map_err(Error::Socket)?;
}
socket.write_all(b"\r\n").map_err(Error::Socket)?;
if let Some(request_body) = request_body {
socket
.write_all(request_body.as_bytes())
.map_err(Error::Socket)?;
}
socket.flush().map_err(Error::Socket)?;
if let Some(body) = parse_http_response(socket)? {
println!("{}", body);
}
Ok(())
}
fn resize_api_command(
socket: &mut UnixStream,
cpus: Option<&str>,
memory: Option<&str>,
) -> Result<(), Error> {
let desired_vcpus: Option<u8> = if let Some(cpus) = cpus {
Some(cpus.parse().map_err(Error::InvalidCPUCount)?)
} else {
None
};
let desired_ram: Option<u64> = if let Some(memory) = memory {
Some(memory.parse().map_err(Error::InvalidMemorySize)?)
} else {
None
};
let resize = vmm::api::VmResizeData {
desired_vcpus,
desired_ram,
};
simple_api_command(
socket,
"PUT",
"resize",
Some(&serde_json::to_string(&resize).unwrap()),
)
}
fn add_device_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let device_config = vmm::config::DeviceConfig::parse(config).map_err(Error::AddDeviceConfig)?;
simple_api_command(
socket,
"PUT",
"add-device",
Some(&serde_json::to_string(&device_config).unwrap()),
)
}
fn remove_device_api_command(socket: &mut UnixStream, id: &str) -> Result<(), Error> {
let remove_device_data = vmm::api::VmRemoveDeviceData { id: id.to_owned() };
simple_api_command(
socket,
"PUT",
"remove-device",
Some(&serde_json::to_string(&remove_device_data).unwrap()),
)
}
fn add_disk_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let disk_config = vmm::config::DiskConfig::parse(config).map_err(Error::AddDiskConfig)?;
simple_api_command(
socket,
"PUT",
"add-disk",
Some(&serde_json::to_string(&disk_config).unwrap()),
)
}
fn add_fs_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let fs_config = vmm::config::FsConfig::parse(config).map_err(Error::AddFsConfig)?;
simple_api_command(
socket,
"PUT",
"add-fs",
Some(&serde_json::to_string(&fs_config).unwrap()),
)
}
fn add_pmem_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let pmem_config = vmm::config::PmemConfig::parse(config).map_err(Error::AddPmemConfig)?;
simple_api_command(
socket,
"PUT",
"add-pmem",
Some(&serde_json::to_string(&pmem_config).unwrap()),
)
}
fn add_net_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let net_config = vmm::config::NetConfig::parse(config).map_err(Error::AddNetConfig)?;
simple_api_command(
socket,
"PUT",
"add-net",
Some(&serde_json::to_string(&net_config).unwrap()),
)
}
fn add_vsock_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let vsock_config = vmm::config::VsockConfig::parse(config).map_err(Error::AddVsockConfig)?;
simple_api_command(
socket,
"PUT",
"add-vsock",
Some(&serde_json::to_string(&vsock_config).unwrap()),
)
}
fn snapshot_api_command(socket: &mut UnixStream, url: &str) -> Result<(), Error> {
let snapshot_config = vmm::api::VmSnapshotConfig {
destination_url: String::from(url),
};
simple_api_command(
socket,
"PUT",
"snapshot",
Some(&serde_json::to_string(&snapshot_config).unwrap()),
)
}
fn restore_api_command(socket: &mut UnixStream, config: &str) -> Result<(), Error> {
let restore_config = vmm::config::RestoreConfig::parse(config).map_err(Error::Restore)?;
simple_api_command(
socket,
"PUT",
"restore",
Some(&serde_json::to_string(&restore_config).unwrap()),
)
}
fn do_command(matches: &ArgMatches) -> Result<(), Error> {
let mut socket =
UnixStream::connect(matches.value_of("api-socket").unwrap()).map_err(Error::Socket)?;
match matches.subcommand_name() {
Some("info") => simple_api_command(&mut socket, "GET", "info", None),
Some("resize") => resize_api_command(
&mut socket,
matches
.subcommand_matches("resize")
.unwrap()
.value_of("cpus"),
matches
.subcommand_matches("resize")
.unwrap()
.value_of("memory"),
),
Some("add-device") => add_device_api_command(
&mut socket,
matches
.subcommand_matches("add-device")
.unwrap()
.value_of("device_config")
.unwrap(),
),
Some("remove-device") => remove_device_api_command(
&mut socket,
matches
.subcommand_matches("remove-device")
.unwrap()
.value_of("id")
.unwrap(),
),
Some("add-disk") => add_disk_api_command(
&mut socket,
matches
.subcommand_matches("add-disk")
.unwrap()
.value_of("disk_config")
.unwrap(),
),
Some("add-fs") => add_fs_api_command(
&mut socket,
matches
.subcommand_matches("add-fs")
.unwrap()
.value_of("fs_config")
.unwrap(),
),
Some("add-pmem") => add_pmem_api_command(
&mut socket,
matches
.subcommand_matches("add-pmem")
.unwrap()
.value_of("pmem_config")
.unwrap(),
),
Some("add-net") => add_net_api_command(
&mut socket,
matches
.subcommand_matches("add-net")
.unwrap()
.value_of("net_config")
.unwrap(),
),
Some("add-vsock") => add_vsock_api_command(
&mut socket,
matches
.subcommand_matches("add-vsock")
.unwrap()
.value_of("vsock_config")
.unwrap(),
),
Some("snapshot") => snapshot_api_command(
&mut socket,
matches
.subcommand_matches("snapshot")
.unwrap()
.value_of("snapshot_config")
.unwrap(),
),
Some("restore") => restore_api_command(
&mut socket,
matches
.subcommand_matches("restore")
.unwrap()
.value_of("restore_config")
.unwrap(),
),
Some(c) => simple_api_command(&mut socket, "PUT", c, None),
None => unreachable!(),
}
}
fn main() {
let app = App::new("ch-remote")
.author(crate_authors!())
.setting(AppSettings::SubcommandRequired)
.about("Remotely control a cloud-hypervisor VMM.")
.arg(
Arg::with_name("api-socket")
.long("api-socket")
.help("HTTP API socket path (UNIX domain socket).")
.takes_value(true)
.min_values(1)
.required(true),
)
.subcommand(
SubCommand::with_name("add-device")
.about("Add VFIO device")
.arg(
Arg::with_name("device_config")
.index(1)
.help(vmm::config::DeviceConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("add-disk")
.about("Add block device")
.arg(
Arg::with_name("disk_config")
.index(1)
.help(vmm::config::DiskConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("add-fs")
.about("Add virtio-fs backed fs device")
.arg(
Arg::with_name("fs_config")
.index(1)
.help(vmm::config::FsConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("add-pmem")
.about("Add persistent memory device")
.arg(
Arg::with_name("pmem_config")
.index(1)
.help(vmm::config::PmemConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("add-net")
.about("Add network device")
.arg(
Arg::with_name("net_config")
.index(1)
.help(vmm::config::NetConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("add-vsock")
.about("Add vsock device")
.arg(
Arg::with_name("vsock_config")
.index(1)
.help(vmm::config::VsockConfig::SYNTAX),
),
)
.subcommand(
SubCommand::with_name("remove-device")
.about("Remove VFIO device")
.arg(Arg::with_name("id").index(1).help("<device_id>")),
)
.subcommand(SubCommand::with_name("info").about("Info on the VM"))
.subcommand(SubCommand::with_name("pause").about("Pause the VM"))
.subcommand(SubCommand::with_name("reboot").about("Reboot the VM"))
.subcommand(
SubCommand::with_name("resize")
.about("Resize the VM")
.arg(
Arg::with_name("cpus")
.long("cpus")
.help("New vCPUs count")
.takes_value(true)
.number_of_values(1),
)
.arg(
Arg::with_name("memory")
.long("memory")
.help("New memory size (in MiB)")
.takes_value(true)
.number_of_values(1),
),
)
.subcommand(SubCommand::with_name("resume").about("Resume the VM"))
.subcommand(SubCommand::with_name("shutdown").about("Shutdown the VM"))
.subcommand(
SubCommand::with_name("snapshot")
.about("Create a snapshot from VM")
.arg(
Arg::with_name("snapshot_config")
.index(1)
.help("<destination_url>"),
),
)
.subcommand(
SubCommand::with_name("restore")
.about("Restore VM from a snapshot")
.arg(
Arg::with_name("restore_config")
.index(1)
.help(vmm::config::RestoreConfig::SYNTAX),
),
);
let matches = app.get_matches();
if let Err(e) = do_command(&matches) {
eprintln!("Error running command: {:?}", e);
process::exit(1)
};
}

38
src/bin/vhost_user_blk.rs Normal file
View File

@@ -0,0 +1,38 @@
// Copyright 2019 Red Hat, Inc. All Rights Reserved.
//
// Portions Copyright 2019 Intel Corporation. All Rights Reserved.
//
// Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
//
// SPDX-License-Identifier: (Apache-2.0 AND BSD-3-Clause)
#[macro_use(crate_version, crate_authors)]
extern crate clap;
extern crate vhost_user_block;
use clap::{App, Arg};
use vhost_user_block::start_block_backend;
fn main() {
let cmd_arguments = App::new("vhost-user-blk backend")
.version(crate_version!())
.author(crate_authors!())
.about("Launch a vhost-user-blk backend.")
.arg(
Arg::with_name("block-backend")
.long("block-backend")
.help(
"vhost-user-block backend parameters \
\"path=<image_path>,socket=<socket_path>,num_queues=<number_of_queues>,\
readonly=true|false,direct=true|false,poll_queue=true|false\"",
)
.takes_value(true)
.min_values(1),
)
.get_matches();
let backend_command = cmd_arguments.value_of("block-backend").unwrap();
start_block_backend(backend_command);
}

369
src/bin/vhost_user_fs.rs Normal file
View File

@@ -0,0 +1,369 @@
// Copyright 2019 Intel Corporation. All Rights Reserved.
//
// SPDX-License-Identifier: (Apache-2.0 AND BSD-3-Clause)
#[macro_use(crate_version, crate_authors)]
extern crate clap;
extern crate log;
extern crate vhost_rs;
extern crate vhost_user_backend;
extern crate vm_virtio;
use clap::{App, Arg};
use epoll;
use futures::executor::{ThreadPool, ThreadPoolBuilder};
use libc::EFD_NONBLOCK;
use log::*;
use std::num::Wrapping;
use std::sync::{Arc, Mutex, RwLock};
use std::{convert, error, fmt, io, process};
use vhost_rs::vhost_user::message::*;
use vhost_rs::vhost_user::SlaveFsCacheReq;
use vhost_user_backend::{VhostUserBackend, VhostUserDaemon, Vring};
use vhost_user_fs::descriptor_utils::Error as VufDescriptorError;
use vhost_user_fs::descriptor_utils::{Reader, Writer};
use vhost_user_fs::filesystem::FileSystem;
use vhost_user_fs::passthrough::{self, PassthroughFs};
use vhost_user_fs::server::Server;
use vhost_user_fs::Error as VhostUserFsError;
use virtio_bindings::bindings::virtio_net::*;
use virtio_bindings::bindings::virtio_ring::{
VIRTIO_RING_F_EVENT_IDX, VIRTIO_RING_F_INDIRECT_DESC,
};
use vm_memory::{GuestAddressSpace, GuestMemoryAtomic, GuestMemoryMmap};
use vm_virtio::queue::DescriptorChain;
use vmm_sys_util::eventfd::EventFd;
const QUEUE_SIZE: usize = 1024;
const NUM_QUEUES: usize = 2;
const THREAD_POOL_SIZE: usize = 64;
// The guest queued an available buffer for the high priority queue.
const HIPRIO_QUEUE_EVENT: u16 = 0;
// The guest queued an available buffer for the request queue.
const REQ_QUEUE_EVENT: u16 = 1;
// The device has been dropped.
const KILL_EVENT: u16 = 2;
type Result<T> = std::result::Result<T, Error>;
type VhostUserBackendResult<T> = std::result::Result<T, std::io::Error>;
#[derive(Debug)]
enum Error {
/// Failed to create kill eventfd.
CreateKillEventFd(io::Error),
/// Failed to create thread pool.
CreateThreadPool(io::Error),
/// Failed to handle event other than input event.
HandleEventNotEpollIn,
/// Failed to handle unknown event.
HandleEventUnknownEvent,
/// No memory configured.
NoMemoryConfigured,
/// Processing queue failed.
ProcessQueue(VhostUserFsError),
/// Creating a queue reader failed.
QueueReader(VufDescriptorError),
/// Creating a queue writer failed.
QueueWriter(VufDescriptorError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "vhost_user_fs_error: {:?}", self)
}
}
impl error::Error for Error {}
impl convert::From<Error> for io::Error {
fn from(e: Error) -> Self {
io::Error::new(io::ErrorKind::Other, e)
}
}
struct VhostUserFsThread<F: FileSystem + Send + Sync + 'static> {
mem: Option<GuestMemoryAtomic<GuestMemoryMmap>>,
kill_evt: EventFd,
server: Arc<Server<F>>,
// handle request from slave to master
vu_req: Option<SlaveFsCacheReq>,
event_idx: bool,
pool: ThreadPool,
}
impl<F: FileSystem + Send + Sync + 'static> Clone for VhostUserFsThread<F> {
fn clone(&self) -> Self {
VhostUserFsThread {
mem: self.mem.clone(),
kill_evt: self.kill_evt.try_clone().unwrap(),
server: self.server.clone(),
vu_req: self.vu_req.clone(),
event_idx: self.event_idx,
pool: self.pool.clone(),
}
}
}
impl<F: FileSystem + Send + Sync + 'static> VhostUserFsThread<F> {
fn new(fs: F, thread_pool_size: usize) -> Result<Self> {
Ok(VhostUserFsThread {
mem: None,
kill_evt: EventFd::new(EFD_NONBLOCK).map_err(Error::CreateKillEventFd)?,
server: Arc::new(Server::new(fs)),
vu_req: None,
event_idx: false,
pool: ThreadPoolBuilder::new()
.pool_size(thread_pool_size)
.create()
.map_err(Error::CreateThreadPool)?,
})
}
fn process_queue(&mut self, vring_lock: Arc<RwLock<Vring>>) -> Result<bool> {
let mut used_any = false;
let (atomic_mem, mem) = match &self.mem {
Some(m) => (m, m.memory()),
None => return Err(Error::NoMemoryConfigured),
};
let mut vring = vring_lock.write().unwrap();
while let Some(avail_desc) = vring.mut_queue().iter(&mem).next() {
used_any = true;
// Prepare a set of objects that can be moved to the worker thread.
let desc_head = avail_desc.get_head();
let atomic_mem = atomic_mem.clone();
let server = self.server.clone();
let mut vu_req = self.vu_req.clone();
let event_idx = self.event_idx;
let vring_lock = vring_lock.clone();
self.pool.spawn_ok(async move {
let mem = atomic_mem.memory();
let desc = DescriptorChain::new_from_head(&mem, desc_head).unwrap();
let head_index = desc.index;
let reader = Reader::new(&mem, desc.clone())
.map_err(Error::QueueReader)
.unwrap();
let writer = Writer::new(&mem, desc.clone())
.map_err(Error::QueueWriter)
.unwrap();
server
.handle_message(reader, writer, vu_req.as_mut())
.map_err(Error::ProcessQueue)
.unwrap();
let mut vring = vring_lock.write().unwrap();
if event_idx {
if let Some(used_idx) = vring.mut_queue().add_used(&mem, head_index, 0) {
if vring.needs_notification(&mem, Wrapping(used_idx)) {
vring.signal_used_queue().unwrap();
}
}
} else {
vring.mut_queue().add_used(&mem, head_index, 0);
vring.signal_used_queue().unwrap();
}
});
}
Ok(used_any)
}
}
struct VhostUserFsBackend<F: FileSystem + Send + Sync + 'static> {
thread: Mutex<VhostUserFsThread<F>>,
}
impl<F: FileSystem + Send + Sync + 'static> VhostUserFsBackend<F> {
fn new(fs: F, thread_pool_size: usize) -> Result<Self> {
let thread = Mutex::new(VhostUserFsThread::new(fs, thread_pool_size)?);
Ok(VhostUserFsBackend { thread })
}
}
impl<F: FileSystem + Send + Sync + 'static> VhostUserBackend for VhostUserFsBackend<F> {
fn num_queues(&self) -> usize {
NUM_QUEUES
}
fn max_queue_size(&self) -> usize {
QUEUE_SIZE
}
fn features(&self) -> u64 {
1 << VIRTIO_F_VERSION_1
| 1 << VIRTIO_RING_F_INDIRECT_DESC
| 1 << VIRTIO_RING_F_EVENT_IDX
| VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits()
}
fn protocol_features(&self) -> VhostUserProtocolFeatures {
VhostUserProtocolFeatures::MQ | VhostUserProtocolFeatures::SLAVE_REQ
}
fn set_event_idx(&mut self, enabled: bool) {
self.thread.lock().unwrap().event_idx = enabled;
}
fn update_memory(&mut self, mem: GuestMemoryMmap) -> VhostUserBackendResult<()> {
self.thread.lock().unwrap().mem = Some(GuestMemoryAtomic::new(mem));
Ok(())
}
fn handle_event(
&self,
device_event: u16,
evset: epoll::Events,
vrings: &[Arc<RwLock<Vring>>],
_thread_id: usize,
) -> VhostUserBackendResult<bool> {
if evset != epoll::Events::EPOLLIN {
return Err(Error::HandleEventNotEpollIn.into());
}
let mut thread = self.thread.lock().unwrap();
let mem = match &thread.mem {
Some(m) => m.memory(),
None => return Err(Error::NoMemoryConfigured.into()),
};
let vring_lock = match device_event {
HIPRIO_QUEUE_EVENT => {
debug!("HIPRIO_QUEUE_EVENT");
vrings[0].clone()
}
REQ_QUEUE_EVENT => {
debug!("QUEUE_EVENT");
vrings[1].clone()
}
_ => return Err(Error::HandleEventUnknownEvent.into()),
};
if thread.event_idx {
// vm-virtio's Queue implementation only checks avail_index
// once, so to properly support EVENT_IDX we need to keep
// calling process_queue() until it stops finding new
// requests on the queue.
loop {
{
let mut vring = vring_lock.write().unwrap();
vring.mut_queue().update_avail_event(&mem);
}
if !thread.process_queue(vring_lock.clone())? {
break;
}
}
} else {
// Without EVENT_IDX, a single call is enough.
thread.process_queue(vring_lock)?;
}
Ok(false)
}
fn exit_event(&self, _thread_index: usize) -> Option<(EventFd, Option<u16>)> {
Some((
self.thread.lock().unwrap().kill_evt.try_clone().unwrap(),
Some(KILL_EVENT),
))
}
fn set_slave_req_fd(&mut self, vu_req: SlaveFsCacheReq) {
self.thread.lock().unwrap().vu_req = Some(vu_req);
}
}
fn main() {
let cmd_arguments = App::new("vhost-user-fs backend")
.version(crate_version!())
.author(crate_authors!())
.about("Launch a vhost-user-fs backend.")
.arg(
Arg::with_name("shared-dir")
.long("shared-dir")
.help("Shared directory path")
.takes_value(true)
.min_values(1),
)
.arg(
Arg::with_name("sock")
.long("sock")
.help("vhost-user socket path")
.takes_value(true)
.min_values(1),
)
.arg(
Arg::with_name("thread-pool-size")
.long("thread-pool-size")
.help("thread pool size (default 64)")
.takes_value(true)
.min_values(1),
)
.arg(
Arg::with_name("disable-xattr")
.long("disable-xattr")
.help("Disable support for extended attributes"),
)
.get_matches();
// Retrieve arguments
let shared_dir = cmd_arguments
.value_of("shared-dir")
.expect("Failed to retrieve shared directory path");
let sock = cmd_arguments
.value_of("sock")
.expect("Failed to retrieve vhost-user socket path");
let thread_pool_size: usize = match cmd_arguments.value_of("thread-pool-size") {
Some(size) => size.parse().expect("Invalid argument for thread-pool-size"),
None => THREAD_POOL_SIZE,
};
let xattr: bool = !cmd_arguments.is_present("disable-xattr");
// Convert into appropriate types
let sock = String::from(sock);
let fs_cfg = passthrough::Config {
root_dir: shared_dir.to_string(),
xattr,
..Default::default()
};
let fs = PassthroughFs::new(fs_cfg).unwrap();
let fs_backend = Arc::new(RwLock::new(
VhostUserFsBackend::new(fs, thread_pool_size).unwrap(),
));
let mut daemon = VhostUserDaemon::new(
String::from("vhost-user-fs-backend"),
sock,
fs_backend.clone(),
)
.unwrap();
if let Err(e) = daemon.start() {
error!("Failed to start daemon: {:?}", e);
process::exit(1);
}
if let Err(e) = daemon.wait() {
error!("Waiting for daemon failed: {:?}", e);
}
let kill_evt = fs_backend
.read()
.unwrap()
.thread
.lock()
.unwrap()
.kill_evt
.try_clone()
.unwrap();
if let Err(e) = kill_evt.write(1) {
error!("Error shutting down worker thread: {:?}", e)
}
}

View File

@@ -8,532 +8,10 @@
#[macro_use(crate_version, crate_authors)]
extern crate clap;
extern crate log;
extern crate net_util;
extern crate vhost_rs;
extern crate vhost_user_backend;
extern crate vm_virtio;
extern crate vhost_user_net;
use clap::{App, Arg};
use epoll;
use libc::{self, EAGAIN, EFD_NONBLOCK};
use log::*;
use std::cmp;
use std::fmt;
use std::io::Read;
use std::io::{self, Write};
use std::mem;
use std::net::Ipv4Addr;
use std::os::unix::io::AsRawFd;
use std::process;
use std::sync::{Arc, RwLock};
use std::vec::Vec;
use vhost_rs::vhost_user::message::*;
use vhost_rs::vhost_user::Error as VhostUserError;
use vhost_user_backend::{VhostUserBackend, VhostUserDaemon, Vring, VringWorker};
use net_gen;
use net_util::{Tap, TapError};
use virtio_bindings::bindings::virtio_net::*;
use vm_memory::{Bytes, GuestAddress, GuestMemoryMmap};
use vmm_sys_util::eventfd::EventFd;
/// The maximum buffer size when segmentation offload is enabled. This
/// includes the 12-byte virtio net header.
/// http://docs.oasis-open.org/virtio/virtio/v1.0/virtio-v1.0.html#x1-1740003
const MAX_BUFFER_SIZE: usize = 65562;
const QUEUE_SIZE: usize = 1024;
const NUM_QUEUES: usize = 2;
// The guest has made a buffer available to receive a frame into.
const RX_QUEUE_EVENT: u16 = 0;
// The transmit queue has a frame that is ready to send from the guest.
const TX_QUEUE_EVENT: u16 = 1;
// A frame is available for reading from the tap device to receive in the guest.
const RX_TAP_EVENT: u16 = 2;
// The device has been dropped.
const KILL_EVENT: u16 = 3;
pub type VhostUserResult<T> = std::result::Result<T, VhostUserError>;
pub type Result<T> = std::result::Result<T, Error>;
pub type VhostUserBackendResult<T> = std::result::Result<T, std::io::Error>;
#[derive(Debug)]
pub enum Error {
/// Failed to activate device.
BadActivate,
/// Failed to create kill eventfd
CreateKillEventFd,
/// Failed to add event.
EpollCtl(io::Error),
/// Fail to wait event.
EpollWait(io::Error),
/// Failed to create EventFd.
EpollCreateFd,
/// Failed to read Tap.
FailedReadTap,
/// Failed to signal used queue.
FailedSignalingUsedQueue,
/// Failed to handle event other than input event.
HandleEventNotEpollIn,
/// Failed to handle unknown event.
HandleEventUnknownEvent,
/// Invalid vring address.
InvalidVringAddr,
/// No vring call fd to notify.
NoVringCallFdNotify,
/// No memory configured.
NoMemoryConfigured,
/// Failed to parse sock parameter.
ParseSockParam,
/// Failed to parse ip parameter.
ParseIpParam,
/// Failed to parse mask parameter.
ParseMaskParam,
/// Open tap device failed.
TapOpen(TapError),
/// Setting tap IP failed.
TapSetIp(TapError),
/// Setting tap netmask failed.
TapSetNetmask(TapError),
/// Setting tap interface offload flags failed.
TapSetOffload(TapError),
/// Setting vnet header size failed.
TapSetVnetHdrSize(TapError),
/// Enabling tap interface failed.
TapEnable(TapError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "vhost_user_net_error: {:?}", self)
}
}
impl std::error::Error for Error {}
impl std::convert::From<Error> for std::io::Error {
fn from(e: Error) -> Self {
std::io::Error::new(io::ErrorKind::Other, e)
}
}
#[derive(Clone)]
struct TxVirtio {
iovec: Vec<(GuestAddress, usize)>,
frame_buf: [u8; MAX_BUFFER_SIZE],
}
impl TxVirtio {
fn new() -> Self {
TxVirtio {
iovec: Vec::new(),
frame_buf: [0u8; MAX_BUFFER_SIZE],
}
}
}
#[derive(Clone)]
struct RxVirtio {
deferred_frame: bool,
deferred_irqs: bool,
bytes_read: usize,
frame_buf: [u8; MAX_BUFFER_SIZE],
}
impl RxVirtio {
fn new() -> Self {
RxVirtio {
deferred_frame: false,
deferred_irqs: false,
bytes_read: 0,
frame_buf: [0u8; MAX_BUFFER_SIZE],
}
}
}
fn vnet_hdr_len() -> usize {
mem::size_of::<virtio_net_hdr_v1>()
}
struct VhostUserNetBackend {
mem: Option<GuestMemoryMmap>,
vring_worker: Option<Arc<VringWorker>>,
kill_evt: EventFd,
tap: Tap,
rx: RxVirtio,
tx: TxVirtio,
rx_tap_listening: bool,
}
impl std::clone::Clone for VhostUserNetBackend {
fn clone(&self) -> Self {
VhostUserNetBackend {
mem: self.mem.clone(),
vring_worker: self.vring_worker.clone(),
kill_evt: self.kill_evt.try_clone().unwrap(),
tap: self.tap.clone(),
rx: self.rx.clone(),
tx: self.tx.clone(),
rx_tap_listening: self.rx_tap_listening,
}
}
}
impl VhostUserNetBackend {
/// Create a new virtio network device with the given TAP interface.
pub fn new_with_tap(tap: Tap) -> Result<Self> {
// Set offload flags to match the virtio features below.
tap.set_offload(
net_gen::TUN_F_CSUM | net_gen::TUN_F_UFO | net_gen::TUN_F_TSO4 | net_gen::TUN_F_TSO6,
)
.map_err(Error::TapSetOffload)?;
let vnet_hdr_size = vnet_hdr_len() as i32;
tap.set_vnet_hdr_size(vnet_hdr_size)
.map_err(Error::TapSetVnetHdrSize)?;
let rx = RxVirtio::new();
let tx = TxVirtio::new();
Ok(VhostUserNetBackend {
mem: None,
vring_worker: None,
kill_evt: EventFd::new(EFD_NONBLOCK).map_err(|_| Error::CreateKillEventFd)?,
tap,
rx,
tx,
rx_tap_listening: false,
})
}
/// Create a new virtio network device with the given IP address and
/// netmask.
pub fn new(ip_addr: Ipv4Addr, netmask: Ipv4Addr) -> Result<Self> {
let tap = Tap::new().map_err(Error::TapOpen)?;
tap.set_ip_addr(ip_addr).map_err(Error::TapSetIp)?;
tap.set_netmask(netmask).map_err(Error::TapSetNetmask)?;
tap.enable().map_err(Error::TapEnable)?;
Self::new_with_tap(tap)
}
// Copies a single frame from `self.rx.frame_buf` into the guest. Returns true
// if a buffer was used, and false if the frame must be deferred until a buffer
// is made available by the driver.
fn rx_single_frame(&mut self, vring: &mut Vring) -> Result<bool> {
let mem = self.mem.as_ref().ok_or(Error::NoMemoryConfigured)?;
let mut next_desc = vring.mut_queue().iter(&mem).next();
if next_desc.is_none() {
// Queue has no available descriptors
if self.rx_tap_listening {
self.vring_worker
.as_ref()
.unwrap()
.unregister_listener(
self.tap.as_raw_fd(),
epoll::Events::EPOLLIN,
u64::from(RX_TAP_EVENT),
)
.unwrap();
self.rx_tap_listening = false;
}
return Ok(false);
}
// We just checked that the head descriptor exists.
let head_index = next_desc.as_ref().unwrap().index;
let mut write_count = 0;
// Copy from frame into buffer, which may span multiple descriptors.
loop {
match next_desc {
Some(desc) => {
if !desc.is_write_only() {
break;
}
let limit = cmp::min(write_count + desc.len as usize, self.rx.bytes_read);
let source_slice = &self.rx.frame_buf[write_count..limit];
let write_result = mem.write_slice(source_slice, desc.addr);
match write_result {
Ok(_) => {
write_count = limit;
}
Err(e) => {
error!("Failed to write slice: {:?}", e);
break;
}
};
if write_count >= self.rx.bytes_read {
break;
}
next_desc = desc.next_descriptor();
}
None => {
warn!("Receiving buffer is too small to hold frame of current size");
break;
}
}
}
vring
.mut_queue()
.add_used(&mem, head_index, write_count as u32);
// Mark that we have at least one pending packet and we need to interrupt the guest.
self.rx.deferred_irqs = true;
Ok(write_count >= self.rx.bytes_read)
}
fn process_rx(&mut self, vring: &mut Vring) -> Result<()> {
// Read as many frames as possible.
loop {
match self.read_tap() {
Ok(count) => {
self.rx.bytes_read = count;
if !self.rx_single_frame(vring)? {
self.rx.deferred_frame = true;
break;
}
}
Err(e) => {
// The tap device is non-blocking, so any error aside from EAGAIN is
// unexpected.
match e.raw_os_error() {
Some(err) if err == EAGAIN => (),
_ => {
error!("Failed to read tap: {:?}", e);
return Err(Error::FailedReadTap);
}
};
break;
}
}
}
if self.rx.deferred_irqs {
self.rx.deferred_irqs = false;
vring.signal_used_queue().unwrap();
Ok(())
} else {
Ok(())
}
}
fn resume_rx(&mut self, vring: &mut Vring) -> Result<()> {
if self.rx.deferred_frame {
if self.rx_single_frame(vring)? {
self.rx.deferred_frame = false;
// process_rx() was interrupted possibly before consuming all
// packets in the tap; try continuing now.
self.process_rx(vring)
} else if self.rx.deferred_irqs {
self.rx.deferred_irqs = false;
vring.signal_used_queue().unwrap();
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
fn process_tx(&mut self, vring: &mut Vring) -> Result<()> {
let mem = self.mem.as_ref().ok_or(Error::NoMemoryConfigured)?;
let mut used_desc_heads = [(0, 0); QUEUE_SIZE];
let mut used_count = 0;
while let Some(avail_desc) = vring.mut_queue().iter(&mem).next() {
let head_index = avail_desc.index;
let mut read_count = 0;
let mut next_desc = Some(avail_desc);
self.tx.iovec.clear();
while let Some(desc) = next_desc {
if desc.is_write_only() {
break;
}
self.tx.iovec.push((desc.addr, desc.len as usize));
read_count += desc.len as usize;
next_desc = desc.next_descriptor();
}
used_desc_heads[used_count] = (head_index, read_count);
used_count += 1;
read_count = 0;
// Copy buffer from across multiple descriptors.
// TODO(performance - Issue #420): change this to use `writev()` instead of `write()`
// and get rid of the intermediate buffer.
for (desc_addr, desc_len) in self.tx.iovec.drain(..) {
let limit = cmp::min((read_count + desc_len) as usize, self.tx.frame_buf.len());
let read_result = mem.read_slice(
&mut self.tx.frame_buf[read_count..limit as usize],
desc_addr,
);
match read_result {
Ok(_) => {
// Increment by number of bytes actually read
read_count += limit - read_count;
}
Err(e) => {
error!("Failed to read slice: {:?}", e);
break;
}
}
}
let write_result = self.tap.write(&self.tx.frame_buf[..read_count as usize]);
match write_result {
Ok(_) => {}
Err(e) => {
error!("net: tx: error failed to write to tap: {}", e);
}
};
}
if used_count > 0 {
for &(desc_index, _) in &used_desc_heads[..used_count] {
vring.mut_queue().add_used(&mem, desc_index, 0);
}
vring.signal_used_queue().unwrap();
}
Ok(())
}
fn read_tap(&mut self) -> io::Result<usize> {
self.tap.read(&mut self.rx.frame_buf)
}
}
impl VhostUserBackend for VhostUserNetBackend {
fn num_queues(&self) -> usize {
NUM_QUEUES
}
fn max_queue_size(&self) -> usize {
QUEUE_SIZE
}
fn features(&self) -> u64 {
1 << VIRTIO_NET_F_GUEST_CSUM
| 1 << VIRTIO_NET_F_CSUM
| 1 << VIRTIO_NET_F_GUEST_TSO4
| 1 << VIRTIO_NET_F_GUEST_UFO
| 1 << VIRTIO_NET_F_HOST_TSO4
| 1 << VIRTIO_NET_F_HOST_UFO
| 1 << VIRTIO_F_VERSION_1
| VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits()
}
fn update_memory(&mut self, mem: GuestMemoryMmap) -> VhostUserBackendResult<()> {
self.mem = Some(mem);
Ok(())
}
fn handle_event(
&mut self,
device_event: u16,
evset: epoll::Events,
vrings: &[Arc<RwLock<Vring>>],
) -> VhostUserBackendResult<bool> {
if evset != epoll::Events::EPOLLIN {
return Err(Error::HandleEventNotEpollIn.into());
}
match device_event {
RX_QUEUE_EVENT => {
let mut vring = vrings[0].write().unwrap();
self.resume_rx(&mut vring)?;
if !self.rx_tap_listening {
self.vring_worker.as_ref().unwrap().register_listener(
self.tap.as_raw_fd(),
epoll::Events::EPOLLIN,
u64::from(RX_TAP_EVENT),
)?;
self.rx_tap_listening = true;
}
}
TX_QUEUE_EVENT => {
let mut vring = vrings[1].write().unwrap();
self.process_tx(&mut vring)?;
}
RX_TAP_EVENT => {
let mut vring = vrings[0].write().unwrap();
if self.rx.deferred_frame
// Process a deferred frame first if available. Don't read from tap again
// until we manage to receive this deferred frame.
{
if self.rx_single_frame(&mut vring)? {
self.rx.deferred_frame = false;
self.process_rx(&mut vring)?;
} else if self.rx.deferred_irqs {
self.rx.deferred_irqs = false;
vring.signal_used_queue()?;
}
} else {
self.process_rx(&mut vring)?;
}
}
KILL_EVENT => {
self.kill_evt.read().unwrap();
return Ok(true);
}
_ => return Err(Error::HandleEventUnknownEvent.into()),
}
Ok(false)
}
}
pub struct VhostUserNetBackendConfig<'a> {
pub ip: Ipv4Addr,
pub mask: Ipv4Addr,
pub sock: &'a str,
}
impl<'a> VhostUserNetBackendConfig<'a> {
pub fn parse(backend: &'a str) -> Result<Self> {
let params_list: Vec<&str> = backend.split(',').collect();
let mut ip_str: &str = "";
let mut mask_str: &str = "";
let mut sock: &str = "";
for param in params_list.iter() {
if param.starts_with("ip=") {
ip_str = &param[3..];
} else if param.starts_with("mask=") {
mask_str = &param[5..];
} else if param.starts_with("sock=") {
sock = &param[5..];
}
}
let mut ip: Ipv4Addr = Ipv4Addr::new(192, 168, 100, 1);
let mut mask: Ipv4Addr = Ipv4Addr::new(255, 255, 255, 0);
if sock.is_empty() {
return Err(Error::ParseSockParam);
}
if !ip_str.is_empty() {
ip = ip_str.parse().map_err(|_| Error::ParseIpParam)?;
}
if !mask_str.is_empty() {
mask = mask_str.parse().map_err(|_| Error::ParseMaskParam)?;
}
Ok(VhostUserNetBackendConfig { ip, mask, sock })
}
}
use vhost_user_net::start_net_backend;
fn main() {
let cmd_arguments = App::new("vhost-user-net backend")
@@ -541,57 +19,18 @@ fn main() {
.author(crate_authors!())
.about("Launch a vhost-user-net backend.")
.arg(
Arg::with_name("backend")
.long("backend")
Arg::with_name("net-backend")
.long("net-backend")
.help(
"Backend parameters \"ip=<ip_addr>,\
mask=<net_mask>,sock=<socket_path>\"",
"vhost-user-net backend parameters \
\"ip=<ip_addr>,mask=<net_mask>,sock=<socket_path>,\
num_queues=<number_of_queues>,queue_size=<size_of_each_queue>,tap=<if_name>\"",
)
.takes_value(true)
.min_values(1),
)
.get_matches();
let vhost_user_net_backend = cmd_arguments.value_of("backend").unwrap();
let backend_config = match VhostUserNetBackendConfig::parse(vhost_user_net_backend) {
Ok(config) => config,
Err(e) => {
println!("Failed parsing parameters {:?}", e);
process::exit(1);
}
};
let net_backend = Arc::new(RwLock::new(
VhostUserNetBackend::new(backend_config.ip, backend_config.mask).unwrap(),
));
let name = "vhost-user-net-backend";
let mut net_daemon = VhostUserDaemon::new(
name.to_string(),
backend_config.sock.to_string(),
net_backend.clone(),
)
.unwrap();
let vring_worker = net_daemon.get_vring_worker();
if let Err(e) = vring_worker.register_listener(
net_backend.read().unwrap().kill_evt.as_raw_fd(),
epoll::Events::EPOLLIN,
u64::from(KILL_EVENT),
) {
println!("failed to register listener for kill event: {:?}", e);
process::exit(1);
}
net_backend.write().unwrap().vring_worker = Some(vring_worker);
if let Err(e) = net_daemon.start() {
println!(
"failed to start daemon for vhost-user-net with error: {:?}",
e
);
process::exit(1);
}
net_daemon.wait().unwrap();
let backend_command = cmd_arguments.value_of("net-backend").unwrap();
start_net_backend(backend_command);
}

File diff suppressed because it is too large Load Diff

View File

@@ -17,7 +17,7 @@ write_files:
Gateway=192.168.2.1
-
path: /etc/systemd/network/00-static-l2.network
path: /etc/systemd/network/00-static-l2-1.network
permissions: 0644
content: |
[Match]
@@ -27,6 +27,28 @@ write_files:
Address=192.168.2.3/24
Gateway=192.168.2.1
-
path: /etc/systemd/network/00-static-l2-2.network
permissions: 0644
content: |
[Match]
MACAddress=de:ad:be:ef:34:56
[Network]
Address=192.168.2.4/24
Gateway=192.168.2.1
-
path: /etc/systemd/network/00-static-l2-3.network
permissions: 0644
content: |
[Match]
MACAddress=de:ad:be:ef:56:78
[Network]
Address=192.168.2.5/24
Gateway=192.168.2.1
-
path: /etc/systemd/system/vfio.service
permissions: 0644
@@ -47,8 +69,12 @@ write_files:
content: |
#!/bin/bash
mount -t virtio_fs virtiofs /mnt -o rootmode=040000,user_id=0,group_id=0,dax
mount -t virtiofs -o dax myfs /mnt
bash -c "echo 0000:00:05.0 > /sys/bus/pci/devices/0000\:00\:05.0/driver/unbind"
bash -c "echo 1af4 1041 > /sys/bus/pci/drivers/vfio-pci/new_id"
/mnt/cloud-hypervisor --kernel /mnt/vmlinux --cmdline "console=hvc0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=/dev/vda2 VFIOTAG" --disk path=/mnt/clear-cloudguest.img path=/mnt/cloudinit.img --cpus 1 --memory size=512M --rng --device path=/sys/bus/pci/devices/0000:00:05.0/
bash -c "echo 0000:00:06.0 > /sys/bus/pci/devices/0000\:00\:06.0/driver/unbind"
bash -c "echo 1af4 1041 > /sys/bus/pci/drivers/vfio-pci/new_id"
# 1G ram requires 512 pages
echo 512 | sudo tee /proc/sys/vm/nr_hugepages
sudo chmod a+rwX /dev/hugepages
/mnt/cloud-hypervisor --kernel /mnt/vmlinux --cmdline "console=hvc0 reboot=k panic=1 nomodules i8042.noaux i8042.nomux i8042.nopnp i8042.dumbkbd root=PARTUUID=6fb4d1a8-6c8c-4dd7-9f7c-1fe0b9f2574c VFIOTAG" --disk path=/mnt/clear-31311-cloudguest.img path=/mnt/cloudinit.img --cpus boot=1 --memory size=512M,hotplug_size=1G,file=/dev/hugepages --device path=/sys/bus/pci/devices/0000:00:05.0/ path=/sys/bus/pci/devices/0000:00:06.0/ --api-socket /tmp/ch_api.sock

4228
tests/integration.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -4,18 +4,19 @@ version = "0.0.1"
authors = ["The Cloud Hypervisor Authors"]
[dependencies]
byteorder = "1.3.2"
arc-swap = ">=0.4.4"
byteorder = "1.3.4"
devices = { path = "../devices" }
kvm-bindings = "0.1.1"
kvm-ioctls = { git = "https://github.com/rust-vmm/kvm-ioctls", branch = "master" }
libc = "0.2.60"
kvm-bindings = { git = "https://github.com/cloud-hypervisor/kvm-bindings", branch = "ch" }
kvm-ioctls = { git = "https://github.com/cloud-hypervisor/kvm-ioctls", branch = "ch" }
libc = "0.2.69"
log = "0.4.8"
pci = { path = "../pci" }
vfio-bindings = "0.1.0"
vm-allocator = { path = "../vm-allocator" }
vm-device = { path = "../vm-device" }
vmm-sys-util = "0.1.1"
vm-memory = { version = "0.2.0", features = ["backend-mmap"] }
vmm-sys-util = ">=0.3.1"
[dependencies.vm-memory]
git = "https://github.com/rust-vmm/vm-memory"
features = ["backend-mmap"]
[dependencies.vfio-bindings]
git = "https://github.com/rust-vmm/vfio-bindings"
features = ["fam-wrappers"]

View File

@@ -5,6 +5,7 @@
//#![deny(missing_docs)]
//! Virtual Function I/O (VFIO) API
extern crate arc_swap;
extern crate byteorder;
extern crate devices;
extern crate kvm_bindings;

View File

@@ -6,22 +6,29 @@ use crate::vec_with_array_field;
use byteorder::{ByteOrder, LittleEndian};
use kvm_ioctls::*;
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::CString;
use std::fmt;
use std::fs::{File, OpenOptions};
use std::io;
use std::mem;
use std::num;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::os::unix::prelude::FileExt;
use std::path::{Path, PathBuf};
use std::result;
use std::sync::{Arc, RwLock};
use std::sync::Arc;
use std::u32;
use vfio_bindings::bindings::vfio::*;
use vfio_bindings::bindings::IrqSet;
use vfio_ioctls::*;
use vm_device::ExternalDmaMapping;
use vm_memory::{Address, GuestAddress, GuestMemory, GuestMemoryMmap, GuestMemoryRegion};
use vm_device::{get_host_address_range, ExternalDmaMapping};
use vm_memory::{
Address, GuestAddress, GuestAddressSpace, GuestMemory, GuestMemoryAtomic, GuestMemoryMmap,
GuestMemoryRegion, GuestRegionMmap,
};
use vmm_sys_util::eventfd::EventFd;
use vmm_sys_util::fam::FamStruct;
use vmm_sys_util::ioctl::*;
#[derive(Debug)]
@@ -38,7 +45,7 @@ pub enum VfioError {
UnsetContainer,
ContainerSetIOMMU,
GroupGetDeviceFD,
KvmSetDeviceAttr(io::Error),
KvmSetDeviceAttr(kvm_ioctls::Error),
VfioDeviceGetInfo,
VfioDeviceGetRegionInfo,
InvalidPath,
@@ -46,6 +53,9 @@ pub enum VfioError {
IommuDmaUnmap,
VfioDeviceGetIrqInfo,
VfioDeviceSetIrq,
VfioNoIommuGroup(String),
ReadLink(io::Error),
ParseInt(num::ParseIntError),
}
pub type Result<T> = std::result::Result<T, VfioError>;
@@ -94,6 +104,9 @@ impl fmt::Display for VfioError {
}
VfioError::VfioDeviceGetIrqInfo => write!(f, "failed to get vfio device irq info"),
VfioError::VfioDeviceSetIrq => write!(f, "failed to set vfio deviece irq"),
VfioError::ReadLink(e) => write!(f, "failed to read link from path: {}", e),
VfioError::VfioNoIommuGroup(e) => write!(f, "Failed to find iommu_group for: {}", e),
VfioError::ParseInt(e) => write!(f, "failed to parse integer: {}", e),
}
}
}
@@ -268,7 +281,7 @@ impl VfioGroup {
.map_err(VfioError::KvmSetDeviceAttr)
}
fn kvm_device_del_group(&self) -> std::result::Result<(), io::Error> {
fn kvm_device_del_group(&self) -> std::result::Result<(), kvm_ioctls::Error> {
let group_fd = self.as_raw_fd();
let group_fd_ptr = &group_fd as *const i32;
let dev_attr = kvm_bindings::kvm_device_attr {
@@ -435,7 +448,7 @@ impl VfioDeviceInfo {
ioctl_with_mut_ref(&self.device, VFIO_DEVICE_GET_REGION_INFO(), &mut reg_info)
};
if ret < 0 {
error!("Could not get region #{} info", i);
warn!("Could not get region #{} info", i);
continue;
}
@@ -461,7 +474,7 @@ impl VfioDeviceInfo {
)
};
if ret < 0 {
error!("Could not get region #{} info", i);
warn!("Could not get region #{} info", i);
continue;
}
// region_with_cap[0].cap_info may contain vfio_region_info_cap_sparse_mmap
@@ -513,23 +526,22 @@ impl VfioDeviceInfo {
/// associated with a specific VFIO container.
pub struct VfioDmaMapping {
container: Arc<VfioContainer>,
memory: Arc<RwLock<GuestMemoryMmap>>,
memory: GuestMemoryAtomic<GuestMemoryMmap>,
}
impl VfioDmaMapping {
pub fn new(container: Arc<VfioContainer>, memory: Arc<RwLock<GuestMemoryMmap>>) -> Self {
pub fn new(container: Arc<VfioContainer>, memory: GuestMemoryAtomic<GuestMemoryMmap>) -> Self {
VfioDmaMapping { container, memory }
}
}
impl ExternalDmaMapping for VfioDmaMapping {
fn map(&self, iova: u64, gpa: u64, size: u64) -> result::Result<(), io::Error> {
let user_addr = if let Some(addr) = self
.memory
.read()
.unwrap()
.get_host_address(GuestAddress(gpa))
{
let user_addr = if let Some(addr) = get_host_address_range(
&self.memory.memory(),
GuestAddress(gpa),
size.try_into().unwrap(),
) {
addr as u64
} else {
return Err(io::Error::new(
@@ -577,7 +589,7 @@ pub struct VfioDevice {
group: VfioGroup,
regions: Vec<VfioRegion>,
irqs: HashMap<u32, VfioIrq>,
mem: Arc<RwLock<GuestMemoryMmap>>,
mem: GuestMemoryAtomic<GuestMemoryMmap>,
iommu_attached: bool,
}
@@ -588,16 +600,19 @@ impl VfioDevice {
pub fn new(
sysfspath: &Path,
device_fd: Arc<DeviceFd>,
mem: Arc<RwLock<GuestMemoryMmap>>,
mem: GuestMemoryAtomic<GuestMemoryMmap>,
iommu_attached: bool,
) -> Result<Self> {
let uuid_path: PathBuf = [sysfspath, Path::new("iommu_group")].iter().collect();
let group_path = uuid_path.read_link().map_err(|_| VfioError::InvalidPath)?;
if !uuid_path.exists() {
return Err(VfioError::VfioNoIommuGroup(
uuid_path.to_str().unwrap().to_string(),
));
}
let group_path = uuid_path.read_link().map_err(VfioError::ReadLink)?;
let group_osstr = group_path.file_name().ok_or(VfioError::InvalidPath)?;
let group_str = group_osstr.to_str().ok_or(VfioError::InvalidPath)?;
let group_id = group_str
.parse::<u32>()
.map_err(|_| VfioError::InvalidPath)?;
let group_id = group_str.parse::<u32>().map_err(VfioError::ParseInt)?;
let group = VfioGroup::new(group_id, device_fd)?;
let device_info = group.get_device(sysfspath)?;
@@ -641,34 +656,25 @@ impl VfioDevice {
return Err(VfioError::VfioDeviceSetIrq);
}
let mut irq_set = vec_with_array_field::<vfio_irq_set, u32>(event_fds.len());
irq_set[0].argsz = mem::size_of::<vfio_irq_set>() as u32
+ (event_fds.len() * mem::size_of::<u32>()) as u32;
irq_set[0].flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set[0].index = irq_index;
irq_set[0].start = 0;
irq_set[0].count = irq.count;
let mut irq_set_wrapper = IrqSet::new(event_fds.len() * mem::size_of::<u32>());
let mut irq_set = irq_set_wrapper.as_mut_fam_struct();
let fds = irq_set.as_mut_slice();
{
// irq_set.data could be none, bool or fd according to flags, so irq_set.data
// is u8 default, here irq_set.data is a vector of fds as u32, so 4 default u8
// are combined together as u32 for each fd.
// It is safe as enough space is reserved through
// vec_with_array_field(u32)<event_fds.len()>.
let fds = unsafe {
irq_set[0]
.data
.as_mut_slice(event_fds.len() * mem::size_of::<u32>())
};
for (index, event_fd) in event_fds.iter().enumerate() {
let fds_offset = index * mem::size_of::<u32>();
let fd = &mut fds[fds_offset..fds_offset + mem::size_of::<u32>()];
LittleEndian::write_u32(fd, event_fd.as_raw_fd() as u32);
}
for (index, event_fd) in event_fds.iter().enumerate() {
let fds_offset = index * mem::size_of::<u32>();
let fd = &mut fds[fds_offset..fds_offset + mem::size_of::<u32>()];
LittleEndian::write_u32(fd, event_fd.as_raw_fd() as u32);
}
irq_set.argsz = mem::size_of::<vfio_irq_set>() as u32
+ (event_fds.len() * mem::size_of::<u32>()) as u32;
irq_set.flags = VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
irq_set.index = irq_index;
irq_set.start = 0;
irq_set.count = irq.count;
// Safe as we are the owner of self and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, VFIO_DEVICE_SET_IRQS(), &irq_set[0]) };
let ret = unsafe { ioctl_with_ref(self, VFIO_DEVICE_SET_IRQS(), irq_set) };
if ret < 0 {
return Err(VfioError::VfioDeviceSetIrq);
}
@@ -692,10 +698,10 @@ impl VfioDevice {
let mut irq_set = vec_with_array_field::<vfio_irq_set, u32>(0);
irq_set[0].argsz = mem::size_of::<vfio_irq_set>() as u32;
irq_set[0].flags = VFIO_IRQ_SET_ACTION_MASK;
irq_set[0].flags = VFIO_IRQ_SET_ACTION_TRIGGER | VFIO_IRQ_SET_DATA_NONE;
irq_set[0].index = irq_index;
irq_set[0].start = 0;
irq_set[0].count = irq.count;
irq_set[0].count = 0;
// Safe as we are the owner of self and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, VFIO_DEVICE_SET_IRQS(), &irq_set[0]) };
@@ -845,7 +851,7 @@ impl VfioDevice {
/// then vfio kernel driver could access guest memory from gfn
pub fn setup_dma_map(&self) -> Result<()> {
if !self.iommu_attached {
self.mem.read().unwrap().with_regions(|_index, region| {
self.mem.memory().with_regions(|_index, region| {
self.vfio_dma_map(
region.start_addr().raw_value(),
region.len() as u64,
@@ -860,13 +866,25 @@ impl VfioDevice {
/// then vfio kernel driver couldn't access this guest memory
pub fn unset_dma_map(&self) -> Result<()> {
if !self.iommu_attached {
self.mem.read().unwrap().with_regions(|_index, region| {
self.mem.memory().with_regions(|_index, region| {
self.vfio_dma_unmap(region.start_addr().raw_value(), region.len() as u64)
})?;
}
Ok(())
}
pub fn extend_dma_map(&self, new_region: &Arc<GuestRegionMmap>) -> Result<()> {
if !self.iommu_attached {
self.vfio_dma_map(
new_region.start_addr().raw_value(),
new_region.len() as u64,
new_region.as_ptr() as u64,
)
} else {
Ok(())
}
}
/// Return the maximum numner of interrupts a VFIO device can request.
/// This is used for pre-allocating the VFIO PCI routes.
pub fn max_interrupts(&self) -> u32 {

View File

@@ -7,36 +7,43 @@ extern crate devices;
extern crate pci;
extern crate vm_allocator;
use crate::vec_with_array_field;
use crate::vfio_device::VfioDevice;
use byteorder::{ByteOrder, LittleEndian};
use devices::BusDevice;
use kvm_bindings::{
kvm_irq_routing, kvm_irq_routing_entry, kvm_userspace_memory_region, KVM_IRQ_ROUTING_MSI,
};
use kvm_bindings::kvm_userspace_memory_region;
use kvm_ioctls::*;
use pci::{
MsiCap, MsixCap, MsixConfig, PciBarConfiguration, PciBarRegionType, PciCapabilityID,
PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass,
MSIX_TABLE_ENTRY_SIZE,
msi_num_enabled_vectors, BarReprogrammingParams, MsiConfig, MsixCap, MsixConfig,
PciBarConfiguration, PciBarRegionType, PciCapabilityID, PciClassCode, PciConfiguration,
PciDevice, PciDeviceError, PciHeaderType, PciSubclass, MSIX_TABLE_ENTRY_SIZE,
};
use std::any::Any;
use std::os::unix::io::AsRawFd;
use std::ptr::null_mut;
use std::sync::Arc;
use std::{fmt, io};
use std::{fmt, io, result};
use vfio_bindings::bindings::vfio::*;
use vm_allocator::SystemAllocator;
use vm_memory::{Address, GuestAddress, GuestUsize};
use vm_device::interrupt::{
InterruptIndex, InterruptManager, InterruptSourceGroup, MsiIrqGroupConfig,
};
use vm_memory::{Address, GuestAddress, GuestRegionMmap, GuestUsize};
use vmm_sys_util::eventfd::EventFd;
#[derive(Debug)]
pub enum VfioPciError {
AllocateGsi,
EventFd(io::Error),
IrqFd(io::Error),
InterruptSourceGroupCreate(io::Error),
IrqFd(kvm_ioctls::Error),
NewVfioPciDevice,
MapRegionGuest(io::Error),
SetGsiRouting(io::Error),
MapRegionGuest(kvm_ioctls::Error),
SetGsiRouting(kvm_ioctls::Error),
MsiNotConfigured,
MsixNotConfigured,
UpdateMemory(crate::VfioError),
UpdateMsiEventFd,
UpdateMsixEventFd,
}
pub type Result<T> = std::result::Result<T, VfioPciError>;
@@ -45,12 +52,20 @@ impl fmt::Display for VfioPciError {
match self {
VfioPciError::AllocateGsi => write!(f, "failed to allocate GSI"),
VfioPciError::EventFd(e) => write!(f, "failed to create eventfd: {}", e),
VfioPciError::InterruptSourceGroupCreate(e) => {
write!(f, "failed to create interrupt source group: {}", e)
}
VfioPciError::IrqFd(e) => write!(f, "failed to register irqfd: {}", e),
VfioPciError::NewVfioPciDevice => write!(f, "failed to create VFIO PCI device"),
VfioPciError::MapRegionGuest(e) => {
write!(f, "failed to map VFIO PCI region into guest: {}", e)
}
VfioPciError::SetGsiRouting(e) => write!(f, "failed to set GSI routes for KVM: {}", e),
VfioPciError::MsiNotConfigured => write!(f, "MSI interrupt not yet configured"),
VfioPciError::MsixNotConfigured => write!(f, "MSI-X interrupt not yet configured"),
VfioPciError::UpdateMemory(e) => write!(f, "failed to update memory: {}", e),
VfioPciError::UpdateMsiEventFd => write!(f, "failed to update MSI eventfd"),
VfioPciError::UpdateMsixEventFd => write!(f, "failed to update MSI-X eventfd"),
}
}
}
@@ -73,19 +88,19 @@ enum InterruptUpdateAction {
DisableMsix,
}
#[derive(Copy, Clone)]
struct VfioMsi {
cap: MsiCap,
cfg: MsiConfig,
cap_offset: u32,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
}
impl VfioMsi {
fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> {
let old_enabled = self.cap.enabled();
let old_enabled = self.cfg.enabled();
self.cap.update(offset, data);
self.cfg.update(offset, data);
let new_enabled = self.cap.enabled();
let new_enabled = self.cfg.enabled();
if !old_enabled && new_enabled {
return Some(InterruptUpdateAction::EnableMsi);
@@ -103,18 +118,19 @@ struct VfioMsix {
bar: MsixConfig,
cap: MsixCap,
cap_offset: u32,
interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>,
}
impl VfioMsix {
fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> {
let old_enabled = self.cap.enabled();
let old_enabled = self.bar.enabled();
// Update "Message Control" word
if offset == 2 && data.len() == 2 {
self.cap.set_msg_ctl(LittleEndian::read_u16(data));
self.bar.set_msg_ctl(LittleEndian::read_u16(data));
}
let new_enabled = self.cap.enabled();
let new_enabled = self.bar.enabled();
if !old_enabled && new_enabled {
return Some(InterruptUpdateAction::EnableMsix);
@@ -163,7 +179,7 @@ impl Interrupt {
fn accessed(&self, offset: u64) -> Option<(PciCapabilityID, u64)> {
if let Some(msi) = &self.msi {
if offset >= u64::from(msi.cap_offset)
&& offset < u64::from(msi.cap_offset) + msi.cap.size()
&& offset < u64::from(msi.cap_offset) + msi.cfg.size()
{
return Some((
PciCapabilityID::MessageSignalledInterrupts,
@@ -181,22 +197,6 @@ impl Interrupt {
None
}
fn msix_enabled(&self) -> bool {
if let Some(msix) = &self.msix {
return msix.cap.enabled();
}
false
}
fn msix_function_masked(&self) -> bool {
if let Some(msix) = &self.msix {
return msix.cap.masked();
}
false
}
fn msix_table_accessed(&self, bar_index: u32, offset: u64) -> bool {
if let Some(msix) = &self.msix {
return msix.table_accessed(bar_index, offset);
@@ -220,41 +220,15 @@ impl Interrupt {
}
}
#[derive(Copy, Clone, Default)]
struct MsiVector {
msg_addr_lo: u32,
msg_addr_hi: u32,
msg_data: u32,
masked: bool,
}
struct InterruptRoute {
gsi: u32,
irq_fd: EventFd,
msi_vector: MsiVector,
}
impl InterruptRoute {
fn new(vm: &Arc<VmFd>, allocator: &mut SystemAllocator, msi_vector: MsiVector) -> Result<Self> {
let irq_fd = EventFd::new(libc::EFD_NONBLOCK).map_err(VfioPciError::EventFd)?;
let gsi = allocator.allocate_gsi().ok_or(VfioPciError::AllocateGsi)?;
vm.register_irqfd(irq_fd.as_raw_fd(), gsi)
.map_err(VfioPciError::IrqFd)?;
Ok(InterruptRoute {
gsi,
irq_fd,
msi_vector,
})
}
}
#[derive(Copy, Clone)]
struct MmioRegion {
start: GuestAddress,
length: GuestUsize,
type_: PciBarRegionType,
index: u32,
mem_slot: Option<u32>,
host_addr: Option<u64>,
mmap_size: Option<usize>,
}
struct VfioPciConfig {
@@ -310,20 +284,20 @@ pub struct VfioPciDevice {
configuration: PciConfiguration,
mmio_regions: Vec<MmioRegion>,
interrupt: Interrupt,
interrupt_routes: Vec<InterruptRoute>,
}
impl VfioPciDevice {
/// Constructs a new Vfio Pci device for the given Vfio device
pub fn new(
vm_fd: &Arc<VmFd>,
allocator: &mut SystemAllocator,
device: VfioDevice,
interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) -> Result<Self> {
let device = Arc::new(device);
device.reset();
let configuration = PciConfiguration::new(
0,
0,
0,
PciClassCode::Other,
@@ -347,71 +321,18 @@ impl VfioPciDevice {
msi: None,
msix: None,
},
interrupt_routes: Vec::new(),
};
vfio_pci_device.parse_capabilities();
// Allocate temporary interrupt routes for now.
// The MSI vectors will be filled when the guest driver programs the device.
let max_interrupts = vfio_pci_device.device.max_interrupts();
for _ in 0..max_interrupts {
let msi_vector: MsiVector = Default::default();
let route = InterruptRoute::new(vm_fd, allocator, msi_vector)?;
vfio_pci_device.interrupt_routes.push(route);
}
vfio_pci_device.parse_capabilities(interrupt_manager);
Ok(vfio_pci_device)
}
fn irq_fds(&self) -> Result<Vec<&EventFd>> {
let mut irq_fds: Vec<&EventFd> = Vec::new();
for r in &self.interrupt_routes {
irq_fds.push(&r.irq_fd);
}
Ok(irq_fds)
}
fn set_kvm_routes(&self) -> Result<()> {
let mut entry_vec: Vec<kvm_irq_routing_entry> = Vec::new();
for route in self.interrupt_routes.iter() {
// Do not add masked vectors to the GSI mapping
if route.msi_vector.masked {
continue;
}
let mut entry = kvm_irq_routing_entry {
gsi: route.gsi,
type_: KVM_IRQ_ROUTING_MSI,
..Default::default()
};
entry.u.msi.address_lo = route.msi_vector.msg_addr_lo;
entry.u.msi.address_hi = route.msi_vector.msg_addr_hi;
entry.u.msi.data = route.msi_vector.msg_data;
entry_vec.push(entry);
}
let mut irq_routing =
vec_with_array_field::<kvm_irq_routing, kvm_irq_routing_entry>(entry_vec.len());
irq_routing[0].nr = entry_vec.len() as u32;
irq_routing[0].flags = 0;
unsafe {
let entries: &mut [kvm_irq_routing_entry] =
irq_routing[0].entries.as_mut_slice(entry_vec.len());
entries.copy_from_slice(&entry_vec);
}
self.vm_fd
.set_gsi_routing(&irq_routing[0])
.map_err(VfioPciError::SetGsiRouting)
}
fn parse_msix_capabilities(&mut self, cap: u8) {
fn parse_msix_capabilities(
&mut self,
cap: u8,
interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) {
let msg_ctl = self
.vfio_pci_configuration
.read_config_word((cap + 2).into());
@@ -429,30 +350,53 @@ impl VfioPciDevice {
table,
pba,
};
let msix_config = MsixConfig::new(msix_cap.table_size());
let interrupt_source_group = interrupt_manager
.create_group(MsiIrqGroupConfig {
base: 0,
count: msix_cap.table_size() as InterruptIndex,
})
.unwrap();
let msix_config = MsixConfig::new(msix_cap.table_size(), interrupt_source_group.clone());
self.interrupt.msix = Some(VfioMsix {
bar: msix_config,
cap: msix_cap,
cap_offset: cap.into(),
interrupt_source_group,
});
}
fn parse_msi_capabilities(&mut self, cap: u8) {
fn parse_msi_capabilities(
&mut self,
cap: u8,
interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) {
let msg_ctl = self
.vfio_pci_configuration
.read_config_word((cap + 2).into());
let interrupt_source_group = interrupt_manager
.create_group(MsiIrqGroupConfig {
base: 0,
count: msi_num_enabled_vectors(msg_ctl) as InterruptIndex,
})
.unwrap();
let msi_config = MsiConfig::new(msg_ctl, interrupt_source_group.clone());
self.interrupt.msi = Some(VfioMsi {
cap: MsiCap {
msg_ctl,
..Default::default()
},
cfg: msi_config,
cap_offset: cap.into(),
interrupt_source_group,
});
}
fn parse_capabilities(&mut self) {
fn parse_capabilities(
&mut self,
interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>,
) {
let mut cap_next = self
.vfio_pci_configuration
.read_config_byte(PCI_CONFIG_CAPABILITY_OFFSET);
@@ -464,10 +408,10 @@ impl VfioPciDevice {
match PciCapabilityID::from(cap_id) {
PciCapabilityID::MessageSignalledInterrupts => {
self.parse_msi_capabilities(cap_next);
self.parse_msi_capabilities(cap_next, interrupt_manager);
}
PciCapabilityID::MSIX => {
self.parse_msix_capabilities(cap_next);
self.parse_msix_capabilities(cap_next, interrupt_manager);
}
_ => {}
};
@@ -478,67 +422,26 @@ impl VfioPciDevice {
}
}
fn update_msi_interrupt_routes(&mut self, msi: &VfioMsi) -> Result<()> {
let num_vectors = msi.cap.num_enabled_vectors();
for (idx, route) in self.interrupt_routes.iter_mut().enumerate() {
// Mask the MSI vector if the amount of vectors supported by the
// guest OS does not match the expected amount. This is related
// to "Multiple Message Capable" and "Multiple Message Enable"
// fields from the "Message Control" register.
if idx >= num_vectors {
route.msi_vector.masked = true;
continue;
}
route.msi_vector.msg_addr_lo = msi.cap.msg_addr_lo;
route.msi_vector.msg_addr_hi = msi.cap.msg_addr_hi;
route.msi_vector.msg_data = u32::from(msi.cap.msg_data) | (idx as u32);
route.msi_vector.masked = msi.cap.vector_masked(idx);
}
// Check if we need to update KVM GSI mapping, based on the status of
// the "MSI Enable" bit.
if msi.cap.enabled() {
return self.set_kvm_routes();
}
Ok(())
}
fn read_msix_table(&mut self, offset: u64, data: &mut [u8]) {
self.interrupt.msix_read_table(offset, data);
}
fn update_msix_table(&mut self, offset: u64, data: &[u8]) -> Result<()> {
self.interrupt.msix_write_table(offset, data);
if self.interrupt.msix_enabled() && !self.interrupt.msix_function_masked() {
// Fill tables
if let Some(msix) = &self.interrupt.msix {
for (idx, entry) in msix.bar.table_entries.iter().enumerate() {
self.interrupt_routes[idx].msi_vector.msg_addr_lo = entry.msg_addr_lo;
self.interrupt_routes[idx].msi_vector.msg_addr_hi = entry.msg_addr_hi;
self.interrupt_routes[idx].msi_vector.msg_data = entry.msg_data;
self.interrupt_routes[idx].msi_vector.masked = entry.masked();
}
}
return self.set_kvm_routes();
}
Ok(())
}
fn update_msi_capabilities(&mut self, offset: u64, data: &[u8]) -> Result<()> {
match self.interrupt.update_msi(offset, data) {
Some(InterruptUpdateAction::EnableMsi) => match self.irq_fds() {
Ok(fds) => {
if let Err(e) = self.device.enable_msi(fds) {
Some(InterruptUpdateAction::EnableMsi) => {
if let Some(msi) = &self.interrupt.msi {
let mut irq_fds: Vec<&EventFd> = Vec::new();
for i in 0..msi.cfg.num_enabled_vectors() {
if let Some(eventfd) =
msi.interrupt_source_group.notifier(i as InterruptIndex)
{
irq_fds.push(eventfd);
} else {
return Err(VfioPciError::UpdateMsiEventFd);
}
}
if let Err(e) = self.device.enable_msi(irq_fds) {
warn!("Could not enable MSI: {}", e);
}
}
Err(e) => warn!("Could not get IRQ fds: {}", e),
},
}
Some(InterruptUpdateAction::DisableMsi) => {
if let Err(e) = self.device.disable_msi() {
warn!("Could not disable MSI: {}", e);
@@ -547,34 +450,38 @@ impl VfioPciDevice {
_ => {}
}
// Update the interrupt_routes table now that the MSI cache has been
// updated. The point is to always update the table based on latest
// changes to the cache, and based on the state of masking flags, the
// KVM GSI routes should be configured.
if let Some(msi) = self.interrupt.msi {
return self.update_msi_interrupt_routes(&msi);
}
Ok(())
}
fn update_msix_capabilities(&mut self, offset: u64, data: &[u8]) {
fn update_msix_capabilities(&mut self, offset: u64, data: &[u8]) -> Result<()> {
match self.interrupt.update_msix(offset, data) {
Some(InterruptUpdateAction::EnableMsix) => match self.irq_fds() {
Ok(fds) => {
if let Err(e) = self.device.enable_msix(fds) {
Some(InterruptUpdateAction::EnableMsix) => {
if let Some(msix) = &self.interrupt.msix {
let mut irq_fds: Vec<&EventFd> = Vec::new();
for i in 0..msix.bar.table_entries.len() {
if let Some(eventfd) =
msix.interrupt_source_group.notifier(i as InterruptIndex)
{
irq_fds.push(eventfd);
} else {
return Err(VfioPciError::UpdateMsiEventFd);
}
}
if let Err(e) = self.device.enable_msix(irq_fds) {
warn!("Could not enable MSI-X: {}", e);
}
}
Err(e) => warn!("Could not get IRQ fds: {}", e),
},
}
Some(InterruptUpdateAction::DisableMsix) => {
if let Err(e) = self.device.disable_msix() {
warn!("Could not disable MSI: {}", e);
warn!("Could not disable MSI-X: {}", e);
}
}
_ => {}
}
Ok(())
}
fn find_region(&self, addr: u64) -> Option<MmioRegion> {
@@ -599,11 +506,13 @@ impl VfioPciDevice {
/// # Return value
///
/// This function returns the updated KVM memory slot id.
pub fn map_mmio_regions(&mut self, vm: &Arc<VmFd>, mem_slot: u32) -> Result<u32> {
pub fn map_mmio_regions<F>(&mut self, vm: &Arc<VmFd>, mem_slot: F) -> Result<()>
where
F: Fn() -> u32,
{
let fd = self.device.as_raw_fd();
let mut new_mem_slot = mem_slot;
for region in self.mmio_regions.iter() {
for region in self.mmio_regions.iter_mut() {
// We want to skip the mapping of the BAR containing the MSI-X
// table even if it is mappable. The reason is we need to trap
// any access to the MSI-X table and update the GSI routing
@@ -645,8 +554,9 @@ impl VfioPciDevice {
continue;
}
let slot = mem_slot();
let mem_region = kvm_userspace_memory_region {
slot: new_mem_slot as u32,
slot,
guest_phys_addr: region.start.raw_value() + mmap_offset,
memory_size: mmap_size as u64,
userspace_addr: host_addr as u64,
@@ -658,22 +568,73 @@ impl VfioPciDevice {
vm.set_user_memory_region(mem_region)
.map_err(VfioPciError::MapRegionGuest)?;
}
new_mem_slot += 1;
// Update the region with memory mapped info.
region.mem_slot = Some(slot);
region.host_addr = Some(host_addr as u64);
region.mmap_size = Some(mmap_size as usize);
}
}
Ok(new_mem_slot)
Ok(())
}
pub fn unmap_mmio_regions(&mut self) {
for region in self.mmio_regions.iter() {
if let (Some(host_addr), Some(mmap_size), Some(mem_slot)) =
(region.host_addr, region.mmap_size, region.mem_slot)
{
let (mmap_offset, _) = self.device.get_region_mmap(region.index);
// Remove region from KVM
let kvm_region = kvm_userspace_memory_region {
slot: mem_slot,
guest_phys_addr: region.start.raw_value() + mmap_offset,
memory_size: 0,
userspace_addr: host_addr,
flags: 0,
};
// Safe because the guest regions are guaranteed not to overlap.
if let Err(e) = unsafe { self.vm_fd.set_user_memory_region(kvm_region) } {
error!(
"Could not remove the userspace memory region from KVM: {}",
e
);
}
let ret = unsafe { libc::munmap(host_addr as *mut libc::c_void, mmap_size) };
if ret != 0 {
error!(
"Could not unmap region {}, error:{}",
region.index,
io::Error::last_os_error()
);
}
}
}
}
pub fn update_memory(&self, new_region: &Arc<GuestRegionMmap>) -> Result<()> {
self.device
.extend_dma_map(new_region)
.map_err(VfioPciError::UpdateMemory)
}
}
impl Drop for VfioPciDevice {
fn drop(&mut self) {
if self.interrupt.msi.is_some() && self.device.disable_msi().is_err() {
error!("Could not disable MSI");
self.unmap_mmio_regions();
if let Some(msix) = &self.interrupt.msix {
if msix.bar.enabled() && self.device.disable_msix().is_err() {
error!("Could not disable MSI-X");
}
}
if self.interrupt.msix.is_some() && self.device.disable_msix().is_err() {
error!("Could not disable MSI-X");
if let Some(msi) = &self.interrupt.msi {
if msi.cfg.enabled() && self.device.disable_msi().is_err() {
error!("Could not disable MSI");
}
}
if self.device.unset_dma_map().is_err() {
@@ -800,7 +761,7 @@ impl PciDevice for VfioPciDevice {
let msb_bar_offset: u32 = PCI_CONFIG_BAR_OFFSET + (bar_id + 1) * 4;
self.vfio_pci_configuration
.write_config_dword(msb_bar_offset, msb_size);
.write_config_dword(msb_size, msb_bar_offset);
msb_size = self
.vfio_pci_configuration
@@ -869,7 +830,11 @@ impl PciDevice for VfioPciDevice {
self.mmio_regions.push(MmioRegion {
start: bar_addr,
length: region_size,
type_: region_type,
index: bar_id as u32,
mem_slot: None,
host_addr: None,
mmap_size: None,
});
bar_id += 1;
@@ -885,6 +850,26 @@ impl PciDevice for VfioPciDevice {
Ok(ranges)
}
fn free_bars(
&mut self,
allocator: &mut SystemAllocator,
) -> std::result::Result<(), PciDeviceError> {
for region in self.mmio_regions.iter() {
match region.type_ {
PciBarRegionType::IORegion => {
allocator.free_io_addresses(region.start, region.length);
}
PciBarRegionType::Memory32BitRegion => {
allocator.free_mmio_hole_addresses(region.start, region.length);
}
PciBarRegionType::Memory64BitRegion => {
allocator.free_mmio_addresses(region.start, region.length);
}
}
}
Ok(())
}
fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]) {
// When the guest wants to write to a BAR, we trap it into
// our local configuration space. We're not reprogramming
@@ -901,8 +886,6 @@ impl PciDevice for VfioPciDevice {
}
let reg = (reg_idx * PCI_CONFIG_REGISTER_SIZE) as u64;
self.device
.region_write(VFIO_PCI_CONFIG_REGION_INDEX, data, reg + offset);
// If the MSI or MSI-X capabilities are accessed, we need to
// update our local cache accordingly.
@@ -917,14 +900,27 @@ impl PciDevice for VfioPciDevice {
}
}
PciCapabilityID::MSIX => {
self.update_msix_capabilities(cap_offset, data);
if let Err(e) = self.update_msix_capabilities(cap_offset, data) {
error!("Could not update MSI-X capabilities: {}", e);
}
}
_ => {}
}
}
// Make sure to write to the device's PCI config space after MSI/MSI-X
// interrupts have been enabled/disabled. In case of MSI, when the
// interrupts are enabled through VFIO (using VFIO_DEVICE_SET_IRQS),
// the MSI Enable bit in the MSI capability structure found in the PCI
// config space is disabled by default. That's why when the guest is
// enabling this bit, we first need to enable the MSI interrupts with
// VFIO through VFIO_DEVICE_SET_IRQS ioctl, and only after we can write
// to the device region to update the MSI Enable bit.
self.device
.region_write(VFIO_PCI_CONFIG_REGION_INDEX, data, reg + offset);
}
fn read_config_register(&self, reg_idx: usize) -> u32 {
fn read_config_register(&mut self, reg_idx: usize) -> u32 {
// When reading the BARs, we trap it and return what comes
// from our local configuration space. We want the guest to
// use that and not the VFIO device BARs as it does not map
@@ -958,13 +954,21 @@ impl PciDevice for VfioPciDevice {
& mask
}
fn detect_bar_reprogramming(
&mut self,
reg_idx: usize,
data: &[u8],
) -> Option<BarReprogrammingParams> {
self.configuration.detect_bar_reprogramming(reg_idx, data)
}
fn read_bar(&mut self, base: u64, offset: u64, data: &mut [u8]) {
let addr = base + offset;
if let Some(region) = self.find_region(addr) {
let offset = addr - region.start.raw_value();
if self.interrupt.msix_table_accessed(region.index, offset) {
self.read_msix_table(offset, data);
self.interrupt.msix_read_table(offset, data);
} else {
self.device.region_read(region.index, data, offset);
}
@@ -978,12 +982,60 @@ impl PciDevice for VfioPciDevice {
// If the MSI-X table is written to, we need to update our cache.
if self.interrupt.msix_table_accessed(region.index, offset) {
if let Err(e) = self.update_msix_table(offset, data) {
error!("Could not update MSI-X table: {}", e);
}
self.interrupt.msix_write_table(offset, data);
} else {
self.device.region_write(region.index, data, offset);
}
}
}
fn move_bar(&mut self, old_base: u64, new_base: u64) -> result::Result<(), io::Error> {
for region in self.mmio_regions.iter_mut() {
if region.start.raw_value() == old_base {
region.start = GuestAddress(new_base);
if let Some(mem_slot) = region.mem_slot {
if let Some(host_addr) = region.host_addr {
let (mmap_offset, mmap_size) = self.device.get_region_mmap(region.index);
// Remove old region from KVM
let old_mem_region = kvm_userspace_memory_region {
slot: mem_slot,
guest_phys_addr: old_base + mmap_offset,
memory_size: 0,
userspace_addr: host_addr,
flags: 0,
};
// Safe because the guest regions are guaranteed not to overlap.
unsafe {
self.vm_fd
.set_user_memory_region(old_mem_region)
.map_err(|e| io::Error::from_raw_os_error(e.errno()))?;
}
// Insert new region to KVM
let new_mem_region = kvm_userspace_memory_region {
slot: mem_slot,
guest_phys_addr: new_base + mmap_offset,
memory_size: mmap_size as u64,
userspace_addr: host_addr,
flags: 0,
};
// Safe because the guest regions are guaranteed not to overlap.
unsafe {
self.vm_fd
.set_user_memory_region(new_mem_region)
.map_err(|e| io::Error::from_raw_os_error(e.errno()))?;
}
}
}
}
}
Ok(())
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

View File

@@ -1,25 +0,0 @@
[package]
name = "vhost_rs"
version = "0.1.0"
authors = ["Liu Jiang <gerry@linux.alibaba.com>"]
repository = "https://github.com/rust-vmm/vhost"
license = "Apache-2.0 or BSD-3-Clause"
[features]
default = []
vhost-vsock = []
vhost-kern = ["vm-memory"]
vhost-user-master = []
vhost-user-slave = []
[dependencies]
bitflags = "1.1.0"
libc = "0.2.60"
vmm-sys-util = "0.1.1"
[dependencies.vm-memory]
git = "https://github.com/rust-vmm/vm-memory"
optional = true
[dev-dependencies]
tempfile = "3.1.0"

View File

@@ -1,202 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -1,27 +0,0 @@
// Copyright 2017 The Chromium OS Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,24 +0,0 @@
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@@ -1,10 +0,0 @@
# vHost
A crate to support vhost backend drivers for virtio devices.
## Kernel-based vHost Backend Drivers
The vhost drivers in Linux provide in-kernel virtio device emulation. Normally the hypervisor userspace process emulates I/O accesses from the guest. Vhost puts virtio emulation code into the kernel, taking hypervisor userspace out of the picture. This allows device emulation code to directly call into kernel subsystems instead of performing system calls from userspace. The hypervisor relies on ioctl based interfaces to control those in-kernel vhost drivers, such as vhost-net, vhost-scsi and vhost-vsock etc.
## vHost-user Backend Drivers
The vhost-user protocol is aiming to implement vhost backend drivers in userspace, which complements the ioctl interface used to control the vhost implementation in the Linux kernel. It implements the control plane needed to establish virtqueue sharing with a user space process on the same host. It uses communication over a Unix domain socket to share file descriptors in the ancillary data of the message.
The protocol defines two sides of the communication, master and slave. Master is the application that shares its virtqueues, slave is the consumer of the virtqueues. Master and slave can be either a client (i.e. connecting) or server (listening) in the socket communication.

View File

@@ -1,130 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file.
//! Common traits and structs for vhost-kern and vhost-user backend drivers.
use super::Result;
use std::os::unix::io::RawFd;
use vmm_sys_util::eventfd::EventFd;
/// Maximum number of memory regions supported.
pub const VHOST_MAX_MEMORY_REGIONS: usize = 255;
/// Vring/virtque configuration data.
pub struct VringConfigData {
/// Maximum queue size supported by the driver.
pub queue_max_size: u16,
/// Actual queue size negotiated by the driver.
pub queue_size: u16,
/// Bitmask of vring flags.
pub flags: u32,
/// Descriptor table address.
pub desc_table_addr: u64,
/// Used ring buffer address.
pub used_ring_addr: u64,
/// Available ring buffer address.
pub avail_ring_addr: u64,
/// Optional address for logging.
pub log_addr: Option<u64>,
}
/// Memory region configuration data.
#[derive(Default, Clone, Copy)]
pub struct VhostUserMemoryRegionInfo {
/// Guest physical address of the memory region.
pub guest_phys_addr: u64,
/// Size of the memory region.
pub memory_size: u64,
/// Virtual address in the current process.
pub userspace_addr: u64,
/// Optional offset where region starts in the mapped memory.
pub mmap_offset: u64,
/// Optional file diescriptor for mmap
pub mmap_handle: RawFd,
}
/// An interface for setting up vhost-based backend drivers.
///
/// Vhost-based virtio devices are different from regular virtio devices because the the vhost
/// backend takes care of handling all the data transfer. The device itself only needs to deal with
/// setting up the the backend driver and managing the control channel.
pub trait VhostBackend: std::marker::Sized {
/// Get a bitmask of supported virtio/vhost features.
fn get_features(&mut self) -> Result<u64>;
/// Inform the vhost subsystem which features to enable.
/// This should be a subset of supported features from get_features().
///
/// # Arguments
/// * `features` - Bitmask of features to set.
fn set_features(&mut self, features: u64) -> Result<()>;
/// Set the current process as the owner of the vhost backend.
/// This must be run before any other vhost commands.
fn set_owner(&mut self) -> Result<()>;
/// Used to be sent to request disabling all rings
/// This is no longer used.
fn reset_owner(&mut self) -> Result<()>;
/// Set the guest memory mappings for vhost to use.
fn set_mem_table(&mut self, regions: &[VhostUserMemoryRegionInfo]) -> Result<()>;
/// Set base address for page modification logging.
fn set_log_base(&mut self, base: u64, fd: Option<RawFd>) -> Result<()>;
/// Specify an eventfd file descriptor to signal on log write.
fn set_log_fd(&mut self, fd: RawFd) -> Result<()>;
/// Set the number of descriptors in the vring.
///
/// # Arguments
/// * `queue_index` - Index of the queue to set descriptor count for.
/// * `num` - Number of descriptors in the queue.
fn set_vring_num(&mut self, queue_index: usize, num: u16) -> Result<()>;
/// Set the addresses for a given vring.
///
/// # Arguments
/// * `queue_index` - Index of the queue to set addresses for.
/// * `config_data` - Configuration data for a vring.
fn set_vring_addr(&mut self, queue_index: usize, config_data: &VringConfigData) -> Result<()>;
/// Set the first index to look for available descriptors.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `num` - Index where available descriptors start.
fn set_vring_base(&mut self, queue_index: usize, base: u16) -> Result<()>;
/// Get the available vring base offset.
fn get_vring_base(&mut self, queue_index: usize) -> Result<u32>;
/// Set the eventfd to trigger when buffers have been used by the host.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd to trigger.
fn set_vring_call(&mut self, queue_index: usize, fd: &EventFd) -> Result<()>;
/// Set the eventfd that will be signaled by the guest when buffers are
/// available for the host to process.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from guest.
fn set_vring_kick(&mut self, queue_index: usize, fd: &EventFd) -> Result<()>;
/// Set the eventfd that will be signaled by the guest when error happens.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from guest.
fn set_vring_err(&mut self, queue_index: usize, fd: &EventFd) -> Result<()>;
}

View File

@@ -1,120 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file.
//! Virtio Vhost Backend Drivers
//!
//! Virtio devices use virtqueues to transport data efficiently. Virtqueue is a set of three
//! different single-producer, single-consumer ring structures designed to store generic
//! scatter-gather I/O.
//!
//! Vhost is a mechanism to improve performance of Virtio devices by delegate data plane operations
//! to dedicated IO service processes. Only the configuration, I/O submission notification, and I/O
//! completion interruption are piped through the hypervisor.
//! It uses the same virtqueue layout as Virtio to allow Vhost devices to be mapped directly to
//! Virtio devices. This allows a Vhost device to be accessed directly by a guest OS inside a
//! hypervisor process with an existing Virtio (PCI) driver.
//!
//! The initial vhost implementation is a part of the Linux kernel and uses ioctl interface to
//! communicate with userspace applications. Dedicated kernel worker threads are created to handle
//! IO requests from the guest.
//!
//! Later Vhost-user protocol is introduced to complement the ioctl interface used to control the
//! vhost implementation in the Linux kernel. It implements the control plane needed to establish
//! virtqueues sharing with a user space process on the same host. It uses communication over a
//! Unix domain socket to share file descriptors in the ancillary data of the message.
//! The protocol defines 2 sides of the communication, master and slave. Master is the application
//! that shares its virtqueues. Slave is the consumer of the virtqueues. Master and slave can be
//! either a client (i.e. connecting) or server (listening) in the socket communication.
#![deny(missing_docs)]
#[cfg_attr(
any(feature = "vhost-user-master", feature = "vhost-user-slave"),
macro_use
)]
extern crate bitflags;
extern crate libc;
#[cfg(feature = "vhost-kern")]
extern crate vm_memory;
#[cfg_attr(feature = "vhost-kern", macro_use)]
extern crate vmm_sys_util;
mod backend;
pub use backend::*;
#[cfg(feature = "vhost-kern")]
pub mod vhost_kern;
#[cfg(any(feature = "vhost-user-master", feature = "vhost-user-slave"))]
pub mod vhost_user;
#[cfg(feature = "vhost-vsock")]
pub mod vsock;
/// Error codes for vhost operations
#[derive(Debug)]
pub enum Error {
/// Invalid operations.
InvalidOperation,
/// Invalid guest memory.
InvalidGuestMemory,
/// Invalid guest memory region.
InvalidGuestMemoryRegion,
/// Invalid queue.
InvalidQueue,
/// Invalid descriptor table address.
DescriptorTableAddress,
/// Invalid used address.
UsedAddress,
/// Invalid available address.
AvailAddress,
/// Invalid log address.
LogAddress,
#[cfg(feature = "vhost-kern")]
/// Error opening the vhost backend driver.
VhostOpen(std::io::Error),
#[cfg(feature = "vhost-kern")]
/// Error while running ioctl.
IoctlError(std::io::Error),
/// Error from IO subsystem.
IOError(std::io::Error),
#[cfg(any(feature = "vhost-user-master", feature = "vhost-user-slave"))]
/// Error from the vhost-user subsystem.
VhostUserProtocol(vhost_user::Error),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::InvalidOperation => write!(f, "invalid vhost operations"),
Error::InvalidGuestMemory => write!(f, "invalid guest memory object"),
Error::InvalidGuestMemoryRegion => write!(f, "invalid guest memory region"),
Error::InvalidQueue => write!(f, "invalid virtque"),
Error::DescriptorTableAddress => write!(f, "invalid virtque descriptor talbe address"),
Error::UsedAddress => write!(f, "invalid virtque used talbe address"),
Error::AvailAddress => write!(f, "invalid virtque available talbe address"),
Error::LogAddress => write!(f, "invalid virtque log address"),
Error::IOError(e) => write!(f, "IO error: {}", e),
#[cfg(feature = "vhost-kern")]
Error::VhostOpen(e) => write!(f, "failure in opening vhost file: {}", e),
#[cfg(feature = "vhost-kern")]
Error::IoctlError(e) => write!(f, "failure in vhost ioctl: {}", e),
#[cfg(any(feature = "vhost-user-master", feature = "vhost-user-slave"))]
Error::VhostUserProtocol(e) => write!(f, "vhost-user: {}", e),
}
}
}
#[cfg(any(feature = "vhost-user-master", feature = "vhost-user-slave"))]
impl std::convert::From<vhost_user::Error> for Error {
fn from(err: vhost_user::Error) -> Self {
Error::VhostUserProtocol(err)
}
}
/// Result of vhost operations
pub type Result<T> = std::result::Result<T, Error>;

View File

@@ -1,320 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file.
//! Traits and structs to control Linux in-kernel vhost drivers.
//!
//! The initial vhost implementation is a part of the Linux kernel and uses ioctl interface to
//! communicate with userspace applications. This sub module provides ioctl based interfaces to
//! control the in-kernel net, scsi, vsock vhost drivers.
use std::os::unix::io::{AsRawFd, RawFd};
use std::ptr::null;
use vm_memory::{Address, GuestAddress, GuestMemory, GuestUsize};
use vmm_sys_util::eventfd::EventFd;
use vmm_sys_util::ioctl::{ioctl, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref};
use super::{
Error, Result, VhostBackend, VhostUserMemoryRegionInfo, VringConfigData,
VHOST_MAX_MEMORY_REGIONS,
};
pub mod vhost_binding;
use self::vhost_binding::*;
#[cfg(feature = "vhost-vsock")]
pub mod vsock;
#[inline]
fn ioctl_result<T>(rc: i32, res: T) -> Result<T> {
if rc < 0 {
Err(Error::IoctlError(std::io::Error::last_os_error()))
} else {
Ok(res)
}
}
fn guest_addr(addr: u64) -> GuestAddress {
GuestAddress::new(addr)
}
/// Represent an in-kernel vhost device backend.
pub trait VhostKernBackend<'a>: AsRawFd {
/// Associated type to access the guest's memory.
type M: GuestMemory<'a>;
/// Get the object to access the guest's memory.
fn mem(&self) -> &Self::M;
/// Check whether the ring configuration is valid.
#[allow(clippy::if_same_then_else)]
#[allow(clippy::needless_bool)]
fn is_valid(
&self,
queue_max_size: u16,
queue_size: u16,
desc_addr: GuestAddress,
avail_addr: GuestAddress,
used_addr: GuestAddress,
) -> bool {
let desc_table_size = 16 * u64::from(queue_size) as GuestUsize;
let avail_ring_size = 6 + 2 * u64::from(queue_size) as GuestUsize;
let used_ring_size = 6 + 8 * u64::from(queue_size) as GuestUsize;
if queue_size > queue_max_size || queue_size == 0 || (queue_size & (queue_size - 1)) != 0 {
false
} else if desc_addr
.checked_add(desc_table_size)
.map_or(true, |v| !self.mem().address_in_range(v))
{
false
} else if avail_addr
.checked_add(avail_ring_size)
.map_or(true, |v| !self.mem().address_in_range(v))
{
false
} else if used_addr
.checked_add(used_ring_size)
.map_or(true, |v| !self.mem().address_in_range(v))
{
false
} else {
true
}
}
}
impl<'a, T: VhostKernBackend<'a>> VhostBackend for T {
/// Set the current process as the owner of this file descriptor.
/// This must be run before any other vhost ioctls.
fn set_owner(&mut self) -> Result<()> {
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl(self, VHOST_SET_OWNER()) };
ioctl_result(ret, ())
}
fn reset_owner(&mut self) -> Result<()> {
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl(self, VHOST_RESET_OWNER()) };
ioctl_result(ret, ())
}
/// Get a bitmask of supported virtio/vhost features.
fn get_features(&mut self) -> Result<u64> {
let mut avail_features: u64 = 0;
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_mut_ref(self, VHOST_GET_FEATURES(), &mut avail_features) };
ioctl_result(ret, avail_features)
}
/// Inform the vhost subsystem which features to enable. This should be a subset of
/// supported features from VHOST_GET_FEATURES.
///
/// # Arguments
/// * `features` - Bitmask of features to set.
fn set_features(&mut self, features: u64) -> Result<()> {
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_FEATURES(), &features) };
ioctl_result(ret, ())
}
/// Set the guest memory mappings for vhost to use.
fn set_mem_table(&mut self, regions: &[VhostUserMemoryRegionInfo]) -> Result<()> {
if regions.is_empty() || regions.len() > VHOST_MAX_MEMORY_REGIONS {
return Err(Error::InvalidGuestMemory);
}
let mut vhost_memory = VhostMemory::new(regions.len() as u16);
for (index, region) in regions.iter().enumerate() {
vhost_memory.set_region(
index as u32,
&vhost_memory_region {
guest_phys_addr: region.guest_phys_addr,
memory_size: region.memory_size,
userspace_addr: region.userspace_addr,
flags_padding: 0u64,
},
)?;
}
// This ioctl is called with a pointer that is valid for the lifetime
// of this function. The kernel will make its own copy of the memory
// tables. As always, check the return value.
let ret = unsafe { ioctl_with_ptr(self, VHOST_SET_MEM_TABLE(), vhost_memory.as_ptr()) };
ioctl_result(ret, ())
}
/// Set base address for page modification logging.
///
/// # Arguments
/// * `base` - Base address for page modification logging.
fn set_log_base(&mut self, base: u64, fd: Option<RawFd>) -> Result<()> {
if fd.is_some() {
return Err(Error::LogAddress);
}
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_LOG_BASE(), &base) };
ioctl_result(ret, ())
}
/// Specify an eventfd file descriptor to signal on log write.
fn set_log_fd(&mut self, fd: RawFd) -> Result<()> {
// This ioctl is called on a valid vhost fd and has its return value checked.
let val: i32 = fd;
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_LOG_FD(), &val) };
ioctl_result(ret, ())
}
/// Set the number of descriptors in the vring.
///
/// # Arguments
/// * `queue_index` - Index of the queue to set descriptor count for.
/// * `num` - Number of descriptors in the queue.
fn set_vring_num(&mut self, queue_index: usize, num: u16) -> Result<()> {
let vring_state = vhost_vring_state {
index: queue_index as u32,
num: u32::from(num),
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_NUM(), &vring_state) };
ioctl_result(ret, ())
}
/// Set the addresses for a given vring.
///
/// # Arguments
/// * `queue_max_size` - Maximum queue size supported by the device.
/// * `queue_size` - Actual queue size negotiated by the driver.
/// * `queue_index` - Index of the queue to set addresses for.
/// * `flags` - Bitmask of vring flags.
/// * `desc_table_addr` - Descriptor table address.
/// * `used_ring_addr` - Used ring buffer address.
/// * `avail_ring_addr` - Available ring buffer address.
/// * `log_addr` - Optional address for logging.
fn set_vring_addr(&mut self, queue_index: usize, config_data: &VringConfigData) -> Result<()> {
if !self.is_valid(
config_data.queue_max_size,
config_data.queue_size,
guest_addr(config_data.desc_table_addr),
guest_addr(config_data.used_ring_addr),
guest_addr(config_data.avail_ring_addr),
) {
return Err(Error::InvalidQueue);
}
let desc_addr = self
.mem()
.get_host_address(guest_addr(config_data.desc_table_addr))
.ok_or(Error::DescriptorTableAddress)?;
let used_addr = self
.mem()
.get_host_address(guest_addr(config_data.used_ring_addr))
.ok_or(Error::UsedAddress)?;
let avail_addr = self
.mem()
.get_host_address(guest_addr(config_data.avail_ring_addr))
.ok_or(Error::AvailAddress)?;
let log_addr = match config_data.log_addr {
None => null(),
Some(a) => self
.mem()
.get_host_address(guest_addr(a))
.ok_or(Error::LogAddress)?,
};
let vring_addr = vhost_vring_addr {
index: queue_index as u32,
flags: config_data.flags,
desc_user_addr: desc_addr as u64,
used_user_addr: used_addr as u64,
avail_user_addr: avail_addr as u64,
log_guest_addr: log_addr as u64,
};
// This ioctl is called on a valid vhost fd and has its
// return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_ADDR(), &vring_addr) };
ioctl_result(ret, ())
}
/// Set the first index to look for available descriptors.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `num` - Index where available descriptors start.
fn set_vring_base(&mut self, queue_index: usize, base: u16) -> Result<()> {
let vring_state = vhost_vring_state {
index: queue_index as u32,
num: u32::from(base),
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_BASE(), &vring_state) };
ioctl_result(ret, ())
}
/// Get a bitmask of supported virtio/vhost features.
fn get_vring_base(&mut self, queue_index: usize) -> Result<u32> {
let vring_state = vhost_vring_state {
index: queue_index as u32,
num: 0,
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_GET_VRING_BASE(), &vring_state) };
ioctl_result(ret, vring_state.num)
}
/// Set the eventfd to trigger when buffers have been used by the host.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd to trigger.
fn set_vring_call(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_CALL(), &vring_file) };
ioctl_result(ret, ())
}
/// Set the eventfd that will be signaled by the guest when buffers are
/// available for the host to process.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from guest.
fn set_vring_kick(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_KICK(), &vring_file) };
ioctl_result(ret, ())
}
/// Set the eventfd to signal an error from the vhost backend.
///
/// # Arguments
/// * `queue_index` - Index of the queue to modify.
/// * `fd` - EventFd that will be signaled from the backend.
fn set_vring_err(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let vring_file = vhost_vring_file {
index: queue_index as u32,
fd: fd.as_raw_fd(),
};
// This ioctl is called on a valid vhost fd and has its return value checked.
let ret = unsafe { ioctl_with_ref(self, VHOST_SET_VRING_ERR(), &vring_file) };
ioctl_result(ret, ())
}
}

View File

@@ -1,405 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file.
/* Auto-generated by bindgen then manually edited for simplicity */
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(missing_docs)]
use std::os::raw;
use {Error, Result};
pub const VHOST: raw::c_uint = 0xaf;
pub const VHOST_VRING_F_LOG: raw::c_uint = 0;
pub const VHOST_ACCESS_RO: raw::c_uint = 1;
pub const VHOST_ACCESS_WO: raw::c_uint = 2;
pub const VHOST_ACCESS_RW: raw::c_uint = 3;
pub const VHOST_IOTLB_MISS: raw::c_uint = 1;
pub const VHOST_IOTLB_UPDATE: raw::c_uint = 2;
pub const VHOST_IOTLB_INVALIDATE: raw::c_uint = 3;
pub const VHOST_IOTLB_ACCESS_FAIL: raw::c_uint = 4;
pub const VHOST_IOTLB_MSG: raw::c_uint = 1;
pub const VHOST_PAGE_SIZE: raw::c_uint = 4096;
pub const VHOST_VIRTIO: raw::c_uint = 175;
pub const VHOST_VRING_LITTLE_ENDIAN: raw::c_uint = 0;
pub const VHOST_VRING_BIG_ENDIAN: raw::c_uint = 1;
pub const VHOST_F_LOG_ALL: raw::c_uint = 26;
pub const VHOST_NET_F_VIRTIO_NET_HDR: raw::c_uint = 27;
pub const VHOST_SCSI_ABI_VERSION: raw::c_uint = 1;
ioctl_ior_nr!(VHOST_GET_FEATURES, VHOST, 0x00, raw::c_ulonglong);
ioctl_iow_nr!(VHOST_SET_FEATURES, VHOST, 0x00, raw::c_ulonglong);
ioctl_io_nr!(VHOST_SET_OWNER, VHOST, 0x01);
ioctl_io_nr!(VHOST_RESET_OWNER, VHOST, 0x02);
ioctl_iow_nr!(VHOST_SET_MEM_TABLE, VHOST, 0x03, vhost_memory);
ioctl_iow_nr!(VHOST_SET_LOG_BASE, VHOST, 0x04, raw::c_ulonglong);
ioctl_iow_nr!(VHOST_SET_LOG_FD, VHOST, 0x07, raw::c_int);
ioctl_iow_nr!(VHOST_SET_VRING_NUM, VHOST, 0x10, vhost_vring_state);
ioctl_iow_nr!(VHOST_SET_VRING_ADDR, VHOST, 0x11, vhost_vring_addr);
ioctl_iow_nr!(VHOST_SET_VRING_BASE, VHOST, 0x12, vhost_vring_state);
ioctl_iowr_nr!(VHOST_GET_VRING_BASE, VHOST, 0x12, vhost_vring_state);
ioctl_iow_nr!(VHOST_SET_VRING_KICK, VHOST, 0x20, vhost_vring_file);
ioctl_iow_nr!(VHOST_SET_VRING_CALL, VHOST, 0x21, vhost_vring_file);
ioctl_iow_nr!(VHOST_SET_VRING_ERR, VHOST, 0x22, vhost_vring_file);
ioctl_iow_nr!(vhost_SET_BACKEND, VHOST, 0x30, vhost_vring_file);
ioctl_iow_nr!(VHOST_SCSI_SET_ENDPOINT, VHOST, 0x40, vhost_scsi_target);
ioctl_iow_nr!(VHOST_SCSI_CLEAR_ENDPOINT, VHOST, 0x41, vhost_scsi_target);
ioctl_iow_nr!(VHOST_SCSI_GET_ABI_VERSION, VHOST, 0x42, raw::c_int);
ioctl_iow_nr!(VHOST_SCSI_SET_EVENTS_MISSED, VHOST, 0x43, raw::c_uint);
ioctl_iow_nr!(VHOST_SCSI_GET_EVENTS_MISSED, VHOST, 0x44, raw::c_uint);
ioctl_iow_nr!(VHOST_VSOCK_SET_GUEST_CID, VHOST, 0x60, raw::c_ulonglong);
ioctl_iow_nr!(VHOST_VSOCK_SET_RUNNING, VHOST, 0x61, raw::c_int);
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub fn new() -> Self {
__IncompleteArrayField(::std::marker::PhantomData)
}
#[inline]
#[allow(clippy::trivially_copy_pass_by_ref)]
#[allow(clippy::useless_transmute)]
pub unsafe fn as_ptr(&self) -> *const T {
::std::mem::transmute(self)
}
#[inline]
#[allow(clippy::useless_transmute)]
pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
::std::mem::transmute(self)
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
}
}
impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
impl<T> ::std::clone::Clone for __IncompleteArrayField<T> {
#[inline]
fn clone(&self) -> Self {
Self::new()
}
}
impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct vhost_vring_state {
pub index: raw::c_uint,
pub num: raw::c_uint,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct vhost_vring_file {
pub index: raw::c_uint,
pub fd: raw::c_int,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct vhost_vring_addr {
pub index: raw::c_uint,
pub flags: raw::c_uint,
pub desc_user_addr: raw::c_ulonglong,
pub used_user_addr: raw::c_ulonglong,
pub avail_user_addr: raw::c_ulonglong,
pub log_guest_addr: raw::c_ulonglong,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct vhost_iotlb_msg {
pub iova: raw::c_ulonglong,
pub size: raw::c_ulonglong,
pub uaddr: raw::c_ulonglong,
pub perm: raw::c_uchar,
pub type_: raw::c_uchar,
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct vhost_msg {
pub type_: raw::c_int,
pub __bindgen_anon_1: vhost_msg__bindgen_ty_1,
}
impl Default for vhost_msg {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union vhost_msg__bindgen_ty_1 {
pub iotlb: vhost_iotlb_msg,
pub padding: [raw::c_uchar; 64usize],
_bindgen_union_align: [u64; 8usize],
}
impl Default for vhost_msg__bindgen_ty_1 {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct vhost_memory_region {
pub guest_phys_addr: raw::c_ulonglong,
pub memory_size: raw::c_ulonglong,
pub userspace_addr: raw::c_ulonglong,
pub flags_padding: raw::c_ulonglong,
}
#[repr(C)]
#[derive(Debug, Default, Clone)]
pub struct vhost_memory {
pub nregions: raw::c_uint,
pub padding: raw::c_uint,
pub regions: __IncompleteArrayField<vhost_memory_region>,
__force_alignment: [u64; 0],
}
#[repr(C)]
#[derive(Copy, Clone)]
pub struct vhost_scsi_target {
pub abi_version: raw::c_int,
pub vhost_wwpn: [raw::c_char; 224usize],
pub vhost_tpgt: raw::c_ushort,
pub reserved: raw::c_ushort,
}
impl Default for vhost_scsi_target {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
/// Helper to support vhost::set_mem_table()
pub struct VhostMemory {
buf: Vec<vhost_memory>,
}
impl VhostMemory {
// Limit number of regions to u16 to simplify error handling
pub fn new(entries: u16) -> Self {
let size = std::mem::size_of::<vhost_memory_region>() * entries as usize;
let count = (size + 2 * std::mem::size_of::<vhost_memory>() - 1)
/ std::mem::size_of::<vhost_memory>();
let mut buf: Vec<vhost_memory> = vec![Default::default(); count];
buf[0].nregions = u32::from(entries);
VhostMemory { buf }
}
pub fn as_ptr(&self) -> *const char {
&self.buf[0] as *const vhost_memory as *const char
}
pub fn get_header(&self) -> &vhost_memory {
&self.buf[0]
}
pub fn get_region(&self, index: u32) -> Option<&vhost_memory_region> {
if index >= self.buf[0].nregions {
return None;
}
// Safe because we have allocated enough space nregions
let regions = unsafe { self.buf[0].regions.as_slice(self.buf[0].nregions as usize) };
Some(&regions[index as usize])
}
pub fn set_region(&mut self, index: u32, region: &vhost_memory_region) -> Result<()> {
if index >= self.buf[0].nregions {
return Err(Error::InvalidGuestMemory);
}
// Safe because we have allocated enough space nregions and checked the index.
let regions = unsafe { self.buf[0].regions.as_mut_slice(index as usize + 1) };
regions[index as usize] = *region;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bindgen_test_layout_vhost_vring_state() {
assert_eq!(
::std::mem::size_of::<vhost_vring_state>(),
8usize,
concat!("Size of: ", stringify!(vhost_vring_state))
);
assert_eq!(
::std::mem::align_of::<vhost_vring_state>(),
4usize,
concat!("Alignment of ", stringify!(vhost_vring_state))
);
}
#[test]
fn bindgen_test_layout_vhost_vring_file() {
assert_eq!(
::std::mem::size_of::<vhost_vring_file>(),
8usize,
concat!("Size of: ", stringify!(vhost_vring_file))
);
assert_eq!(
::std::mem::align_of::<vhost_vring_file>(),
4usize,
concat!("Alignment of ", stringify!(vhost_vring_file))
);
}
#[test]
fn bindgen_test_layout_vhost_vring_addr() {
assert_eq!(
::std::mem::size_of::<vhost_vring_addr>(),
40usize,
concat!("Size of: ", stringify!(vhost_vring_addr))
);
assert_eq!(
::std::mem::align_of::<vhost_vring_addr>(),
8usize,
concat!("Alignment of ", stringify!(vhost_vring_addr))
);
}
#[test]
fn bindgen_test_layout_vhost_msg__bindgen_ty_1() {
assert_eq!(
::std::mem::size_of::<vhost_msg__bindgen_ty_1>(),
64usize,
concat!("Size of: ", stringify!(vhost_msg__bindgen_ty_1))
);
assert_eq!(
::std::mem::align_of::<vhost_msg__bindgen_ty_1>(),
8usize,
concat!("Alignment of ", stringify!(vhost_msg__bindgen_ty_1))
);
}
#[test]
fn bindgen_test_layout_vhost_msg() {
assert_eq!(
::std::mem::size_of::<vhost_msg>(),
72usize,
concat!("Size of: ", stringify!(vhost_msg))
);
assert_eq!(
::std::mem::align_of::<vhost_msg>(),
8usize,
concat!("Alignment of ", stringify!(vhost_msg))
);
}
#[test]
fn bindgen_test_layout_vhost_memory_region() {
assert_eq!(
::std::mem::size_of::<vhost_memory_region>(),
32usize,
concat!("Size of: ", stringify!(vhost_memory_region))
);
assert_eq!(
::std::mem::align_of::<vhost_memory_region>(),
8usize,
concat!("Alignment of ", stringify!(vhost_memory_region))
);
}
#[test]
fn bindgen_test_layout_vhost_memory() {
assert_eq!(
::std::mem::size_of::<vhost_memory>(),
8usize,
concat!("Size of: ", stringify!(vhost_memory))
);
assert_eq!(
::std::mem::align_of::<vhost_memory>(),
8usize,
concat!("Alignment of ", stringify!(vhost_memory))
);
}
#[test]
fn bindgen_test_layout_vhost_iotlb_msg() {
assert_eq!(
::std::mem::size_of::<vhost_iotlb_msg>(),
32usize,
concat!("Size of: ", stringify!(vhost_iotlb_msg))
);
assert_eq!(
::std::mem::align_of::<vhost_iotlb_msg>(),
8usize,
concat!("Alignment of ", stringify!(vhost_iotlb_msg))
);
}
#[test]
fn bindgen_test_layout_vhost_scsi_target() {
assert_eq!(
::std::mem::size_of::<vhost_scsi_target>(),
232usize,
concat!("Size of: ", stringify!(vhost_scsi_target))
);
assert_eq!(
::std::mem::align_of::<vhost_scsi_target>(),
4usize,
concat!("Alignment of ", stringify!(vhost_scsi_target))
);
}
#[test]
fn test_vhostmemory() {
let mut obj = VhostMemory::new(2);
let region = vhost_memory_region {
guest_phys_addr: 0x1000u64,
memory_size: 0x2000u64,
userspace_addr: 0x300000u64,
flags_padding: 0u64,
};
assert!(obj.get_region(2).is_none());
{
let header = obj.get_header();
assert_eq!(header.nregions, 2u32);
}
{
assert!(obj.set_region(0, &region).is_ok());
assert!(obj.set_region(1, &region).is_ok());
assert!(obj.set_region(2, &region).is_err());
}
let region1 = obj.get_region(1).unwrap();
assert_eq!(region1.guest_phys_addr, 0x1000u64);
assert_eq!(region1.memory_size, 0x2000u64);
assert_eq!(region1.userspace_addr, 0x300000u64);
}
}

View File

@@ -1,84 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or MIT
//
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the THIRD-PARTY file.
//! Kernel-based vsock vhost backend.
use std::fs::{File, OpenOptions};
use std::marker::PhantomData;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRawFd, RawFd};
use super::vhost_binding::{VHOST_VSOCK_SET_GUEST_CID, VHOST_VSOCK_SET_RUNNING};
use super::{ioctl_result, Error, Result, VhostKernBackend};
use libc;
use vm_memory::GuestMemory;
use vmm_sys_util::ioctl::ioctl_with_ref;
const VHOST_PATH: &str = "/dev/vhost-vsock";
/// Handle for running VHOST_VSOCK ioctls.
pub struct Vsock<'a, M: GuestMemory<'a>> {
fd: File,
mem: M,
_phatomdata: PhantomData<&'a M>, // Get rid of unused type parameter `a
}
impl<'a, M: GuestMemory<'a>> Vsock<'a, M> {
/// Open a handle to a new VHOST-VSOCK instance.
pub fn new(mem: &M) -> Result<Self> {
Ok(Vsock {
fd: OpenOptions::new()
.read(true)
.write(true)
.custom_flags(libc::O_CLOEXEC | libc::O_NONBLOCK)
.open(VHOST_PATH)
.map_err(Error::VhostOpen)?,
mem: mem.clone(),
_phatomdata: PhantomData,
})
}
/// Set the CID for the guest. This number is used for routing all data destined for
/// running in the guest. Each guest on a hypervisor must have an unique CID
///
/// # Arguments
/// * `cid` - CID to assign to the guest
pub fn set_guest_cid(&self, cid: u64) -> Result<()> {
let ret = unsafe { ioctl_with_ref(&self.fd, VHOST_VSOCK_SET_GUEST_CID(), &cid) };
ioctl_result(ret, ())
}
/// Tell the VHOST driver to start performing data transfer.
pub fn start(&self) -> Result<()> {
self.set_running(true)
}
/// Tell the VHOST driver to stop performing data transfer.
pub fn stop(&self) -> Result<()> {
self.set_running(false)
}
fn set_running(&self, running: bool) -> Result<()> {
let on: ::std::os::raw::c_int = if running { 1 } else { 0 };
let ret = unsafe { ioctl_with_ref(&self.fd, VHOST_VSOCK_SET_RUNNING(), &on) };
ioctl_result(ret, ())
}
}
impl<'a, M: GuestMemory<'a>> VhostKernBackend<'a> for Vsock<'a, M> {
type M = M;
fn mem(&self) -> &Self::M {
&self.mem
}
}
impl<'a, M: GuestMemory<'a>> AsRawFd for Vsock<'a, M> {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}

View File

@@ -1,737 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Structs for Unix Domain Socket listener and endpoint.
#![allow(dead_code)]
use libc::{c_void, iovec};
use std::io::ErrorKind;
use std::marker::PhantomData;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::{UnixListener, UnixStream};
use std::{mem, slice};
use super::message::*;
use super::sock_ctrl_msg::ScmSocket;
use super::{Error, Result};
/// Unix domain socket listener for accepting incoming connections.
pub struct Listener {
fd: UnixListener,
path: String,
}
impl Listener {
/// Create a unix domain socket listener.
///
/// # Return:
/// * - the new Listener object on success.
/// * - SocketError: failed to create listener socket.
pub fn new(path: &str, unlink: bool) -> Result<Self> {
if unlink {
let _ = std::fs::remove_file(path);
}
let fd = UnixListener::bind(path).map_err(Error::SocketError)?;
Ok(Listener {
fd,
path: path.to_string(),
})
}
/// Accept an incoming connection.
///
/// # Return:
/// * - Some(UnixStream): new UnixStream object if new incoming connection is available.
/// * - None: no incoming connection available.
/// * - SocketError: errors from accept().
pub fn accept(&self) -> Result<Option<UnixStream>> {
loop {
match self.fd.accept() {
Ok((socket, _addr)) => return Ok(Some(socket)),
Err(e) => {
match e.kind() {
// No incoming connection available.
ErrorKind::WouldBlock => return Ok(None),
// New connection closed by peer.
ErrorKind::ConnectionAborted => return Ok(None),
// Interrupted by signals, retry
ErrorKind::Interrupted => continue,
_ => return Err(Error::SocketError(e)),
}
}
}
}
}
/// Change blocking status on the listener.
///
/// # Return:
/// * - () on success.
/// * - SocketError: failure from set_nonblocking().
pub fn set_nonblocking(&self, block: bool) -> Result<()> {
self.fd.set_nonblocking(block).map_err(Error::SocketError)
}
}
impl AsRawFd for Listener {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_raw_fd()
}
}
impl Drop for Listener {
fn drop(&mut self) {
let _ = std::fs::remove_file(self.path.clone());
}
}
/// Unix domain socket endpoint for vhost-user connection.
pub(super) struct Endpoint<R: Req> {
sock: UnixStream,
_r: PhantomData<R>,
}
impl<R: Req> Endpoint<R> {
/// Create a new stream by connecting to server at `str`.
///
/// # Return:
/// * - the new Endpoint object on success.
/// * - SocketConnect: failed to connect to peer.
pub fn connect(path: &str) -> Result<Self> {
let sock = UnixStream::connect(path).map_err(Error::SocketConnect)?;
Ok(Self::from_stream(sock))
}
/// Create an endpoint from a stream object.
pub fn from_stream(sock: UnixStream) -> Self {
Endpoint {
sock,
_r: PhantomData,
}
}
/// Sends bytes from scatter-gather vectors over the socket with optional attached file
/// descriptors.
///
/// # Return:
/// * - number of bytes sent on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
pub fn send_iovec(&mut self, iovs: &[&[u8]], fds: Option<&[RawFd]>) -> Result<usize> {
let rfds = match fds {
Some(rfds) => rfds,
_ => &[],
};
self.sock.send_with_fds(iovs, rfds).map_err(Into::into)
}
/// Sends bytes from a slice over the socket with optional attached file descriptors.
///
/// # Return:
/// * - number of bytes sent on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
pub fn send_slice(&mut self, data: &[u8], fds: Option<&[RawFd]>) -> Result<usize> {
self.send_iovec(&[data], fds)
}
/// Sends a header-only message with optional attached file descriptors.
///
/// # Return:
/// * - number of bytes sent on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
pub fn send_header(
&mut self,
hdr: &VhostUserMsgHeader<R>,
fds: Option<&[RawFd]>,
) -> Result<()> {
// Safe because there can't be other mutable referance to hdr.
let iovs = unsafe {
[slice::from_raw_parts(
hdr as *const VhostUserMsgHeader<R> as *const u8,
mem::size_of::<VhostUserMsgHeader<R>>(),
)]
};
let bytes = self.send_iovec(&iovs[..], fds)?;
if bytes != mem::size_of::<VhostUserMsgHeader<R>>() {
return Err(Error::PartialMessage);
}
Ok(())
}
/// Send a message with header and body. Optional file descriptors may be attached to
/// the message.
///
/// # Return:
/// * - number of bytes sent on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
pub fn send_message<T: Sized>(
&mut self,
hdr: &VhostUserMsgHeader<R>,
body: &T,
fds: Option<&[RawFd]>,
) -> Result<()> {
// Safe because there can't be other mutable referance to hdr and body.
let iovs = unsafe {
[
slice::from_raw_parts(
hdr as *const VhostUserMsgHeader<R> as *const u8,
mem::size_of::<VhostUserMsgHeader<R>>(),
),
slice::from_raw_parts(body as *const T as *const u8, mem::size_of::<T>()),
]
};
let bytes = self.send_iovec(&iovs[..], fds)?;
if bytes != mem::size_of::<VhostUserMsgHeader<R>>() + mem::size_of::<T>() {
return Err(Error::PartialMessage);
}
Ok(())
}
/// Send a message with header, body and payload. Optional file descriptors
/// may also be attached to the message.
///
/// # Return:
/// * - number of bytes sent on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - OversizedMsg: message size is too big.
/// * - PartialMessage: received a partial message.
/// * - IncorrectFds: wrong number of attached fds.
pub fn send_message_with_payload<T: Sized, P: Sized>(
&mut self,
hdr: &VhostUserMsgHeader<R>,
body: &T,
payload: &[P],
fds: Option<&[RawFd]>,
) -> Result<()> {
let len = payload.len() * mem::size_of::<P>();
if len > MAX_MSG_SIZE - mem::size_of::<T>() {
return Err(Error::OversizedMsg);
}
if let Some(fd_arr) = fds {
if fd_arr.len() > MAX_ATTACHED_FD_ENTRIES {
return Err(Error::IncorrectFds);
}
}
// Safe because there can't be other mutable reference to hdr, body and payload.
let iovs = unsafe {
[
slice::from_raw_parts(
hdr as *const VhostUserMsgHeader<R> as *const u8,
mem::size_of::<VhostUserMsgHeader<R>>(),
),
slice::from_raw_parts(body as *const T as *const u8, mem::size_of::<T>()),
slice::from_raw_parts(payload.as_ptr() as *const u8, len),
]
};
let total = mem::size_of::<VhostUserMsgHeader<R>>() + mem::size_of::<T>() + len;
let len = self.send_iovec(&iovs, fds)?;
if len != total {
return Err(Error::PartialMessage);
}
Ok(())
}
/// Reads bytes from the socket into the given scatter/gather vectors.
///
/// # Return:
/// * - (number of bytes received, buf) on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
pub fn recv_data(&mut self, len: usize) -> Result<(usize, Vec<u8>)> {
let mut rbuf = vec![0u8; len];
let mut iovs = [iovec {
iov_base: rbuf.as_mut_ptr() as *mut c_void,
iov_len: len,
}];
let (bytes, _) = self.sock.recv_with_fds(&mut iovs, &mut [])?;
Ok((bytes, rbuf))
}
/// Reads bytes from the socket into the given scatter/gather vectors with optional attached
/// file descriptors.
///
/// The underlying communication channel is a Unix domain socket in STREAM mode. It's a little
/// tricky to pass file descriptors through such a communication channel. Let's assume that a
/// sender sending a message with some file descriptors attached. To successfully receive those
/// attached file descriptors, the receiver must obey following rules:
/// 1) file descriptors are attached to a message.
/// 2) message(packet) boundaries must be respected on the receive side.
/// In other words, recvmsg() operations must not cross the packet boundary, otherwise the
/// attached file descriptors will get lost.
///
/// # Return:
/// * - (number of bytes received, [received fds]) on success
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
pub fn recv_into_iovec(&mut self, iovs: &mut [iovec]) -> Result<(usize, Option<Vec<RawFd>>)> {
let mut fd_array = vec![0; MAX_ATTACHED_FD_ENTRIES];
let (bytes, fds) = self.sock.recv_with_fds(iovs, &mut fd_array)?;
let rfds = match fds {
0 => None,
n => {
let mut fds = Vec::with_capacity(n);
fds.extend_from_slice(&fd_array[0..n]);
Some(fds)
}
};
Ok((bytes, rfds))
}
/// Reads bytes from the socket into a new buffer with optional attached
/// file descriptors. Received file descriptors are set close-on-exec.
///
/// # Return:
/// * - (number of bytes received, buf, [received fds]) on success.
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
pub fn recv_into_buf(
&mut self,
buf_size: usize,
) -> Result<(usize, Vec<u8>, Option<Vec<RawFd>>)> {
let mut buf = vec![0u8; buf_size];
let (bytes, rfds) = {
let mut iovs = [iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf_size,
}];
self.recv_into_iovec(&mut iovs)?
};
Ok((bytes, buf, rfds))
}
/// Receive a header-only message with optional attached file descriptors.
/// Note, only the first MAX_ATTACHED_FD_ENTRIES file descriptors will be
/// accepted and all other file descriptor will be discard silently.
///
/// # Return:
/// * - (message header, [received fds]) on success.
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
/// * - InvalidMessage: received a invalid message.
pub fn recv_header(&mut self) -> Result<(VhostUserMsgHeader<R>, Option<Vec<RawFd>>)> {
let mut hdr = VhostUserMsgHeader::default();
let mut iovs = [iovec {
iov_base: (&mut hdr as *mut VhostUserMsgHeader<R>) as *mut c_void,
iov_len: mem::size_of::<VhostUserMsgHeader<R>>(),
}];
let (bytes, rfds) = self.recv_into_iovec(&mut iovs[..])?;
if bytes != mem::size_of::<VhostUserMsgHeader<R>>() {
return Err(Error::PartialMessage);
} else if !hdr.is_valid() {
return Err(Error::InvalidMessage);
}
Ok((hdr, rfds))
}
/// Receive a message with optional attached file descriptors.
/// Note, only the first MAX_ATTACHED_FD_ENTRIES file descriptors will be
/// accepted and all other file descriptor will be discard silently.
///
/// # Return:
/// * - (message header, message body, [received fds]) on success.
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
/// * - InvalidMessage: received a invalid message.
pub fn recv_body<T: Sized + Default + VhostUserMsgValidator>(
&mut self,
) -> Result<(VhostUserMsgHeader<R>, T, Option<Vec<RawFd>>)> {
let mut hdr = VhostUserMsgHeader::default();
let mut body: T = Default::default();
let mut iovs = [
iovec {
iov_base: (&mut hdr as *mut VhostUserMsgHeader<R>) as *mut c_void,
iov_len: mem::size_of::<VhostUserMsgHeader<R>>(),
},
iovec {
iov_base: (&mut body as *mut T) as *mut c_void,
iov_len: mem::size_of::<T>(),
},
];
let (bytes, rfds) = self.recv_into_iovec(&mut iovs[..])?;
let total = mem::size_of::<VhostUserMsgHeader<R>>() + mem::size_of::<T>();
if bytes != total {
return Err(Error::PartialMessage);
} else if !hdr.is_valid() || !body.is_valid() {
return Err(Error::InvalidMessage);
}
Ok((hdr, body, rfds))
}
/// Receive a message with header and optional content. Callers need to
/// pre-allocate a big enough buffer to receive the message body and
/// optional payload. If there are attached file descriptor associated
/// with the message, the first MAX_ATTACHED_FD_ENTRIES file descriptors
/// will be accepted and all other file descriptor will be discard
/// silently.
///
/// # Return:
/// * - (message header, message size, [received fds]) on success.
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
/// * - InvalidMessage: received a invalid message.
pub fn recv_body_into_buf(
&mut self,
buf: &mut [u8],
) -> Result<(VhostUserMsgHeader<R>, usize, Option<Vec<RawFd>>)> {
let mut hdr = VhostUserMsgHeader::default();
let mut iovs = [
iovec {
iov_base: (&mut hdr as *mut VhostUserMsgHeader<R>) as *mut c_void,
iov_len: mem::size_of::<VhostUserMsgHeader<R>>(),
},
iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf.len(),
},
];
let (bytes, rfds) = self.recv_into_iovec(&mut iovs[..])?;
if bytes < mem::size_of::<VhostUserMsgHeader<R>>() {
return Err(Error::PartialMessage);
} else if !hdr.is_valid() {
return Err(Error::InvalidMessage);
}
Ok((hdr, bytes - mem::size_of::<VhostUserMsgHeader<R>>(), rfds))
}
/// Receive a message with optional payload and attached file descriptors.
/// Note, only the first MAX_ATTACHED_FD_ENTRIES file descriptors will be
/// accepted and all other file descriptor will be discard silently.
///
/// # Return:
/// * - (message header, message body, size of payload, [received fds]) on success.
/// * - SocketRetry: temporary error caused by signals or short of resources.
/// * - SocketBroken: the underline socket is broken.
/// * - SocketError: other socket related errors.
/// * - PartialMessage: received a partial message.
/// * - InvalidMessage: received a invalid message.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::type_complexity))]
pub fn recv_payload_into_buf<T: Sized + Default + VhostUserMsgValidator>(
&mut self,
buf: &mut [u8],
) -> Result<(VhostUserMsgHeader<R>, T, usize, Option<Vec<RawFd>>)> {
let mut hdr = VhostUserMsgHeader::default();
let mut body: T = Default::default();
let mut iovs = [
iovec {
iov_base: (&mut hdr as *mut VhostUserMsgHeader<R>) as *mut c_void,
iov_len: mem::size_of::<VhostUserMsgHeader<R>>(),
},
iovec {
iov_base: (&mut body as *mut T) as *mut c_void,
iov_len: mem::size_of::<T>(),
},
iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf.len(),
},
];
let (bytes, rfds) = self.recv_into_iovec(&mut iovs[..])?;
let total = mem::size_of::<VhostUserMsgHeader<R>>() + mem::size_of::<T>();
if bytes < total {
return Err(Error::PartialMessage);
} else if !hdr.is_valid() || !body.is_valid() {
return Err(Error::InvalidMessage);
}
Ok((hdr, body, bytes - total, rfds))
}
/// Close all raw file descriptors.
pub fn close_rfds(rfds: Option<Vec<RawFd>>) {
if let Some(fds) = rfds {
for fd in fds {
// safe because the rawfds are valid and we don't care about the result.
let _ = unsafe { libc::close(fd) };
}
}
}
}
impl<T: Req> AsRawFd for Endpoint<T> {
fn as_raw_fd(&self) -> RawFd {
self.sock.as_raw_fd()
}
}
#[cfg(test)]
mod tests {
extern crate tempfile;
use self::tempfile::tempfile;
use super::*;
use libc;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom, Write};
use std::os::unix::io::FromRawFd;
const UNIX_SOCKET_LISTENER: &'static str = "/tmp/vhost_user_test_rust_listener";
const UNIX_SOCKET_CONNECTION: &'static str = "/tmp/vhost_user_test_rust_connection";
const UNIX_SOCKET_DATA: &'static str = "/tmp/vhost_user_test_rust_data";
const UNIX_SOCKET_FD: &'static str = "/tmp/vhost_user_test_rust_fd";
const UNIX_SOCKET_SEND: &'static str = "/tmp/vhost_user_test_rust_send";
#[test]
fn create_listener() {
let _ = Listener::new(UNIX_SOCKET_LISTENER, true).unwrap();
}
#[test]
fn accept_connection() {
let listener = Listener::new(UNIX_SOCKET_CONNECTION, true).unwrap();
listener.set_nonblocking(true).unwrap();
// accept on a fd without incoming connection
let conn = listener.accept().unwrap();
assert!(conn.is_none());
listener.set_nonblocking(true).unwrap();
// accept on a closed fd
unsafe {
libc::close(listener.as_raw_fd());
}
let conn2 = listener.accept();
assert!(conn2.is_err());
}
#[test]
fn send_data() {
let listener = Listener::new(UNIX_SOCKET_DATA, true).unwrap();
listener.set_nonblocking(true).unwrap();
let mut master = Endpoint::<MasterReq>::connect(UNIX_SOCKET_DATA).unwrap();
let sock = listener.accept().unwrap().unwrap();
let mut slave = Endpoint::<MasterReq>::from_stream(sock);
let buf1 = vec![0x1, 0x2, 0x3, 0x4];
let mut len = master.send_slice(&buf1[..], None).unwrap();
assert_eq!(len, 4);
let (bytes, buf2, _) = slave.recv_into_buf(0x1000).unwrap();
assert_eq!(bytes, 4);
assert_eq!(&buf1[..], &buf2[..bytes]);
len = master.send_slice(&buf1[..], None).unwrap();
assert_eq!(len, 4);
let (bytes, buf2, _) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[..2], &buf2[..]);
let (bytes, buf2, _) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[2..], &buf2[..]);
}
#[test]
fn send_fd() {
let listener = Listener::new(UNIX_SOCKET_FD, true).unwrap();
listener.set_nonblocking(true).unwrap();
let mut master = Endpoint::<MasterReq>::connect(UNIX_SOCKET_FD).unwrap();
let sock = listener.accept().unwrap().unwrap();
let mut slave = Endpoint::<MasterReq>::from_stream(sock);
let mut fd = tempfile().unwrap();
write!(fd, "test").unwrap();
// Normal case for sending/receiving file descriptors
let buf1 = vec![0x1, 0x2, 0x3, 0x4];
let len = master
.send_slice(&buf1[..], Some(&[fd.as_raw_fd()]))
.unwrap();
assert_eq!(len, 4);
let (bytes, buf2, rfds) = slave.recv_into_buf(4).unwrap();
assert_eq!(bytes, 4);
assert_eq!(&buf1[..], &buf2[..]);
assert!(rfds.is_some());
let fds = rfds.unwrap();
{
assert_eq!(fds.len(), 1);
let mut file = unsafe { File::from_raw_fd(fds[0]) };
let mut content = String::new();
file.seek(SeekFrom::Start(0)).unwrap();
file.read_to_string(&mut content).unwrap();
assert_eq!(content, "test");
}
// Following communication pattern should work:
// Sending side: data(header, body) with fds
// Receiving side: data(header) with fds, data(body)
let len = master
.send_slice(
&buf1[..],
Some(&[fd.as_raw_fd(), fd.as_raw_fd(), fd.as_raw_fd()]),
)
.unwrap();
assert_eq!(len, 4);
let (bytes, buf2, rfds) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[..2], &buf2[..]);
assert!(rfds.is_some());
let fds = rfds.unwrap();
{
assert_eq!(fds.len(), 3);
let mut file = unsafe { File::from_raw_fd(fds[1]) };
let mut content = String::new();
file.seek(SeekFrom::Start(0)).unwrap();
file.read_to_string(&mut content).unwrap();
assert_eq!(content, "test");
}
let (bytes, buf2, rfds) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[2..], &buf2[..]);
assert!(rfds.is_none());
// Following communication pattern should not work:
// Sending side: data(header, body) with fds
// Receiving side: data(header), data(body) with fds
let len = master
.send_slice(
&buf1[..],
Some(&[fd.as_raw_fd(), fd.as_raw_fd(), fd.as_raw_fd()]),
)
.unwrap();
assert_eq!(len, 4);
let (bytes, buf4) = slave.recv_data(2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[..2], &buf4[..]);
let (bytes, buf2, rfds) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[2..], &buf2[..]);
assert!(rfds.is_none());
// Following communication pattern should work:
// Sending side: data, data with fds
// Receiving side: data, data with fds
let len = master.send_slice(&buf1[..], None).unwrap();
assert_eq!(len, 4);
let len = master
.send_slice(
&buf1[..],
Some(&[fd.as_raw_fd(), fd.as_raw_fd(), fd.as_raw_fd()]),
)
.unwrap();
assert_eq!(len, 4);
let (bytes, buf2, rfds) = slave.recv_into_buf(0x4).unwrap();
assert_eq!(bytes, 4);
assert_eq!(&buf1[..], &buf2[..]);
assert!(rfds.is_none());
let (bytes, buf2, rfds) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[..2], &buf2[..]);
assert!(rfds.is_some());
let fds = rfds.unwrap();
{
assert_eq!(fds.len(), 3);
let mut file = unsafe { File::from_raw_fd(fds[1]) };
let mut content = String::new();
file.seek(SeekFrom::Start(0)).unwrap();
file.read_to_string(&mut content).unwrap();
assert_eq!(content, "test");
}
let (bytes, buf2, rfds) = slave.recv_into_buf(0x2).unwrap();
assert_eq!(bytes, 2);
assert_eq!(&buf1[2..], &buf2[..]);
assert!(rfds.is_none());
// Following communication pattern should not work:
// Sending side: data1, data2 with fds
// Receiving side: data + partial of data2, left of data2 with fds
let len = master.send_slice(&buf1[..], None).unwrap();
assert_eq!(len, 4);
let len = master
.send_slice(
&buf1[..],
Some(&[fd.as_raw_fd(), fd.as_raw_fd(), fd.as_raw_fd()]),
)
.unwrap();
assert_eq!(len, 4);
let (bytes, _) = slave.recv_data(5).unwrap();
assert_eq!(bytes, 5);
let (bytes, _, rfds) = slave.recv_into_buf(0x4).unwrap();
assert_eq!(bytes, 3);
assert!(rfds.is_none());
// If the target fd array is too small, extra file descriptors will get lost.
let len = master
.send_slice(
&buf1[..],
Some(&[fd.as_raw_fd(), fd.as_raw_fd(), fd.as_raw_fd()]),
)
.unwrap();
assert_eq!(len, 4);
let (bytes, _, rfds) = slave.recv_into_buf(0x4).unwrap();
assert_eq!(bytes, 4);
assert!(rfds.is_some());
Endpoint::<MasterReq>::close_rfds(rfds);
Endpoint::<MasterReq>::close_rfds(None);
}
#[test]
fn send_recv() {
let listener = Listener::new(UNIX_SOCKET_SEND, true).unwrap();
listener.set_nonblocking(true).unwrap();
let mut master = Endpoint::<MasterReq>::connect(UNIX_SOCKET_SEND).unwrap();
let sock = listener.accept().unwrap().unwrap();
let mut slave = Endpoint::<MasterReq>::from_stream(sock);
let mut hdr1 =
VhostUserMsgHeader::new(MasterReq::GET_FEATURES, 0, mem::size_of::<u64>() as u32);
hdr1.set_need_reply(true);
let features1 = 0x1u64;
master.send_message(&hdr1, &features1, None).unwrap();
let mut features2 = 0u64;
let slice = unsafe {
slice::from_raw_parts_mut(
(&mut features2 as *mut u64) as *mut u8,
mem::size_of::<u64>(),
)
};
let (hdr2, bytes, rfds) = slave.recv_body_into_buf(slice).unwrap();
assert_eq!(hdr1, hdr2);
assert_eq!(bytes, 8);
assert_eq!(features1, features2);
assert!(rfds.is_none());
master.send_header(&hdr1, None).unwrap();
let (hdr2, rfds) = slave.recv_header().unwrap();
assert_eq!(hdr1, hdr2);
assert!(rfds.is_none());
}
}

View File

@@ -1,250 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
use super::message::*;
use super::*;
use std::os::unix::io::RawFd;
pub const MAX_QUEUE_NUM: usize = 2;
pub const MAX_VRING_NUM: usize = 256;
pub const VIRTIO_FEATURES: u64 = 0x40000003;
#[derive(Default)]
pub struct DummySlaveReqHandler {
pub owned: bool,
pub features_acked: bool,
pub acked_features: u64,
pub acked_protocol_features: u64,
pub queue_num: usize,
pub vring_num: [u32; MAX_QUEUE_NUM],
pub vring_base: [u32; MAX_QUEUE_NUM],
pub call_fd: [Option<RawFd>; MAX_QUEUE_NUM],
pub kick_fd: [Option<RawFd>; MAX_QUEUE_NUM],
pub err_fd: [Option<RawFd>; MAX_QUEUE_NUM],
pub vring_started: [bool; MAX_QUEUE_NUM],
pub vring_enabled: [bool; MAX_QUEUE_NUM],
}
impl DummySlaveReqHandler {
pub fn new() -> Self {
DummySlaveReqHandler {
queue_num: MAX_QUEUE_NUM,
..Default::default()
}
}
}
impl VhostUserSlaveReqHandler for DummySlaveReqHandler {
fn set_owner(&mut self) -> Result<()> {
if self.owned {
return Err(Error::InvalidOperation);
}
self.owned = true;
Ok(())
}
fn reset_owner(&mut self) -> Result<()> {
self.owned = false;
self.features_acked = false;
self.acked_features = 0;
self.acked_protocol_features = 0;
Ok(())
}
fn get_features(&mut self) -> Result<u64> {
Ok(VIRTIO_FEATURES)
}
fn set_features(&mut self, features: u64) -> Result<()> {
if !self.owned {
return Err(Error::InvalidOperation);
} else if self.features_acked {
return Err(Error::InvalidOperation);
} else if (features & !VIRTIO_FEATURES) != 0 {
return Err(Error::InvalidParam);
}
self.acked_features = features;
self.features_acked = true;
// If VHOST_USER_F_PROTOCOL_FEATURES has not been negotiated,
// the ring is initialized in an enabled state.
// If VHOST_USER_F_PROTOCOL_FEATURES has been negotiated,
// the ring is initialized in a disabled state. Client must not
// pass data to/from the backend until ring is enabled by
// VHOST_USER_SET_VRING_ENABLE with parameter 1, or after it has
// been disabled by VHOST_USER_SET_VRING_ENABLE with parameter 0.
let vring_enabled =
self.acked_features & VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits() == 0;
for enabled in &mut self.vring_enabled {
*enabled = vring_enabled;
}
Ok(())
}
fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures> {
Ok(VhostUserProtocolFeatures::all())
}
fn set_protocol_features(&mut self, features: u64) -> Result<()> {
// Note: slave that reported VHOST_USER_F_PROTOCOL_FEATURES must
// support this message even before VHOST_USER_SET_FEATURES was
// called.
// What happens if the master calls set_features() with
// VHOST_USER_F_PROTOCOL_FEATURES cleared after calling this
// interface?
self.acked_protocol_features = features;
Ok(())
}
fn set_mem_table(&mut self, _ctx: &[VhostUserMemoryRegion], _fds: &[RawFd]) -> Result<()> {
// TODO
Ok(())
}
fn get_queue_num(&mut self) -> Result<u64> {
Ok(MAX_QUEUE_NUM as u64)
}
fn set_vring_num(&mut self, index: u32, num: u32) -> Result<()> {
if index as usize >= self.queue_num || num == 0 || num as usize > MAX_VRING_NUM {
return Err(Error::InvalidParam);
}
self.vring_num[index as usize] = num;
Ok(())
}
fn set_vring_addr(
&mut self,
index: u32,
_flags: VhostUserVringAddrFlags,
_descriptor: u64,
_used: u64,
_available: u64,
_log: u64,
) -> Result<()> {
if index as usize >= self.queue_num {
return Err(Error::InvalidParam);
}
Ok(())
}
fn set_vring_base(&mut self, index: u32, base: u32) -> Result<()> {
if index as usize >= self.queue_num || base as usize >= MAX_VRING_NUM {
return Err(Error::InvalidParam);
}
self.vring_base[index as usize] = base;
Ok(())
}
fn get_vring_base(&mut self, index: u32) -> Result<VhostUserVringState> {
if index as usize >= self.queue_num {
return Err(Error::InvalidParam);
}
// Quotation from vhost-user spec:
// Client must start ring upon receiving a kick (that is, detecting
// that file descriptor is readable) on the descriptor specified by
// VHOST_USER_SET_VRING_KICK, and stop ring upon receiving
// VHOST_USER_GET_VRING_BASE.
self.vring_started[index as usize] = false;
Ok(VhostUserVringState::new(
index,
self.vring_base[index as usize],
))
}
fn set_vring_kick(&mut self, index: u8, fd: Option<RawFd>) -> Result<()> {
if index as usize >= self.queue_num || index as usize > self.queue_num {
return Err(Error::InvalidParam);
}
if self.kick_fd[index as usize].is_some() {
// Close file descriptor set by previous operations.
let _ = unsafe { libc::close(self.kick_fd[index as usize].unwrap()) };
}
self.kick_fd[index as usize] = fd;
// Quotation from vhost-user spec:
// Client must start ring upon receiving a kick (that is, detecting
// that file descriptor is readable) on the descriptor specified by
// VHOST_USER_SET_VRING_KICK, and stop ring upon receiving
// VHOST_USER_GET_VRING_BASE.
//
// So we should add fd to event monitor(select, poll, epoll) here.
self.vring_started[index as usize] = true;
Ok(())
}
fn set_vring_call(&mut self, index: u8, fd: Option<RawFd>) -> Result<()> {
if index as usize >= self.queue_num || index as usize > self.queue_num {
return Err(Error::InvalidParam);
}
if self.call_fd[index as usize].is_some() {
// Close file descriptor set by previous operations.
let _ = unsafe { libc::close(self.call_fd[index as usize].unwrap()) };
}
self.call_fd[index as usize] = fd;
Ok(())
}
fn set_vring_err(&mut self, index: u8, fd: Option<RawFd>) -> Result<()> {
if index as usize >= self.queue_num || index as usize > self.queue_num {
return Err(Error::InvalidParam);
}
if self.err_fd[index as usize].is_some() {
// Close file descriptor set by previous operations.
let _ = unsafe { libc::close(self.err_fd[index as usize].unwrap()) };
}
self.err_fd[index as usize] = fd;
Ok(())
}
fn set_vring_enable(&mut self, index: u32, enable: bool) -> Result<()> {
// This request should be handled only when VHOST_USER_F_PROTOCOL_FEATURES
// has been negotiated.
if self.acked_features & VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits() == 0 {
return Err(Error::InvalidOperation);
} else if index as usize >= self.queue_num || index as usize > self.queue_num {
return Err(Error::InvalidParam);
}
// Slave must not pass data to/from the backend until ring is
// enabled by VHOST_USER_SET_VRING_ENABLE with parameter 1,
// or after it has been disabled by VHOST_USER_SET_VRING_ENABLE
// with parameter 0.
self.vring_enabled[index as usize] = enable;
Ok(())
}
fn get_config(
&mut self,
offset: u32,
size: u32,
_flags: VhostUserConfigFlags,
) -> Result<Vec<u8>> {
if self.acked_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return Err(Error::InvalidOperation);
} else if offset < VHOST_USER_CONFIG_OFFSET
|| offset >= VHOST_USER_CONFIG_SIZE
|| size > VHOST_USER_CONFIG_SIZE - VHOST_USER_CONFIG_OFFSET
|| size + offset > VHOST_USER_CONFIG_SIZE
{
return Err(Error::InvalidParam);
}
Ok(vec![0xa5; size as usize])
}
fn set_config(&mut self, offset: u32, buf: &[u8], _flags: VhostUserConfigFlags) -> Result<()> {
let size = buf.len() as u32;
if self.acked_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return Err(Error::InvalidOperation);
} else if offset < VHOST_USER_CONFIG_OFFSET
|| offset >= VHOST_USER_CONFIG_SIZE
|| size > VHOST_USER_CONFIG_SIZE - VHOST_USER_CONFIG_OFFSET
|| size + offset > VHOST_USER_CONFIG_SIZE
{
return Err(Error::InvalidParam);
}
Ok(())
}
}

View File

@@ -1,762 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Traits and Struct for vhost-user master.
use std::mem;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::sync::{Arc, Mutex};
use vmm_sys_util::eventfd::EventFd;
use super::connection::Endpoint;
use super::message::*;
use super::{Error as VhostUserError, Result as VhostUserResult};
use crate::backend::{VhostBackend, VhostUserMemoryRegionInfo, VringConfigData};
use crate::{Error, Result};
/// Trait for vhost-user master to provide extra methods not covered by the VhostBackend yet.
pub trait VhostUserMaster: VhostBackend {
/// Get the protocol feature bitmask from the underlying vhost implementation.
fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures>;
/// Enable protocol features in the underlying vhost implementation.
fn set_protocol_features(&mut self, features: VhostUserProtocolFeatures) -> Result<()>;
/// Query how many queues the backend supports.
fn get_queue_num(&mut self) -> Result<u64>;
/// Signal slave to enable or disable corresponding vring.
///
/// Slave must not pass data to/from the backend until ring is enabled by
/// VHOST_USER_SET_VRING_ENABLE with parameter 1, or after it has been
/// disabled by VHOST_USER_SET_VRING_ENABLE with parameter 0.
fn set_vring_enable(&mut self, queue_index: usize, enable: bool) -> Result<()>;
/// Fetch the contents of the virtio device configuration space.
fn get_config(
&mut self,
offset: u32,
size: u32,
flags: VhostUserConfigFlags,
buf: &[u8],
) -> Result<(VhostUserConfig, VhostUserConfigPayload)>;
/// Change the virtio device configuration space. It also can be used for live migration on the
/// destination host to set readonly configuration space fields.
fn set_config(&mut self, offset: u32, flags: VhostUserConfigFlags, buf: &[u8]) -> Result<()>;
/// Setup slave communication channel.
fn set_slave_request_fd(&mut self, fd: RawFd) -> Result<()>;
}
fn error_code<T>(err: VhostUserError) -> Result<T> {
Err(Error::VhostUserProtocol(err))
}
/// Struct for the vhost-user master endpoint.
#[derive(Clone)]
pub struct Master {
node: Arc<Mutex<MasterInternal>>,
}
impl Master {
/// Create a new instance.
fn new(ep: Endpoint<MasterReq>, max_queue_num: u64) -> Self {
Master {
node: Arc::new(Mutex::new(MasterInternal {
main_sock: ep,
virtio_features: 0,
acked_virtio_features: 0,
protocol_features: 0,
acked_protocol_features: 0,
protocol_features_ready: false,
max_queue_num,
error: None,
})),
}
}
/// Create a new instance from a Unix stream socket.
pub fn from_stream(sock: UnixStream, max_queue_num: u64) -> Self {
Self::new(Endpoint::<MasterReq>::from_stream(sock), max_queue_num)
}
/// Create a new vhost-user master endpoint.
///
/// # Arguments
/// * `path` - path of Unix domain socket listener to connect to
pub fn connect(path: &str, max_queue_num: u64) -> Result<Self> {
Ok(Self::new(
Endpoint::<MasterReq>::connect(path)?,
max_queue_num,
))
}
}
impl VhostBackend for Master {
/// Get from the underlying vhost implementation the feature bitmask.
fn get_features(&mut self) -> Result<u64> {
let mut node = self.node.lock().unwrap();
let hdr = node.send_request_header(MasterReq::GET_FEATURES, None)?;
let val = node.recv_reply::<VhostUserU64>(&hdr)?;
node.virtio_features = val.value;
Ok(node.virtio_features)
}
/// Enable features in the underlying vhost implementation using a bitmask.
fn set_features(&mut self, features: u64) -> Result<()> {
let mut node = self.node.lock().unwrap();
let val = VhostUserU64::new(features);
let _ = node.send_request_with_body(MasterReq::SET_FEATURES, &val, None)?;
// Don't wait for ACK here because the protocol feature negotiation process hasn't been
// completed yet.
node.acked_virtio_features = features & node.virtio_features;
Ok(())
}
/// Set the current Master as an owner of the session.
fn set_owner(&mut self) -> Result<()> {
// We unwrap() the return value to assert that we are not expecting threads to ever fail
// while holding the lock.
let mut node = self.node.lock().unwrap();
let _ = node.send_request_header(MasterReq::SET_OWNER, None)?;
// Don't wait for ACK here because the protocol feature negotiation process hasn't been
// completed yet.
Ok(())
}
fn reset_owner(&mut self) -> Result<()> {
let mut node = self.node.lock().unwrap();
let _ = node.send_request_header(MasterReq::RESET_OWNER, None)?;
// Don't wait for ACK here because the protocol feature negotiation process hasn't been
// completed yet.
Ok(())
}
/// Set the memory map regions on the slave so it can translate the vring
/// addresses. In the ancillary data there is an array of file descriptors
fn set_mem_table(&mut self, regions: &[VhostUserMemoryRegionInfo]) -> Result<()> {
if regions.is_empty() || regions.len() > MAX_ATTACHED_FD_ENTRIES {
return error_code(VhostUserError::InvalidParam);
}
let mut ctx = VhostUserMemoryContext::new();
for region in regions.iter() {
if region.memory_size == 0 || region.mmap_handle < 0 {
return error_code(VhostUserError::InvalidParam);
}
let reg = VhostUserMemoryRegion {
guest_phys_addr: region.guest_phys_addr,
memory_size: region.memory_size,
user_addr: region.userspace_addr,
mmap_offset: region.mmap_offset,
};
ctx.append(&reg, region.mmap_handle);
}
let mut node = self.node.lock().unwrap();
let body = VhostUserMemory::new(ctx.regions.len() as u32);
let hdr = node.send_request_with_payload(
MasterReq::SET_MEM_TABLE,
&body,
ctx.regions.as_slice(),
Some(ctx.fds.as_slice()),
)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
// Clippy doesn't seem to know that if let with && is still experimental
#[allow(clippy::unnecessary_unwrap)]
fn set_log_base(&mut self, base: u64, fd: Option<RawFd>) -> Result<()> {
let mut node = self.node.lock().unwrap();
let val = VhostUserU64::new(base);
if node.acked_protocol_features & VhostUserProtocolFeatures::LOG_SHMFD.bits() != 0
&& fd.is_some()
{
let fds = [fd.unwrap()];
let _ = node.send_request_with_body(MasterReq::SET_LOG_BASE, &val, Some(&fds))?;
} else {
let _ = node.send_request_with_body(MasterReq::SET_LOG_BASE, &val, None)?;
}
Ok(())
}
fn set_log_fd(&mut self, fd: RawFd) -> Result<()> {
let mut node = self.node.lock().unwrap();
let fds = [fd];
node.send_request_header(MasterReq::SET_LOG_FD, Some(&fds))?;
Ok(())
}
/// Set the size of the queue.
fn set_vring_num(&mut self, queue_index: usize, num: u16) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
let val = VhostUserVringState::new(queue_index as u32, num.into());
let hdr = node.send_request_with_body(MasterReq::SET_VRING_NUM, &val, None)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
/// Sets the addresses of the different aspects of the vring.
fn set_vring_addr(&mut self, queue_index: usize, config_data: &VringConfigData) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num
|| config_data.flags & !(VhostUserVringAddrFlags::all().bits()) != 0
{
return error_code(VhostUserError::InvalidParam);
}
let val = VhostUserVringAddr::from_config_data(queue_index as u32, config_data);
let hdr = node.send_request_with_body(MasterReq::SET_VRING_ADDR, &val, None)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
/// Sets the base offset in the available vring.
fn set_vring_base(&mut self, queue_index: usize, base: u16) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
let val = VhostUserVringState::new(queue_index as u32, base.into());
let hdr = node.send_request_with_body(MasterReq::SET_VRING_BASE, &val, None)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
fn get_vring_base(&mut self, queue_index: usize) -> Result<u32> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
let req = VhostUserVringState::new(queue_index as u32, 0);
let hdr = node.send_request_with_body(MasterReq::GET_VRING_BASE, &req, None)?;
let reply = node.recv_reply::<VhostUserVringState>(&hdr)?;
Ok(reply.num)
}
/// Set the event file descriptor to signal when buffers are used.
/// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
/// is set when there is no file descriptor in the ancillary data. This signals that polling
/// will be used instead of waiting for the call.
fn set_vring_call(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
node.send_fd_for_vring(MasterReq::SET_VRING_CALL, queue_index, fd.as_raw_fd())?;
Ok(())
}
/// Set the event file descriptor for adding buffers to the vring.
/// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
/// is set when there is no file descriptor in the ancillary data. This signals that polling
/// should be used instead of waiting for a kick.
fn set_vring_kick(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
node.send_fd_for_vring(MasterReq::SET_VRING_KICK, queue_index, fd.as_raw_fd())?;
Ok(())
}
/// Set the event file descriptor to signal when error occurs.
/// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag. This flag
/// is set when there is no file descriptor in the ancillary data.
fn set_vring_err(&mut self, queue_index: usize, fd: &EventFd) -> Result<()> {
let mut node = self.node.lock().unwrap();
if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
node.send_fd_for_vring(MasterReq::SET_VRING_ERR, queue_index, fd.as_raw_fd())?;
Ok(())
}
}
impl VhostUserMaster for Master {
fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures> {
let mut node = self.node.lock().unwrap();
let flag = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits();
if node.virtio_features & flag == 0 || node.acked_virtio_features & flag == 0 {
return error_code(VhostUserError::InvalidOperation);
}
let hdr = node.send_request_header(MasterReq::GET_PROTOCOL_FEATURES, None)?;
let val = node.recv_reply::<VhostUserU64>(&hdr)?;
node.protocol_features = val.value;
// Should we support forward compatibility?
// If so just mask out unrecognized flags instead of return errors.
match VhostUserProtocolFeatures::from_bits(node.protocol_features) {
Some(val) => Ok(val),
None => error_code(VhostUserError::InvalidMessage),
}
}
fn set_protocol_features(&mut self, features: VhostUserProtocolFeatures) -> Result<()> {
let mut node = self.node.lock().unwrap();
let flag = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits();
if node.virtio_features & flag == 0 || node.acked_virtio_features & flag == 0 {
return error_code(VhostUserError::InvalidOperation);
}
let val = VhostUserU64::new(features.bits());
let _ = node.send_request_with_body(MasterReq::SET_PROTOCOL_FEATURES, &val, None)?;
// Don't wait for ACK here because the protocol feature negotiation process hasn't been
// completed yet.
node.acked_protocol_features = features.bits();
node.protocol_features_ready = true;
Ok(())
}
fn get_queue_num(&mut self) -> Result<u64> {
let mut node = self.node.lock().unwrap();
if !node.is_feature_mq_available() {
return error_code(VhostUserError::InvalidOperation);
}
let hdr = node.send_request_header(MasterReq::GET_QUEUE_NUM, None)?;
let val = node.recv_reply::<VhostUserU64>(&hdr)?;
if val.value > VHOST_USER_MAX_VRINGS {
return error_code(VhostUserError::InvalidMessage);
}
node.max_queue_num = val.value;
Ok(node.max_queue_num)
}
fn set_vring_enable(&mut self, queue_index: usize, enable: bool) -> Result<()> {
let mut node = self.node.lock().unwrap();
// set_vring_enable() is supported only when PROTOCOL_FEATURES has been enabled.
if node.acked_virtio_features & VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits() == 0 {
return error_code(VhostUserError::InvalidOperation);
} else if queue_index as u64 >= node.max_queue_num {
return error_code(VhostUserError::InvalidParam);
}
let flag = if enable { 1 } else { 0 };
let val = VhostUserVringState::new(queue_index as u32, flag);
let hdr = node.send_request_with_body(MasterReq::SET_VRING_ENABLE, &val, None)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
fn get_config(
&mut self,
offset: u32,
size: u32,
flags: VhostUserConfigFlags,
buf: &[u8],
) -> Result<(VhostUserConfig, VhostUserConfigPayload)> {
let body = VhostUserConfig::new(offset, size, flags);
if !body.is_valid() {
return error_code(VhostUserError::InvalidParam);
}
let mut node = self.node.lock().unwrap();
// depends on VhostUserProtocolFeatures::CONFIG
if node.acked_protocol_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return error_code(VhostUserError::InvalidOperation);
}
// vhost-user spec states that:
// "Master payload: virtio device config space"
// "Slave payload: virtio device config space"
let hdr = node.send_request_with_payload(MasterReq::GET_CONFIG, &body, buf, None)?;
let (body_reply, buf_reply, rfds) =
node.recv_reply_with_payload::<VhostUserConfig>(&hdr)?;
if rfds.is_some() {
Endpoint::<MasterReq>::close_rfds(rfds);
return error_code(VhostUserError::InvalidMessage);
} else if body_reply.size == 0 {
return error_code(VhostUserError::SlaveInternalError);
} else if body_reply.size != body.size || body_reply.size as usize != buf.len() {
return error_code(VhostUserError::InvalidMessage);
}
Ok((body_reply, buf_reply))
}
fn set_config(&mut self, offset: u32, flags: VhostUserConfigFlags, buf: &[u8]) -> Result<()> {
if buf.len() > MAX_MSG_SIZE {
return error_code(VhostUserError::InvalidParam);
}
let body = VhostUserConfig::new(offset, buf.len() as u32, flags);
if !body.is_valid() {
return error_code(VhostUserError::InvalidParam);
}
let mut node = self.node.lock().unwrap();
// depends on VhostUserProtocolFeatures::CONFIG
if node.acked_protocol_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return error_code(VhostUserError::InvalidOperation);
}
let hdr = node.send_request_with_payload(MasterReq::SET_CONFIG, &body, buf, None)?;
node.wait_for_ack(&hdr).map_err(|e| e.into())
}
fn set_slave_request_fd(&mut self, fd: RawFd) -> Result<()> {
let mut node = self.node.lock().unwrap();
if node.acked_protocol_features & VhostUserProtocolFeatures::SLAVE_REQ.bits() == 0 {
return error_code(VhostUserError::InvalidOperation);
}
let fds = [fd];
node.send_request_header(MasterReq::SET_SLAVE_REQ_FD, Some(&fds))?;
Ok(())
}
}
impl AsRawFd for Master {
fn as_raw_fd(&self) -> RawFd {
let node = self.node.lock().unwrap();
node.main_sock.as_raw_fd()
}
}
/// Context object to pass guest memory configuration to VhostUserMaster::set_mem_table().
struct VhostUserMemoryContext {
regions: VhostUserMemoryPayload,
fds: Vec<RawFd>,
}
impl VhostUserMemoryContext {
/// Create a context object.
pub fn new() -> Self {
VhostUserMemoryContext {
regions: VhostUserMemoryPayload::new(),
fds: Vec::new(),
}
}
/// Append a user memory region and corresponding RawFd into the context object.
pub fn append(&mut self, region: &VhostUserMemoryRegion, fd: RawFd) {
self.regions.push(*region);
self.fds.push(fd);
}
}
struct MasterInternal {
// Used to send requests to the slave.
main_sock: Endpoint<MasterReq>,
// Cached virtio features from the slave.
virtio_features: u64,
// Cached acked virtio features from the driver.
acked_virtio_features: u64,
// Cached vhost-user protocol features from the slave.
protocol_features: u64,
// Cached vhost-user protocol features.
acked_protocol_features: u64,
// Cached vhost-user protocol features are ready to use.
protocol_features_ready: bool,
// Cached maxinum number of queues supported from the slave.
max_queue_num: u64,
// Internal flag to mark failure state.
error: Option<i32>,
}
impl MasterInternal {
fn send_request_header(
&mut self,
code: MasterReq,
fds: Option<&[RawFd]>,
) -> VhostUserResult<VhostUserMsgHeader<MasterReq>> {
self.check_state()?;
let hdr = Self::new_request_header(code, 0);
self.main_sock.send_header(&hdr, fds)?;
Ok(hdr)
}
fn send_request_with_body<T: Sized>(
&mut self,
code: MasterReq,
msg: &T,
fds: Option<&[RawFd]>,
) -> VhostUserResult<VhostUserMsgHeader<MasterReq>> {
if mem::size_of::<T>() > MAX_MSG_SIZE {
return Err(VhostUserError::InvalidParam);
}
self.check_state()?;
let hdr = Self::new_request_header(code, mem::size_of::<T>() as u32);
self.main_sock.send_message(&hdr, msg, fds)?;
Ok(hdr)
}
fn send_request_with_payload<T: Sized, P: Sized>(
&mut self,
code: MasterReq,
msg: &T,
payload: &[P],
fds: Option<&[RawFd]>,
) -> VhostUserResult<VhostUserMsgHeader<MasterReq>> {
let len = mem::size_of::<T>() + payload.len() * mem::size_of::<P>();
if len > MAX_MSG_SIZE {
return Err(VhostUserError::InvalidParam);
}
if let Some(ref fd_arr) = fds {
if fd_arr.len() > MAX_ATTACHED_FD_ENTRIES {
return Err(VhostUserError::InvalidParam);
}
}
self.check_state()?;
let hdr = Self::new_request_header(code, len as u32);
self.main_sock
.send_message_with_payload(&hdr, msg, payload, fds)?;
Ok(hdr)
}
fn send_fd_for_vring(
&mut self,
code: MasterReq,
queue_index: usize,
fd: RawFd,
) -> VhostUserResult<VhostUserMsgHeader<MasterReq>> {
if queue_index as u64 >= self.max_queue_num {
return Err(VhostUserError::InvalidParam);
}
self.check_state()?;
// Bits (0-7) of the payload contain the vring index. Bit 8 is the invalid FD flag.
// This flag is set when there is no file descriptor in the ancillary data. This signals
// that polling will be used instead of waiting for the call.
let msg = VhostUserU64::new(queue_index as u64);
let hdr = Self::new_request_header(code, mem::size_of::<VhostUserU64>() as u32);
self.main_sock.send_message(&hdr, &msg, Some(&[fd]))?;
Ok(hdr)
}
fn recv_reply<T: Sized + Default + VhostUserMsgValidator>(
&mut self,
hdr: &VhostUserMsgHeader<MasterReq>,
) -> VhostUserResult<T> {
if mem::size_of::<T>() > MAX_MSG_SIZE || hdr.is_reply() {
return Err(VhostUserError::InvalidParam);
}
self.check_state()?;
let (reply, body, rfds) = self.main_sock.recv_body::<T>()?;
if !reply.is_reply_for(&hdr) || rfds.is_some() || !body.is_valid() {
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(VhostUserError::InvalidMessage);
}
Ok(body)
}
fn recv_reply_with_payload<T: Sized + Default + VhostUserMsgValidator>(
&mut self,
hdr: &VhostUserMsgHeader<MasterReq>,
) -> VhostUserResult<(T, Vec<u8>, Option<Vec<RawFd>>)> {
if mem::size_of::<T>() > MAX_MSG_SIZE || hdr.is_reply() {
return Err(VhostUserError::InvalidParam);
}
self.check_state()?;
let mut buf: Vec<u8> = vec![0; hdr.get_size() as usize - mem::size_of::<T>()];
let (reply, body, bytes, rfds) = self.main_sock.recv_payload_into_buf::<T>(&mut buf)?;
if !reply.is_reply_for(hdr)
|| reply.get_size() as usize != mem::size_of::<T>() + bytes
|| rfds.is_some()
|| !body.is_valid()
{
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(VhostUserError::InvalidMessage);
} else if bytes > MAX_MSG_SIZE - mem::size_of::<T>() {
return Err(VhostUserError::InvalidMessage);
} else if bytes < buf.len() {
// It's safe because we have checked the buffer size
unsafe { buf.set_len(bytes) };
}
Ok((body, buf, rfds))
}
fn wait_for_ack(&mut self, hdr: &VhostUserMsgHeader<MasterReq>) -> VhostUserResult<()> {
if self.acked_protocol_features & VhostUserProtocolFeatures::REPLY_ACK.bits() == 0
|| !hdr.is_need_reply()
{
return Ok(());
}
self.check_state()?;
let (reply, body, rfds) = self.main_sock.recv_body::<VhostUserU64>()?;
if !reply.is_reply_for(&hdr) || rfds.is_some() || !body.is_valid() {
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(VhostUserError::InvalidMessage);
}
if body.value != 0 {
return Err(VhostUserError::SlaveInternalError);
}
Ok(())
}
fn is_feature_mq_available(&self) -> bool {
self.acked_protocol_features & VhostUserProtocolFeatures::MQ.bits() != 0
}
fn check_state(&self) -> VhostUserResult<()> {
match self.error {
Some(e) => Err(VhostUserError::SocketBroken(
std::io::Error::from_raw_os_error(e),
)),
None => Ok(()),
}
}
#[inline]
fn new_request_header(request: MasterReq, size: u32) -> VhostUserMsgHeader<MasterReq> {
// TODO: handle NEED_REPLY flag
VhostUserMsgHeader::new(request, 0x1, size)
}
}
#[cfg(test)]
mod tests {
use super::super::connection::Listener;
use super::*;
const UNIX_SOCKET_MASTER: &'static str = "/tmp/vhost_user_test_rust_master";
const UNIX_SOCKET_MASTER2: &'static str = "/tmp/vhost_user_test_rust_master2";
const UNIX_SOCKET_MASTER3: &'static str = "/tmp/vhost_user_test_rust_master3";
const UNIX_SOCKET_MASTER4: &'static str = "/tmp/vhost_user_test_rust_master4";
fn create_pair(path: &str) -> (Master, Endpoint<MasterReq>) {
let listener = Listener::new(path, true).unwrap();
listener.set_nonblocking(true).unwrap();
let master = Master::connect(path, 2).unwrap();
let slave = listener.accept().unwrap().unwrap();
(master, Endpoint::from_stream(slave))
}
#[test]
fn create_master() {
let listener = Listener::new(UNIX_SOCKET_MASTER, true).unwrap();
listener.set_nonblocking(true).unwrap();
let mut master = Master::connect(UNIX_SOCKET_MASTER, 2).unwrap();
let mut slave = Endpoint::<MasterReq>::from_stream(listener.accept().unwrap().unwrap());
// Send two messages continuously
master.set_owner().unwrap();
master.reset_owner().unwrap();
let (hdr, rfds) = slave.recv_header().unwrap();
assert_eq!(hdr.get_code(), MasterReq::SET_OWNER);
assert_eq!(hdr.get_size(), 0);
assert_eq!(hdr.get_version(), 0x1);
assert!(rfds.is_none());
let (hdr, rfds) = slave.recv_header().unwrap();
assert_eq!(hdr.get_code(), MasterReq::RESET_OWNER);
assert_eq!(hdr.get_size(), 0);
assert_eq!(hdr.get_version(), 0x1);
assert!(rfds.is_none());
}
#[test]
fn test_create_failure() {
let _ = Listener::new(UNIX_SOCKET_MASTER2, true).unwrap();
let _ = Listener::new(UNIX_SOCKET_MASTER2, false).is_err();
assert!(Master::connect(UNIX_SOCKET_MASTER2, 2).is_err());
let listener = Listener::new(UNIX_SOCKET_MASTER2, true).unwrap();
assert!(Listener::new(UNIX_SOCKET_MASTER2, false).is_err());
listener.set_nonblocking(true).unwrap();
let _master = Master::connect(UNIX_SOCKET_MASTER2, 2).unwrap();
let _slave = listener.accept().unwrap().unwrap();
}
#[test]
fn test_features() {
let (mut master, mut peer) = create_pair(UNIX_SOCKET_MASTER3);
master.set_owner().unwrap();
let (hdr, rfds) = peer.recv_header().unwrap();
assert_eq!(hdr.get_code(), MasterReq::SET_OWNER);
assert_eq!(hdr.get_size(), 0);
assert_eq!(hdr.get_version(), 0x1);
assert!(rfds.is_none());
let hdr = VhostUserMsgHeader::new(MasterReq::GET_FEATURES, 0x4, 8);
let msg = VhostUserU64::new(0x15);
peer.send_message(&hdr, &msg, None).unwrap();
let features = master.get_features().unwrap();
assert_eq!(features, 0x15u64);
let (_hdr, rfds) = peer.recv_header().unwrap();
assert!(rfds.is_none());
master.set_features(0x15).unwrap();
let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
assert!(rfds.is_none());
let val = msg.value;
assert_eq!(val, 0x15);
let hdr = VhostUserMsgHeader::new(MasterReq::GET_FEATURES, 0x4, 8);
let msg = 0x15u32;
peer.send_message(&hdr, &msg, None).unwrap();
assert!(master.get_features().is_err());
}
#[test]
fn test_protocol_features() {
let (mut master, mut peer) = create_pair(UNIX_SOCKET_MASTER4);
master.set_owner().unwrap();
let (hdr, rfds) = peer.recv_header().unwrap();
assert_eq!(hdr.get_code(), MasterReq::SET_OWNER);
assert!(rfds.is_none());
assert!(master.get_protocol_features().is_err());
assert!(master
.set_protocol_features(VhostUserProtocolFeatures::all())
.is_err());
let vfeatures = 0x15 | VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits();
let hdr = VhostUserMsgHeader::new(MasterReq::GET_FEATURES, 0x4, 8);
let msg = VhostUserU64::new(vfeatures);
peer.send_message(&hdr, &msg, None).unwrap();
let features = master.get_features().unwrap();
assert_eq!(features, vfeatures);
let (_hdr, rfds) = peer.recv_header().unwrap();
assert!(rfds.is_none());
master.set_features(vfeatures).unwrap();
let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
assert!(rfds.is_none());
let val = msg.value;
assert_eq!(val, vfeatures);
let pfeatures = VhostUserProtocolFeatures::all();
let hdr = VhostUserMsgHeader::new(MasterReq::GET_PROTOCOL_FEATURES, 0x4, 8);
let msg = VhostUserU64::new(pfeatures.bits());
peer.send_message(&hdr, &msg, None).unwrap();
let features = master.get_protocol_features().unwrap();
assert_eq!(features, pfeatures);
let (_hdr, rfds) = peer.recv_header().unwrap();
assert!(rfds.is_none());
master.set_protocol_features(pfeatures).unwrap();
let (_hdr, msg, rfds) = peer.recv_body::<VhostUserU64>().unwrap();
assert!(rfds.is_none());
let val = msg.value;
assert_eq!(val, pfeatures.bits());
let hdr = VhostUserMsgHeader::new(MasterReq::SET_PROTOCOL_FEATURES, 0x4, 8);
let msg = VhostUserU64::new(pfeatures.bits());
peer.send_message(&hdr, &msg, None).unwrap();
assert!(master.get_protocol_features().is_err());
}
#[test]
fn test_set_mem_table() {
// TODO
}
#[test]
fn test_get_ring_num() {
// TODO
}
}

View File

@@ -1,258 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Traits and Structs to handle vhost-user requests from the slave to the master.
use libc;
use std::mem;
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::UnixStream;
use std::sync::{Arc, Mutex};
use super::connection::Endpoint;
use super::message::*;
use super::{Error, HandlerResult, Result};
/// Trait to handle vhost-user requests from the slave to the master.
pub trait VhostUserMasterReqHandler {
// fn handle_iotlb_msg(&mut self, iotlb: VhostUserIotlb);
// fn handle_vring_host_notifier(&mut self, area: VhostUserVringArea, fd: RawFd);
/// Handle device configuration change notifications from the slave.
fn handle_config_change(&mut self) -> HandlerResult<()> {
Err(std::io::Error::from_raw_os_error(libc::ENOSYS))
}
/// Handle virtio-fs map file requests from the slave.
fn fs_slave_map(&mut self, _fs: &VhostUserFSSlaveMsg, fd: RawFd) -> HandlerResult<()> {
// Safe because we have just received the rawfd from kernel.
unsafe { libc::close(fd) };
Err(std::io::Error::from_raw_os_error(libc::ENOSYS))
}
/// Handle virtio-fs unmap file requests from the slave.
fn fs_slave_unmap(&mut self, _fs: &VhostUserFSSlaveMsg) -> HandlerResult<()> {
Err(std::io::Error::from_raw_os_error(libc::ENOSYS))
}
/// Handle virtio-fs sync file requests from the slave.
fn fs_slave_sync(&mut self, _fs: &VhostUserFSSlaveMsg) -> HandlerResult<()> {
Err(std::io::Error::from_raw_os_error(libc::ENOSYS))
}
}
/// A vhost-user master request endpoint which relays all received requests from the slave to the
/// provided request handler.
pub struct MasterReqHandler<S: VhostUserMasterReqHandler> {
// underlying Unix domain socket for communication
sub_sock: Endpoint<SlaveReq>,
tx_sock: UnixStream,
// the VirtIO backend device object
backend: Arc<Mutex<S>>,
// whether the endpoint has encountered any failure
error: Option<i32>,
}
impl<S: VhostUserMasterReqHandler> MasterReqHandler<S> {
/// Create a vhost-user slave request handler.
/// This opens a pair of connected anonymous sockets.
/// Returns Self and the socket that must be sent to the slave via SET_SLAVE_REQ_FD.
pub fn new(backend: Arc<Mutex<S>>) -> Result<Self> {
let (tx, rx) = UnixStream::pair().map_err(Error::SocketError)?;
Ok(MasterReqHandler {
sub_sock: Endpoint::<SlaveReq>::from_stream(rx),
tx_sock: tx,
backend,
error: None,
})
}
/// Get the raw fd to send to the slave as slave communication channel.
pub fn get_tx_raw_fd(&self) -> RawFd {
self.tx_sock.as_raw_fd()
}
/// Mark endpoint as failed or normal state.
pub fn set_failed(&mut self, error: i32) {
self.error = Some(error);
}
/// Receive and handle one incoming request message from the slave.
/// The caller needs to:
/// . serialize calls to this function
/// . decide what to do when errer happens
/// . optional recover from failure
pub fn handle_request(&mut self) -> Result<()> {
// Return error if the endpoint is already in failed state.
self.check_state()?;
// The underlying communication channel is a Unix domain socket in
// stream mode, and recvmsg() is a little tricky here. To successfully
// receive attached file descriptors, we need to receive messages and
// corresponding attached file descriptors in this way:
// . recv messsage header and optional attached file
// . validate message header
// . recv optional message body and payload according size field in
// message header
// . validate message body and optional payload
let (hdr, rfds) = self.sub_sock.recv_header()?;
let rfds = self.check_attached_rfds(&hdr, rfds)?;
let (size, buf) = match hdr.get_size() {
0 => (0, vec![0u8; 0]),
len => {
let (size2, rbuf) = self.sub_sock.recv_data(len as usize)?;
if size2 != len as usize {
return Err(Error::InvalidMessage);
}
(size2, rbuf)
}
};
let res = match hdr.get_code() {
SlaveReq::CONFIG_CHANGE_MSG => {
self.check_msg_size(&hdr, size, 0)?;
self.backend
.lock()
.unwrap()
.handle_config_change()
.map_err(Error::ReqHandlerError)
}
SlaveReq::FS_MAP => {
let msg = self.extract_msg_body::<VhostUserFSSlaveMsg>(&hdr, size, &buf)?;
self.backend
.lock()
.unwrap()
.fs_slave_map(msg, rfds.unwrap()[0])
.map_err(Error::ReqHandlerError)
}
SlaveReq::FS_UNMAP => {
let msg = self.extract_msg_body::<VhostUserFSSlaveMsg>(&hdr, size, &buf)?;
self.backend
.lock()
.unwrap()
.fs_slave_unmap(msg)
.map_err(Error::ReqHandlerError)
}
SlaveReq::FS_SYNC => {
let msg = self.extract_msg_body::<VhostUserFSSlaveMsg>(&hdr, size, &buf)?;
self.backend
.lock()
.unwrap()
.fs_slave_sync(msg)
.map_err(Error::ReqHandlerError)
}
_ => Err(Error::InvalidMessage),
};
self.send_ack_message(&hdr, &res)?;
res
}
fn check_state(&self) -> Result<()> {
match self.error {
Some(e) => Err(Error::SocketBroken(std::io::Error::from_raw_os_error(e))),
None => Ok(()),
}
}
fn check_msg_size(
&self,
hdr: &VhostUserMsgHeader<SlaveReq>,
size: usize,
expected: usize,
) -> Result<()> {
if hdr.get_size() as usize != expected
|| hdr.is_reply()
|| hdr.get_version() != 0x1
|| size != expected
{
return Err(Error::InvalidMessage);
}
Ok(())
}
fn check_attached_rfds(
&self,
hdr: &VhostUserMsgHeader<SlaveReq>,
rfds: Option<Vec<RawFd>>,
) -> Result<Option<Vec<RawFd>>> {
match hdr.get_code() {
SlaveReq::FS_MAP => {
// Expect an fd set with a single fd.
match rfds {
None => Err(Error::InvalidMessage),
Some(fds) => {
if fds.len() != 1 {
Endpoint::<SlaveReq>::close_rfds(Some(fds));
Err(Error::InvalidMessage)
} else {
Ok(Some(fds))
}
}
}
}
_ => {
if rfds.is_some() {
Endpoint::<SlaveReq>::close_rfds(rfds);
Err(Error::InvalidMessage)
} else {
Ok(rfds)
}
}
}
}
fn extract_msg_body<'a, T: Sized + VhostUserMsgValidator>(
&self,
hdr: &VhostUserMsgHeader<SlaveReq>,
size: usize,
buf: &'a [u8],
) -> Result<&'a T> {
self.check_msg_size(hdr, size, mem::size_of::<T>())?;
let msg = unsafe { &*(buf.as_ptr() as *const T) };
if !msg.is_valid() {
return Err(Error::InvalidMessage);
}
Ok(msg)
}
fn new_reply_header<T: Sized>(
&self,
req: &VhostUserMsgHeader<SlaveReq>,
) -> Result<VhostUserMsgHeader<SlaveReq>> {
if mem::size_of::<T>() > MAX_MSG_SIZE {
return Err(Error::InvalidParam);
}
self.check_state()?;
Ok(VhostUserMsgHeader::new(
req.get_code(),
VhostUserHeaderFlag::REPLY.bits(),
mem::size_of::<T>() as u32,
))
}
fn send_ack_message(
&mut self,
req: &VhostUserMsgHeader<SlaveReq>,
res: &Result<()>,
) -> Result<()> {
if req.is_need_reply() {
let hdr = self.new_reply_header::<VhostUserU64>(req)?;
let val = match res {
Ok(_) => 0,
Err(_) => 1,
};
let msg = VhostUserU64::new(val);
self.sub_sock.send_message(&hdr, &msg, None)?;
}
Ok(())
}
}
impl<S: VhostUserMasterReqHandler> AsRawFd for MasterReqHandler<S> {
fn as_raw_fd(&self) -> RawFd {
self.sub_sock.as_raw_fd()
}
}

View File

@@ -1,811 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Define communication messages for the vhost-user protocol.
//!
//! For message definition, please refer to the [vhost-user spec](https://github.com/qemu/qemu/blob/f7526eece29cd2e36a63b6703508b24453095eb8/docs/interop/vhost-user.txt).
#![allow(dead_code)]
#![allow(non_camel_case_types)]
use std::fmt::Debug;
use std::marker::PhantomData;
use VringConfigData;
/// The vhost-user specification uses a field of u32 to store message length.
/// On the other hand, preallocated buffers are needed to receive messages from the Unix domain
/// socket. To preallocating a 4GB buffer for each vhost-user message is really just an overhead.
/// Among all defined vhost-user messages, only the VhostUserConfig and VhostUserMemory has variable
/// message size. For the VhostUserConfig, a maximum size of 4K is enough because the user
/// configuration space for virtio devices is (4K - 0x100) bytes at most. For the VhostUserMemory,
/// 4K should be enough too because it can support 255 memory regions at most.
pub const MAX_MSG_SIZE: usize = 0x1000;
/// The VhostUserMemory message has variable message size and variable number of attached file
/// descriptors. Each user memory region entry in the message payload occupies 32 bytes,
/// so setting maximum number of attached file descriptors based on the maximum message size.
/// But rust only implements Default and AsMut traits for arrays with 0 - 32 entries, so further
/// reduce the maximum number...
// pub const MAX_ATTACHED_FD_ENTRIES: usize = (MAX_MSG_SIZE - 8) / 32;
pub const MAX_ATTACHED_FD_ENTRIES: usize = 32;
/// Starting position (inclusion) of the device configuration space in virtio devices.
pub const VHOST_USER_CONFIG_OFFSET: u32 = 0x100;
/// Ending position (exclusion) of the device configuration space in virtio devices.
pub const VHOST_USER_CONFIG_SIZE: u32 = 0x1000;
/// Maximum number of vrings supported.
pub const VHOST_USER_MAX_VRINGS: u64 = 0xFFu64;
pub(super) trait Req:
Clone + Copy + Debug + PartialEq + Eq + PartialOrd + Ord + Into<u32>
{
fn is_valid(&self) -> bool;
}
/// Type of requests sending from masters to slaves.
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum MasterReq {
/// Null operation.
NOOP = 0,
/// Get from the underlying vhost implementation the features bit mask.
GET_FEATURES = 1,
/// Enable features in the underlying vhost implementation using a bit mask.
SET_FEATURES = 2,
/// Set the current Master as an owner of the session.
SET_OWNER = 3,
/// No longer used.
RESET_OWNER = 4,
/// Set the memory map regions on the slave so it can translate the vring addresses.
SET_MEM_TABLE = 5,
/// Set logging shared memory space.
SET_LOG_BASE = 6,
/// Set the logging file descriptor, which is passed as ancillary data.
SET_LOG_FD = 7,
/// Set the size of the queue.
SET_VRING_NUM = 8,
/// Set the addresses of the different aspects of the vring.
SET_VRING_ADDR = 9,
/// Set the base offset in the available vring.
SET_VRING_BASE = 10,
/// Get the available vring base offset.
GET_VRING_BASE = 11,
/// Set the event file descriptor for adding buffers to the vring.
SET_VRING_KICK = 12,
/// Set the event file descriptor to signal when buffers are used.
SET_VRING_CALL = 13,
/// Set the event file descriptor to signal when error occurs.
SET_VRING_ERR = 14,
/// Get the protocol feature bit mask from the underlying vhost implementation.
GET_PROTOCOL_FEATURES = 15,
/// Enable protocol features in the underlying vhost implementation.
SET_PROTOCOL_FEATURES = 16,
/// Query how many queues the backend supports.
GET_QUEUE_NUM = 17,
/// Signal slave to enable or disable corresponding vring.
SET_VRING_ENABLE = 18,
/// Ask vhost user backend to broadcast a fake RARP to notify the migration is terminated
/// for guest that does not support GUEST_ANNOUNCE.
SEND_RARP = 19,
/// Set host MTU value exposed to the guest.
NET_SET_MTU = 20,
/// Set the socket file descriptor for slave initiated requests.
SET_SLAVE_REQ_FD = 21,
/// Send IOTLB messages with struct vhost_iotlb_msg as payload.
IOTLB_MSG = 22,
/// Set the endianness of a VQ for legacy devices.
SET_VRING_ENDIAN = 23,
/// Fetch the contents of the virtio device configuration space.
GET_CONFIG = 24,
/// Change the contents of the virtio device configuration space.
SET_CONFIG = 25,
/// Create a session for crypto operation.
CREATE_CRYPTO_SESSION = 26,
/// Close a session for crypto operation.
CLOSE_CRYPTO_SESSION = 27,
/// Advise slave that a migration with postcopy enabled is underway.
POSTCOPY_ADVISE = 28,
/// Advise slave that a transition to postcopy mode has happened.
POSTCOPY_LISTEN = 29,
/// Advise that postcopy migration has now completed.
POSTCOPY_END = 30,
/// Get a shared buffer from slave.
GET_INFLIGHT_FD = 31,
/// Send the shared inflight buffer back to slave
SET_INFLIGHT_FD = 32,
/// Upper bound of valid commands.
MAX_CMD = 33,
}
impl Into<u32> for MasterReq {
fn into(self) -> u32 {
self as u32
}
}
impl Req for MasterReq {
fn is_valid(&self) -> bool {
(*self > MasterReq::NOOP) && (*self < MasterReq::MAX_CMD)
}
}
/// Type of requests sending from slaves to masters.
#[repr(u32)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum SlaveReq {
/// Null operation.
NOOP = 0,
/// Send IOTLB messages with struct vhost_iotlb_msg as payload.
IOTLB_MSG = 1,
/// Notify that the virtio device's configuration space has changed.
CONFIG_CHANGE_MSG = 2,
/// Set host notifier for a specified queue.
VRING_HOST_NOTIFIER_MSG = 3,
/// Virtio-fs draft: map file content into the window.
FS_MAP = 4,
/// Virtio-fs draft: unmap file content from the window.
FS_UNMAP = 5,
/// Virtio-fs draft: sync file content.
FS_SYNC = 6,
/// Upper bound of valid commands.
MAX_CMD = 7,
}
impl Into<u32> for SlaveReq {
fn into(self) -> u32 {
self as u32
}
}
impl Req for SlaveReq {
fn is_valid(&self) -> bool {
(*self > SlaveReq::NOOP) && (*self < SlaveReq::MAX_CMD)
}
}
/// Vhost message Validator.
pub trait VhostUserMsgValidator {
/// Validate message syntax only.
/// It doesn't validate message semantics such as protocol version number and dependency
/// on feature flags etc.
fn is_valid(&self) -> bool {
true
}
}
bitflags! {
/// Common message flags for vhost-user requests and replies.
pub struct VhostUserHeaderFlag: u32 {
/// Bits[0..2] is message version number.
const VERSION = 0x3;
/// Mark message as reply.
const REPLY = 0x4;
/// Sender anticipates a reply message from the peer.
const NEED_REPLY = 0x8;
/// All valid bits.
const ALL_FLAGS = 0xc;
/// All reserved bits.
const RESERVED_BITS = !0xf;
}
}
/// Common message header for vhost-user requests and replies.
/// A vhost-user message consists of 3 header fields and an optional payload. All numbers are in the
/// machine native byte order.
#[allow(safe_packed_borrows)]
#[repr(packed)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct VhostUserMsgHeader<R: Req> {
request: u32,
flags: u32,
size: u32,
_r: PhantomData<R>,
}
impl<R: Req> VhostUserMsgHeader<R> {
/// Create a new instance of `VhostUserMsgHeader`.
pub fn new(request: R, flags: u32, size: u32) -> Self {
// Default to protocol version 1
let fl = (flags & VhostUserHeaderFlag::ALL_FLAGS.bits()) | 0x1;
VhostUserMsgHeader {
request: request.into(),
flags: fl,
size,
_r: PhantomData,
}
}
/// Get message type.
pub fn get_code(&self) -> R {
// It's safe because R is marked as repr(u32).
unsafe { std::mem::transmute_copy::<u32, R>(&self.request) }
}
/// Set message type.
pub fn set_code(&mut self, request: R) {
self.request = request.into();
}
/// Get message version number.
pub fn get_version(&self) -> u32 {
self.flags & 0x3
}
/// Set message version number.
pub fn set_version(&mut self, ver: u32) {
self.flags &= !0x3;
self.flags |= ver & 0x3;
}
/// Check whether it's a reply message.
pub fn is_reply(&self) -> bool {
(self.flags & VhostUserHeaderFlag::REPLY.bits()) != 0
}
/// Mark message as reply.
pub fn set_reply(&mut self, is_reply: bool) {
if is_reply {
self.flags |= VhostUserHeaderFlag::REPLY.bits();
} else {
self.flags &= !VhostUserHeaderFlag::REPLY.bits();
}
}
/// Check whether reply for this message is requested.
pub fn is_need_reply(&self) -> bool {
(self.flags & VhostUserHeaderFlag::NEED_REPLY.bits()) != 0
}
/// Mark that reply for this message is needed.
pub fn set_need_reply(&mut self, need_reply: bool) {
if need_reply {
self.flags |= VhostUserHeaderFlag::NEED_REPLY.bits();
} else {
self.flags &= !VhostUserHeaderFlag::NEED_REPLY.bits();
}
}
/// Check whether it's the reply message for the request `req`.
pub fn is_reply_for(&self, req: &VhostUserMsgHeader<R>) -> bool {
self.is_reply() && !req.is_reply() && self.get_code() == req.get_code()
}
/// Get message size.
pub fn get_size(&self) -> u32 {
self.size
}
/// Set message size.
pub fn set_size(&mut self, size: u32) {
self.size = size;
}
}
impl<R: Req> Default for VhostUserMsgHeader<R> {
fn default() -> Self {
VhostUserMsgHeader {
request: 0,
flags: 0x1,
size: 0,
_r: PhantomData,
}
}
}
impl<T: Req> VhostUserMsgValidator for VhostUserMsgHeader<T> {
#[allow(clippy::if_same_then_else)]
fn is_valid(&self) -> bool {
if !self.get_code().is_valid() {
return false;
} else if self.size as usize > MAX_MSG_SIZE {
return false;
} else if self.get_version() != 0x1 {
return false;
} else if (self.flags & VhostUserHeaderFlag::RESERVED_BITS.bits()) != 0 {
return false;
}
true
}
}
bitflags! {
/// Transport specific flags in VirtIO feature set defined by vhost-user.
pub struct VhostUserVirtioFeatures: u64 {
/// Feature flag for the protocol feature.
const PROTOCOL_FEATURES = 0x4000_0000;
}
}
bitflags! {
/// Vhost-user protocol feature flags.
pub struct VhostUserProtocolFeatures: u64 {
/// Support multiple queues.
const MQ = 0x0000_0001;
/// Support logging through shared memory fd.
const LOG_SHMFD = 0x0000_0002;
/// Support broadcasting fake RARP packet.
const RARP = 0x0000_0004;
/// Support sending reply messages for requests with NEED_REPLY flag set.
const REPLY_ACK = 0x0000_0008;
/// Support setting MTU for virtio-net devices.
const MTU = 0x0000_0010;
/// Allow the slave to send requests to the master by an optional communication channel.
const SLAVE_REQ = 0x0000_0020;
/// Support setting slave endian by SET_VRING_ENDIAN.
const CROSS_ENDIAN = 0x0000_0040;
/// Support crypto operations.
const CRYPTO_SESSION = 0x0000_0080;
/// Support sending userfault_fd from slaves to masters.
const PAGEFAULT = 0x0000_0100;
/// Support Virtio device configuration.
const CONFIG = 0x0000_0200;
/// Allow the slave to send fds (at most 8 descriptors in each message) to the master.
const SLAVE_SEND_FD = 0x0000_0400;
/// Allow the slave to register a host notifier.
const HOST_NOTIFIER = 0x0000_0800;
/// Support inflight shmfd.
const INFLIGHT_SHMFD = 0x0000_1000;
}
}
/// A generic message to encapsulate a 64-bit value.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserU64 {
/// The encapsulated 64-bit common value.
pub value: u64,
}
impl VhostUserU64 {
/// Create a new instance.
pub fn new(value: u64) -> Self {
VhostUserU64 { value }
}
}
impl VhostUserMsgValidator for VhostUserU64 {}
/// Memory region descriptor for the SET_MEM_TABLE request.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserMemory {
/// Number of memory regions in the payload.
pub num_regions: u32,
/// Padding for alignment.
pub padding1: u32,
}
impl VhostUserMemory {
/// Create a new instance.
pub fn new(cnt: u32) -> Self {
VhostUserMemory {
num_regions: cnt,
padding1: 0,
}
}
}
impl VhostUserMsgValidator for VhostUserMemory {
#[allow(clippy::if_same_then_else)]
fn is_valid(&self) -> bool {
if self.padding1 != 0 {
return false;
} else if self.num_regions == 0 || self.num_regions > MAX_ATTACHED_FD_ENTRIES as u32 {
return false;
}
true
}
}
/// Memory region descriptors as payload for the SET_MEM_TABLE request.
#[repr(packed)]
#[derive(Default, Clone, Copy)]
pub struct VhostUserMemoryRegion {
/// Guest physical address of the memory region.
pub guest_phys_addr: u64,
/// Size of the memory region.
pub memory_size: u64,
/// Virtual address in the current process.
pub user_addr: u64,
/// Offset where region starts in the mapped memory.
pub mmap_offset: u64,
}
impl VhostUserMemoryRegion {
/// Create a new instance.
pub fn new(guest_phys_addr: u64, memory_size: u64, user_addr: u64, mmap_offset: u64) -> Self {
VhostUserMemoryRegion {
guest_phys_addr,
memory_size,
user_addr,
mmap_offset,
}
}
}
impl VhostUserMsgValidator for VhostUserMemoryRegion {
fn is_valid(&self) -> bool {
if self.memory_size == 0
|| self.guest_phys_addr.checked_add(self.memory_size).is_none()
|| self.user_addr.checked_add(self.memory_size).is_none()
|| self.mmap_offset.checked_add(self.memory_size).is_none()
{
return false;
}
true
}
}
/// Payload of the VhostUserMemory message.
pub type VhostUserMemoryPayload = Vec<VhostUserMemoryRegion>;
/// Vring state descriptor.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserVringState {
/// Vring index.
pub index: u32,
/// A common 32bit value to encapsulate vring state etc.
pub num: u32,
}
impl VhostUserVringState {
/// Create a new instance.
pub fn new(index: u32, num: u32) -> Self {
VhostUserVringState { index, num }
}
}
impl VhostUserMsgValidator for VhostUserVringState {}
bitflags! {
/// Flags for vring address.
pub struct VhostUserVringAddrFlags: u32 {
/// Support log of vring operations.
/// Modifications to "used" vring should be logged.
const VHOST_VRING_F_LOG = 0x1;
}
}
/// Vring address descriptor.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserVringAddr {
/// Vring index.
pub index: u32,
/// Vring flags defined by VhostUserVringAddrFlags.
pub flags: u32,
/// Ring address of the vring descriptor table.
pub descriptor: u64,
/// Ring address of the vring used ring.
pub used: u64,
/// Ring address of the vring available ring.
pub available: u64,
/// Guest address for logging.
pub log: u64,
}
impl VhostUserVringAddr {
/// Create a new instance.
pub fn new(
index: u32,
flags: VhostUserVringAddrFlags,
descriptor: u64,
used: u64,
available: u64,
log: u64,
) -> Self {
VhostUserVringAddr {
index,
flags: flags.bits(),
descriptor,
used,
available,
log,
}
}
/// Create a new instance from `VringConfigData`.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::identity_conversion))]
pub fn from_config_data(index: u32, config_data: &VringConfigData) -> Self {
let log_addr = config_data.log_addr.unwrap_or(0);
VhostUserVringAddr {
index,
flags: config_data.flags,
descriptor: config_data.desc_table_addr,
used: config_data.used_ring_addr,
available: config_data.avail_ring_addr,
log: log_addr,
}
}
}
impl VhostUserMsgValidator for VhostUserVringAddr {
#[allow(clippy::if_same_then_else)]
fn is_valid(&self) -> bool {
if (self.flags & !VhostUserVringAddrFlags::all().bits()) != 0 {
return false;
} else if self.descriptor & 0xf != 0 {
return false;
} else if self.available & 0x1 != 0 {
return false;
} else if self.used & 0x3 != 0 {
return false;
}
true
}
}
bitflags! {
/// Flags for the device configuration message.
pub struct VhostUserConfigFlags: u32 {
/// Vhost master messages used for writeable fields.
const WRITABLE = 0x0;
/// Vhost master messages used for live migration.
const LIVE_MIGRATION = 0x1;
}
}
/// Message to read/write device configuration space.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserConfig {
/// Offset of virtio device's configuration space.
pub offset: u32,
/// Configuration space access size in bytes.
pub size: u32,
/// Flags for the device configuration operation.
pub flags: u32,
}
impl VhostUserConfig {
/// Create a new instance.
pub fn new(offset: u32, size: u32, flags: VhostUserConfigFlags) -> Self {
VhostUserConfig {
offset,
size,
flags: flags.bits(),
}
}
}
impl VhostUserMsgValidator for VhostUserConfig {
#[allow(clippy::if_same_then_else)]
fn is_valid(&self) -> bool {
if (self.flags & !VhostUserConfigFlags::all().bits()) != 0 {
return false;
} else if self.offset >= VHOST_USER_CONFIG_SIZE
|| self.size == 0
|| self.size > VHOST_USER_CONFIG_SIZE
|| self.size + self.offset > VHOST_USER_CONFIG_SIZE
{
return false;
}
true
}
}
/// Payload for the VhostUserConfig message.
pub type VhostUserConfigPayload = Vec<u8>;
/*
* TODO: support dirty log, live migration and IOTLB operations.
#[repr(packed)]
pub struct VhostUserVringArea {
pub index: u32,
pub flags: u32,
pub size: u64,
pub offset: u64,
}
#[repr(packed)]
pub struct VhostUserLog {
pub size: u64,
pub offset: u64,
}
#[repr(packed)]
pub struct VhostUserIotlb {
pub iova: u64,
pub size: u64,
pub user_addr: u64,
pub permission: u8,
pub optype: u8,
}
*/
bitflags! {
#[derive(Default)]
/// Flags for virtio-fs slave messages.
pub struct VhostUserFSSlaveMsgFlags: u64 {
/// Empty permission.
const EMPTY = 0x0;
/// Read permission.
const MAP_R = 0x1;
/// Write permission.
const MAP_W = 0x2;
}
}
/// Max entries in one virtio-fs slave request.
const VHOST_USER_FS_SLAVE_ENTRIES: usize = 8;
/// Slave request message to update the MMIO window.
#[repr(packed)]
#[derive(Default)]
pub struct VhostUserFSSlaveMsg {
/// TODO:
pub fd_offset: [u64; VHOST_USER_FS_SLAVE_ENTRIES],
/// TODO:
pub cache_offset: [u64; VHOST_USER_FS_SLAVE_ENTRIES],
/// Size of region to map.
pub len: [u64; VHOST_USER_FS_SLAVE_ENTRIES],
/// Flags for the mmap operation
pub flags: [VhostUserFSSlaveMsgFlags; VHOST_USER_FS_SLAVE_ENTRIES],
}
impl VhostUserMsgValidator for VhostUserFSSlaveMsg {
fn is_valid(&self) -> bool {
for i in 0..VHOST_USER_FS_SLAVE_ENTRIES {
if ({ self.flags[i] }.bits() & !VhostUserFSSlaveMsgFlags::all().bits()) != 0
|| self.fd_offset[i].checked_add(self.len[i]).is_none()
|| self.cache_offset[i].checked_add(self.len[i]).is_none()
{
return false;
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn check_request_code() {
let code = MasterReq::NOOP;
assert!(!code.is_valid());
let code = MasterReq::MAX_CMD;
assert!(!code.is_valid());
let code = MasterReq::GET_FEATURES;
assert!(code.is_valid());
}
#[test]
fn msg_header_ops() {
let mut hdr = VhostUserMsgHeader::new(MasterReq::GET_FEATURES, 0, 0x100);
assert_eq!(hdr.get_code(), MasterReq::GET_FEATURES);
hdr.set_code(MasterReq::SET_FEATURES);
assert_eq!(hdr.get_code(), MasterReq::SET_FEATURES);
assert_eq!(hdr.get_version(), 0x1);
assert_eq!(hdr.is_reply(), false);
hdr.set_reply(true);
assert_eq!(hdr.is_reply(), true);
hdr.set_reply(false);
assert_eq!(hdr.is_need_reply(), false);
hdr.set_need_reply(true);
assert_eq!(hdr.is_need_reply(), true);
hdr.set_need_reply(false);
assert_eq!(hdr.get_size(), 0x100);
hdr.set_size(0x200);
assert_eq!(hdr.get_size(), 0x200);
assert_eq!(hdr.is_need_reply(), false);
assert_eq!(hdr.is_reply(), false);
assert_eq!(hdr.get_version(), 0x1);
// Check message length
assert!(hdr.is_valid());
hdr.set_size(0x2000);
assert!(!hdr.is_valid());
hdr.set_size(0x100);
assert_eq!(hdr.get_size(), 0x100);
assert!(hdr.is_valid());
hdr.set_size((MAX_MSG_SIZE - mem::size_of::<VhostUserMsgHeader<MasterReq>>()) as u32);
assert!(hdr.is_valid());
hdr.set_size(0x0);
assert!(hdr.is_valid());
// Check version
hdr.set_version(0x0);
assert!(!hdr.is_valid());
hdr.set_version(0x2);
assert!(!hdr.is_valid());
hdr.set_version(0x1);
assert!(hdr.is_valid());
}
#[test]
fn check_user_memory() {
let mut msg = VhostUserMemory::new(1);
assert!(msg.is_valid());
msg.num_regions = MAX_ATTACHED_FD_ENTRIES as u32;
assert!(msg.is_valid());
msg.num_regions += 1;
assert!(!msg.is_valid());
msg.num_regions = 0xFFFFFFFF;
assert!(!msg.is_valid());
msg.num_regions = MAX_ATTACHED_FD_ENTRIES as u32;
msg.padding1 = 1;
assert!(!msg.is_valid());
}
#[test]
fn check_user_memory_region() {
let mut msg = VhostUserMemoryRegion {
guest_phys_addr: 0,
memory_size: 0x1000,
user_addr: 0,
mmap_offset: 0,
};
assert!(msg.is_valid());
msg.guest_phys_addr = 0xFFFFFFFFFFFFEFFF;
assert!(msg.is_valid());
msg.guest_phys_addr = 0xFFFFFFFFFFFFF000;
assert!(!msg.is_valid());
msg.guest_phys_addr = 0xFFFFFFFFFFFF0000;
msg.memory_size = 0;
assert!(!msg.is_valid());
}
#[test]
fn check_user_vring_addr() {
let mut msg =
VhostUserVringAddr::new(0, VhostUserVringAddrFlags::all(), 0x0, 0x0, 0x0, 0x0);
assert!(msg.is_valid());
msg.descriptor = 1;
assert!(!msg.is_valid());
msg.descriptor = 0;
msg.available = 1;
assert!(!msg.is_valid());
msg.available = 0;
msg.used = 1;
assert!(!msg.is_valid());
msg.used = 0;
msg.flags |= 0x80000000;
assert!(!msg.is_valid());
msg.flags &= !0x80000000;
}
#[test]
fn check_user_config_msg() {
let mut msg = VhostUserConfig::new(
VHOST_USER_CONFIG_OFFSET,
VHOST_USER_CONFIG_SIZE - VHOST_USER_CONFIG_OFFSET,
VhostUserConfigFlags::WRITABLE,
);
assert!(msg.is_valid());
msg.size = 0;
assert!(!msg.is_valid());
msg.size = 1;
assert!(msg.is_valid());
msg.offset = 0;
assert!(!msg.is_valid());
msg.offset = VHOST_USER_CONFIG_SIZE;
assert!(!msg.is_valid());
msg.offset = VHOST_USER_CONFIG_SIZE - 1;
assert!(msg.is_valid());
msg.size = 2;
assert!(!msg.is_valid());
msg.size = 1;
msg.flags |= VhostUserConfigFlags::LIVE_MIGRATION.bits();
assert!(msg.is_valid());
msg.flags |= 0x4;
assert!(!msg.is_valid());
}
}

View File

@@ -1,251 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! The protocol for vhost-user is based on the existing implementation of vhost for the Linux
//! Kernel. The protocol defines two sides of the communication, master and slave. Master is
//! the application that shares its virtqueues. Slave is the consumer of the virtqueues.
//!
//! The communication channel between the master and the slave includes two sub channels. One is
//! used to send requests from the master to the slave and optional replies from the slave to the
//! master. This sub channel is created on master startup by connecting to the slave service
//! endpoint. The other is used to send requests from the slave to the master and optional replies
//! from the master to the slave. This sub channel is created by the master issuing a
//! VHOST_USER_SET_SLAVE_REQ_FD request to the slave with an auxiliary file descriptor.
//!
//! Unix domain socket is used as the underlying communication channel because the master needs to
//! send file descriptors to the slave.
//!
//! Most messages that can be sent via the Unix domain socket implementing vhost-user have an
//! equivalent ioctl to the kernel implementation.
use libc;
use std::io::Error as IOError;
mod connection;
pub mod message;
pub use self::connection::Listener;
#[cfg(feature = "vhost-user-master")]
mod master;
#[cfg(feature = "vhost-user-master")]
pub use self::master::{Master, VhostUserMaster};
#[cfg(feature = "vhost-user-master")]
mod master_req_handler;
#[cfg(feature = "vhost-user-master")]
pub use self::master_req_handler::{MasterReqHandler, VhostUserMasterReqHandler};
#[cfg(feature = "vhost-user-slave")]
mod slave;
#[cfg(feature = "vhost-user-slave")]
pub use self::slave::SlaveListener;
#[cfg(feature = "vhost-user-slave")]
mod slave_req_handler;
#[cfg(feature = "vhost-user-slave")]
pub use self::slave_req_handler::{SlaveReqHandler, VhostUserSlaveReqHandler};
pub mod sock_ctrl_msg;
/// Errors for vhost-user operations
#[derive(Debug)]
pub enum Error {
/// Invalid parameters.
InvalidParam,
/// Unsupported operations due to that the protocol feature hasn't been negotiated.
InvalidOperation,
/// Invalid message format, flag or content.
InvalidMessage,
/// Only part of a message have been sent or received successfully
PartialMessage,
/// Message is too large
OversizedMsg,
/// Fd array in question is too big or too small
IncorrectFds,
/// Can't connect to peer.
SocketConnect(std::io::Error),
/// Generic socket errors.
SocketError(std::io::Error),
/// The socket is broken or has been closed.
SocketBroken(std::io::Error),
/// Should retry the socket operation again.
SocketRetry(std::io::Error),
/// Failure from the slave side.
SlaveInternalError,
/// Virtio/protocol features mismatch.
FeatureMismatch,
/// Error from request handler
ReqHandlerError(IOError),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Error::InvalidParam => write!(f, "invalid parameters"),
Error::InvalidOperation => write!(f, "invalid operation"),
Error::InvalidMessage => write!(f, "invalid message"),
Error::PartialMessage => write!(f, "partial message"),
Error::OversizedMsg => write!(f, "oversized message"),
Error::IncorrectFds => write!(f, "wrong number of attached fds"),
Error::SocketError(e) => write!(f, "socket error: {}", e),
Error::SocketConnect(e) => write!(f, "can't connect to peer: {}", e),
Error::SocketBroken(e) => write!(f, "socket is broken: {}", e),
Error::SocketRetry(e) => write!(f, "temporary socket error: {}", e),
Error::SlaveInternalError => write!(f, "slave internal error"),
Error::FeatureMismatch => write!(f, "virtio/protocol features mismatch"),
Error::ReqHandlerError(e) => write!(f, "handler failed to handle request: {}", e),
}
}
}
impl Error {
/// Determine whether to rebuild the underline communication channel.
pub fn should_reconnect(&self) -> bool {
match *self {
// Should reconnect because it may be caused by temporary network errors.
Error::PartialMessage => true,
// Should reconnect because the underline socket is broken.
Error::SocketBroken(_) => true,
// Slave internal error, hope it recovers on reconnect.
Error::SlaveInternalError => true,
// Should just retry the IO operation instead of rebuilding the underline connection.
Error::SocketRetry(_) => false,
Error::InvalidParam | Error::InvalidOperation => false,
Error::InvalidMessage | Error::IncorrectFds | Error::OversizedMsg => false,
Error::SocketError(_) | Error::SocketConnect(_) => false,
Error::FeatureMismatch => false,
Error::ReqHandlerError(_) => false,
}
}
}
impl std::convert::From<vmm_sys_util::errno::Error> for Error {
/// Convert raw socket errors into meaningful vhost-user errors.
///
/// The vmm_sys_util::errno::Error is a simple wrapper over the raw errno, which doesn't means much
/// to the vhost-user connection manager. So convert it into meaningful errors to simplify
/// the connection manager logic.
///
/// # Return:
/// * - Error::SocketRetry: temporary error caused by signals or short of resources.
/// * - Error::SocketBroken: the underline socket is broken.
/// * - Error::SocketError: other socket related errors.
#[allow(unreachable_patterns)] // EWOULDBLOCK equals to EGAIN on linux
fn from(err: vmm_sys_util::errno::Error) -> Self {
match err.errno() {
// The socket is marked nonblocking and the requested operation would block.
libc::EAGAIN => Error::SocketRetry(IOError::from_raw_os_error(libc::EAGAIN)),
// The socket is marked nonblocking and the requested operation would block.
libc::EWOULDBLOCK => Error::SocketRetry(IOError::from_raw_os_error(libc::EWOULDBLOCK)),
// A signal occurred before any data was transmitted
libc::EINTR => Error::SocketRetry(IOError::from_raw_os_error(libc::EINTR)),
// The output queue for a network interface was full. This generally indicates
// that the interface has stopped sending, but may be caused by transient congestion.
libc::ENOBUFS => Error::SocketRetry(IOError::from_raw_os_error(libc::ENOBUFS)),
// No memory available.
libc::ENOMEM => Error::SocketRetry(IOError::from_raw_os_error(libc::ENOMEM)),
// Connection reset by peer.
libc::ECONNRESET => Error::SocketBroken(IOError::from_raw_os_error(libc::ECONNRESET)),
// The local end has been shut down on a connection oriented socket. In this case the
// process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.
libc::EPIPE => Error::SocketBroken(IOError::from_raw_os_error(libc::EPIPE)),
// Write permission is denied on the destination socket file, or search permission is
// denied for one of the directories the path prefix.
libc::EACCES => Error::SocketConnect(IOError::from_raw_os_error(libc::EACCES)),
// Catch all other errors
e => Error::SocketError(IOError::from_raw_os_error(e)),
}
}
}
/// Result of vhost-user operations
pub type Result<T> = std::result::Result<T, Error>;
/// Result of request handler.
pub type HandlerResult<T> = std::result::Result<T, IOError>;
#[cfg(all(test, feature = "vhost-user-master", feature = "vhost-user-slave"))]
mod dummy_slave;
#[cfg(all(test, feature = "vhost-user-master", feature = "vhost-user-slave"))]
mod tests {
use super::dummy_slave::{DummySlaveReqHandler, VIRTIO_FEATURES};
use super::message::*;
use super::*;
use crate::backend::VhostBackend;
use std::sync::{Arc, Barrier, Mutex};
use std::thread;
fn create_slave<S: VhostUserSlaveReqHandler>(
path: &str,
backend: Arc<Mutex<S>>,
) -> (Master, SlaveReqHandler<S>) {
let mut slave_listener = SlaveListener::new(path, true, backend).unwrap();
let master = Master::connect(path).unwrap();
(master, slave_listener.accept().unwrap().unwrap())
}
#[test]
fn create_dummy_slave() {
let mut slave = DummySlaveReqHandler::new();
slave.set_owner().unwrap();
assert!(slave.set_owner().is_err());
}
#[test]
fn test_set_owner() {
let slave_be = Arc::new(Mutex::new(DummySlaveReqHandler::new()));
let (mut master, mut slave) =
create_slave("/tmp/vhost_user_lib_unit_test_owner", slave_be.clone());
assert_eq!(slave_be.lock().unwrap().owned, false);
master.set_owner().unwrap();
slave.handle_request().unwrap();
assert_eq!(slave_be.lock().unwrap().owned, true);
master.set_owner().unwrap();
assert!(slave.handle_request().is_err());
assert_eq!(slave_be.lock().unwrap().owned, true);
}
#[test]
fn test_set_features() {
let mbar = Arc::new(Barrier::new(2));
let sbar = mbar.clone();
let slave_be = Arc::new(Mutex::new(DummySlaveReqHandler::new()));
let (mut master, mut slave) =
create_slave("/tmp/vhost_user_lib_unit_test_feature", slave_be.clone());
thread::spawn(move || {
slave.handle_request().unwrap();
assert_eq!(slave_be.lock().unwrap().owned, true);
slave.handle_request().unwrap();
slave.handle_request().unwrap();
assert_eq!(
slave_be.lock().unwrap().acked_features,
VIRTIO_FEATURES & !0x1
);
slave.handle_request().unwrap();
slave.handle_request().unwrap();
assert_eq!(
slave_be.lock().unwrap().acked_protocol_features,
VhostUserProtocolFeatures::all().bits()
);
sbar.wait();
});
master.set_owner().unwrap();
// set virtio features
let features = master.get_features().unwrap();
assert_eq!(features, VIRTIO_FEATURES);
master.set_features(VIRTIO_FEATURES & !0x1).unwrap();
// set vhost protocol features
let features = master.get_protocol_features().unwrap();
assert_eq!(features.bits(), VhostUserProtocolFeatures::all().bits());
master.set_protocol_features(features).unwrap();
mbar.wait();
}
}

View File

@@ -1,48 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Traits and Structs for vhost-user slave.
use std::sync::{Arc, Mutex};
use super::connection::{Endpoint, Listener};
use super::message::*;
use super::{Result, SlaveReqHandler, VhostUserSlaveReqHandler};
/// Vhost-user slave side connection listener.
pub struct SlaveListener<S: VhostUserSlaveReqHandler> {
listener: Listener,
backend: Option<Arc<Mutex<S>>>,
}
/// Sets up a listener for incoming master connections, and handles construction
/// of a Slave on success.
impl<S: VhostUserSlaveReqHandler> SlaveListener<S> {
/// Create a unix domain socket for incoming master connections.
///
/// Be careful, the file at `path` will be unlinked if unlink is true
pub fn new(path: &str, unlink: bool, backend: Arc<Mutex<S>>) -> Result<Self> {
Ok(SlaveListener {
listener: Listener::new(path, unlink)?,
backend: Some(backend),
})
}
/// Accept an incoming connection from the master, returning Some(Slave) on
/// success, or None if the socket is nonblocking and no incoming connection
/// was detected
pub fn accept(&mut self) -> Result<Option<SlaveReqHandler<S>>> {
if let Some(fd) = self.listener.accept()? {
return Ok(Some(SlaveReqHandler::new(
Endpoint::<MasterReq>::from_stream(fd),
self.backend.take().unwrap(),
)));
}
Ok(None)
}
/// Change blocking status on the listener.
pub fn set_nonblocking(&self, block: bool) -> Result<()> {
self.listener.set_nonblocking(block)
}
}

View File

@@ -1,582 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//! Traits and Structs to handle vhost-user requests from the master to the slave.
use std::mem;
use std::os::unix::io::{AsRawFd, RawFd};
use std::slice;
use std::sync::{Arc, Mutex};
use super::connection::Endpoint;
use super::message::*;
use super::{Error, Result};
/// Trait to handle vhost-user requests from the master to the slave.
#[allow(missing_docs)]
pub trait VhostUserSlaveReqHandler {
fn set_owner(&mut self) -> Result<()>;
fn reset_owner(&mut self) -> Result<()>;
fn get_features(&mut self) -> Result<u64>;
fn set_features(&mut self, features: u64) -> Result<()>;
fn set_mem_table(&mut self, ctx: &[VhostUserMemoryRegion], fds: &[RawFd]) -> Result<()>;
fn set_vring_num(&mut self, index: u32, num: u32) -> Result<()>;
fn set_vring_addr(
&mut self,
index: u32,
flags: VhostUserVringAddrFlags,
descriptor: u64,
used: u64,
available: u64,
log: u64,
) -> Result<()>;
fn set_vring_base(&mut self, index: u32, base: u32) -> Result<()>;
fn get_vring_base(&mut self, index: u32) -> Result<VhostUserVringState>;
fn set_vring_kick(&mut self, index: u8, fd: Option<RawFd>) -> Result<()>;
fn set_vring_call(&mut self, index: u8, fd: Option<RawFd>) -> Result<()>;
fn set_vring_err(&mut self, index: u8, fd: Option<RawFd>) -> Result<()>;
fn get_protocol_features(&mut self) -> Result<VhostUserProtocolFeatures>;
fn set_protocol_features(&mut self, features: u64) -> Result<()>;
fn get_queue_num(&mut self) -> Result<u64>;
fn set_vring_enable(&mut self, index: u32, enable: bool) -> Result<()>;
fn get_config(
&mut self,
offset: u32,
size: u32,
flags: VhostUserConfigFlags,
) -> Result<Vec<u8>>;
fn set_config(&mut self, offset: u32, buf: &[u8], flags: VhostUserConfigFlags) -> Result<()>;
}
/// A vhost-user slave endpoint which relays all received requests from the
/// master to the virtio backend device object.
///
/// The lifetime of the SlaveReqHandler object should be the same as the underline Unix Domain
/// Socket, so it gets simpler to recover from disconnect.
pub struct SlaveReqHandler<S: VhostUserSlaveReqHandler> {
// underlying Unix domain socket for communication
main_sock: Endpoint<MasterReq>,
// the vhost-user backend device object
backend: Arc<Mutex<S>>,
virtio_features: u64,
acked_virtio_features: u64,
protocol_features: VhostUserProtocolFeatures,
acked_protocol_features: u64,
// sending ack for messages without payload
reply_ack_enabled: bool,
// whether the endpoint has encountered any failure
error: Option<i32>,
}
impl<S: VhostUserSlaveReqHandler> SlaveReqHandler<S> {
/// Create a vhost-user slave endpoint.
pub(super) fn new(main_sock: Endpoint<MasterReq>, backend: Arc<Mutex<S>>) -> Self {
SlaveReqHandler {
main_sock,
backend,
virtio_features: 0,
acked_virtio_features: 0,
protocol_features: VhostUserProtocolFeatures::empty(),
acked_protocol_features: 0,
reply_ack_enabled: false,
error: None,
}
}
/// Create a new vhost-user slave endpoint.
///
/// # Arguments
/// * - `path` - path of Unix domain socket listener to connect to
/// * - `backend` - handler for requests from the master to the slave
pub fn connect(path: &str, backend: Arc<Mutex<S>>) -> Result<Self> {
Ok(Self::new(Endpoint::<MasterReq>::connect(path)?, backend))
}
/// Mark endpoint as failed with specified error code.
pub fn set_failed(&mut self, error: i32) {
self.error = Some(error);
}
/// Receive and handle one incoming request message from the master.
/// The caller needs to:
/// . serialize calls to this function
/// . decide what to do when error happens
/// . optional recover from failure
pub fn handle_request(&mut self) -> Result<()> {
// Return error if the endpoint is already in failed state.
self.check_state()?;
// The underlying communication channel is a Unix domain socket in
// stream mode, and recvmsg() is a little tricky here. To successfully
// receive attached file descriptors, we need to receive messages and
// corresponding attached file descriptors in this way:
// . recv messsage header and optional attached file
// . validate message header
// . recv optional message body and payload according size field in
// message header
// . validate message body and optional payload
let (hdr, rfds) = self.main_sock.recv_header()?;
let rfds = self.check_attached_rfds(&hdr, rfds)?;
let (size, buf) = match hdr.get_size() {
0 => (0, vec![0u8; 0]),
len => {
let (size2, rbuf) = self.main_sock.recv_data(len as usize)?;
if size2 != len as usize {
return Err(Error::InvalidMessage);
}
(size2, rbuf)
}
};
match hdr.get_code() {
MasterReq::SET_OWNER => {
self.check_request_size(&hdr, size, 0)?;
self.backend.lock().unwrap().set_owner()?;
}
MasterReq::RESET_OWNER => {
self.check_request_size(&hdr, size, 0)?;
self.backend.lock().unwrap().reset_owner()?;
}
MasterReq::GET_FEATURES => {
self.check_request_size(&hdr, size, 0)?;
let features = self.backend.lock().unwrap().get_features()?;
let msg = VhostUserU64::new(features);
self.send_reply_message(&hdr, &msg)?;
self.virtio_features = features;
self.update_reply_ack_flag();
}
MasterReq::SET_FEATURES => {
let msg = self.extract_request_body::<VhostUserU64>(&hdr, size, &buf)?;
self.backend.lock().unwrap().set_features(msg.value)?;
self.acked_virtio_features = msg.value;
self.update_reply_ack_flag();
}
MasterReq::SET_MEM_TABLE => {
let res = self.set_mem_table(&hdr, size, &buf, rfds);
self.send_ack_message(&hdr, res)?;
}
MasterReq::SET_VRING_NUM => {
let msg = self.extract_request_body::<VhostUserVringState>(&hdr, size, &buf)?;
let res = self
.backend
.lock()
.unwrap()
.set_vring_num(msg.index, msg.num);
self.send_ack_message(&hdr, res)?;
}
MasterReq::SET_VRING_ADDR => {
let msg = self.extract_request_body::<VhostUserVringAddr>(&hdr, size, &buf)?;
let flags = match VhostUserVringAddrFlags::from_bits(msg.flags) {
Some(val) => val,
None => return Err(Error::InvalidMessage),
};
let res = self.backend.lock().unwrap().set_vring_addr(
msg.index,
flags,
msg.descriptor,
msg.used,
msg.available,
msg.log,
);
self.send_ack_message(&hdr, res)?;
}
MasterReq::SET_VRING_BASE => {
let msg = self.extract_request_body::<VhostUserVringState>(&hdr, size, &buf)?;
let res = self
.backend
.lock()
.unwrap()
.set_vring_base(msg.index, msg.num);
self.send_ack_message(&hdr, res)?;
}
MasterReq::GET_VRING_BASE => {
let msg = self.extract_request_body::<VhostUserVringState>(&hdr, size, &buf)?;
let reply = self.backend.lock().unwrap().get_vring_base(msg.index)?;
self.send_reply_message(&hdr, &reply)?;
}
MasterReq::SET_VRING_CALL => {
self.check_request_size(&hdr, size, mem::size_of::<VhostUserU64>())?;
let (index, rfds) = self.handle_vring_fd_request(&buf, rfds)?;
let res = self.backend.lock().unwrap().set_vring_call(index, rfds);
self.send_ack_message(&hdr, res)?;
}
MasterReq::SET_VRING_KICK => {
self.check_request_size(&hdr, size, mem::size_of::<VhostUserU64>())?;
let (index, rfds) = self.handle_vring_fd_request(&buf, rfds)?;
let res = self.backend.lock().unwrap().set_vring_kick(index, rfds);
self.send_ack_message(&hdr, res)?;
}
MasterReq::SET_VRING_ERR => {
self.check_request_size(&hdr, size, mem::size_of::<VhostUserU64>())?;
let (index, rfds) = self.handle_vring_fd_request(&buf, rfds)?;
let res = self.backend.lock().unwrap().set_vring_err(index, rfds);
self.send_ack_message(&hdr, res)?;
}
MasterReq::GET_PROTOCOL_FEATURES => {
self.check_request_size(&hdr, size, 0)?;
let features = self.backend.lock().unwrap().get_protocol_features()?;
let msg = VhostUserU64::new(features.bits());
self.send_reply_message(&hdr, &msg)?;
self.protocol_features = features;
self.update_reply_ack_flag();
}
MasterReq::SET_PROTOCOL_FEATURES => {
let msg = self.extract_request_body::<VhostUserU64>(&hdr, size, &buf)?;
self.backend
.lock()
.unwrap()
.set_protocol_features(msg.value)?;
self.acked_protocol_features = msg.value;
self.update_reply_ack_flag();
}
MasterReq::GET_QUEUE_NUM => {
if self.acked_protocol_features & VhostUserProtocolFeatures::MQ.bits() == 0 {
return Err(Error::InvalidOperation);
}
self.check_request_size(&hdr, size, 0)?;
let num = self.backend.lock().unwrap().get_queue_num()?;
let msg = VhostUserU64::new(num);
self.send_reply_message(&hdr, &msg)?;
}
MasterReq::SET_VRING_ENABLE => {
let msg = self.extract_request_body::<VhostUserVringState>(&hdr, size, &buf)?;
if self.acked_protocol_features & VhostUserProtocolFeatures::MQ.bits() == 0
&& msg.index > 0
{
return Err(Error::InvalidOperation);
}
let enable = match msg.num {
1 => true,
0 => false,
_ => return Err(Error::InvalidParam),
};
let res = self
.backend
.lock()
.unwrap()
.set_vring_enable(msg.index, enable);
self.send_ack_message(&hdr, res)?;
}
MasterReq::GET_CONFIG => {
if self.acked_protocol_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return Err(Error::InvalidOperation);
}
self.check_request_size(&hdr, size, mem::size_of::<VhostUserConfig>())?;
self.get_config(&hdr, &buf)?;
}
MasterReq::SET_CONFIG => {
if self.acked_protocol_features & VhostUserProtocolFeatures::CONFIG.bits() == 0 {
return Err(Error::InvalidOperation);
}
self.check_request_size(&hdr, size, hdr.get_size() as usize)?;
self.set_config(&hdr, size, &buf)?;
}
_ => {
return Err(Error::InvalidMessage);
}
}
Ok(())
}
fn set_mem_table(
&mut self,
hdr: &VhostUserMsgHeader<MasterReq>,
size: usize,
buf: &[u8],
rfds: Option<Vec<RawFd>>,
) -> Result<()> {
self.check_request_size(&hdr, size, hdr.get_size() as usize)?;
// check message size is consistent
let hdrsize = mem::size_of::<VhostUserMemory>();
if size < hdrsize {
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(Error::InvalidMessage);
}
let msg = unsafe { &*(buf.as_ptr() as *const VhostUserMemory) };
if !msg.is_valid() {
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(Error::InvalidMessage);
}
if size != hdrsize + msg.num_regions as usize * mem::size_of::<VhostUserMemoryRegion>() {
Endpoint::<MasterReq>::close_rfds(rfds);
return Err(Error::InvalidMessage);
}
// validate number of fds matching number of memory regions
let fds = match rfds {
None => return Err(Error::InvalidMessage),
Some(fds) => {
if fds.len() != msg.num_regions as usize {
Endpoint::<MasterReq>::close_rfds(Some(fds));
return Err(Error::InvalidMessage);
}
fds
}
};
// Validate memory regions
let regions = unsafe {
slice::from_raw_parts(
buf.as_ptr().add(hdrsize) as *const VhostUserMemoryRegion,
msg.num_regions as usize,
)
};
for region in regions.iter() {
if !region.is_valid() {
Endpoint::<MasterReq>::close_rfds(Some(fds));
return Err(Error::InvalidMessage);
}
}
self.backend.lock().unwrap().set_mem_table(&regions, &fds)
}
fn get_config(&mut self, hdr: &VhostUserMsgHeader<MasterReq>, buf: &[u8]) -> Result<()> {
let msg = unsafe { &*(buf.as_ptr() as *const VhostUserConfig) };
if !msg.is_valid() {
return Err(Error::InvalidMessage);
}
let flags = match VhostUserConfigFlags::from_bits(msg.flags) {
Some(val) => val,
None => return Err(Error::InvalidMessage),
};
let res = self
.backend
.lock()
.unwrap()
.get_config(msg.offset, msg.size, flags);
// vhost-user slave's payload size MUST match master's request
// on success, uses zero length of payload to indicate an error
// to vhost-user master.
match res {
Ok(ref buf) if buf.len() == msg.size as usize => {
let reply = VhostUserConfig::new(msg.offset, buf.len() as u32, flags);
self.send_reply_with_payload(&hdr, &reply, buf.as_slice())?;
}
Ok(_) => {
let reply = VhostUserConfig::new(msg.offset, 0, flags);
self.send_reply_message(&hdr, &reply)?;
}
Err(_) => {
let reply = VhostUserConfig::new(msg.offset, 0, flags);
self.send_reply_message(&hdr, &reply)?;
}
}
Ok(())
}
fn set_config(
&mut self,
hdr: &VhostUserMsgHeader<MasterReq>,
size: usize,
buf: &[u8],
) -> Result<()> {
if size < mem::size_of::<VhostUserConfig>() {
return Err(Error::InvalidMessage);
}
let msg = unsafe { &*(buf.as_ptr() as *const VhostUserConfig) };
if !msg.is_valid() {
return Err(Error::InvalidMessage);
}
if size - mem::size_of::<VhostUserConfig>() != msg.size as usize {
return Err(Error::InvalidMessage);
}
let flags: VhostUserConfigFlags;
match VhostUserConfigFlags::from_bits(msg.flags) {
Some(val) => flags = val,
None => return Err(Error::InvalidMessage),
}
let res = self
.backend
.lock()
.unwrap()
.set_config(msg.offset, buf, flags);
self.send_ack_message(&hdr, res)?;
Ok(())
}
fn handle_vring_fd_request(
&mut self,
buf: &[u8],
rfds: Option<Vec<RawFd>>,
) -> Result<(u8, Option<RawFd>)> {
let msg = unsafe { &*(buf.as_ptr() as *const VhostUserU64) };
if !msg.is_valid() {
return Err(Error::InvalidMessage);
}
// Bits (0-7) of the payload contain the vring index. Bit 8 is the
// invalid FD flag. This flag is set when there is no file descriptor
// in the ancillary data. This signals that polling will be used
// instead of waiting for the call.
let nofd = match msg.value & 0x100u64 {
0x100u64 => true,
_ => false,
};
let mut rfd = None;
match rfds {
Some(fds) => {
if !nofd && fds.len() == 1 {
rfd = Some(fds[0]);
} else if (nofd && !fds.is_empty()) || (!nofd && fds.len() != 1) {
Endpoint::<MasterReq>::close_rfds(Some(fds));
return Err(Error::InvalidMessage);
}
}
None => {
if !nofd {
return Err(Error::InvalidMessage);
}
}
}
Ok((msg.value as u8, rfd))
}
fn check_state(&self) -> Result<()> {
match self.error {
Some(e) => Err(Error::SocketBroken(std::io::Error::from_raw_os_error(e))),
None => Ok(()),
}
}
fn check_request_size(
&self,
hdr: &VhostUserMsgHeader<MasterReq>,
size: usize,
expected: usize,
) -> Result<()> {
if hdr.get_size() as usize != expected
|| hdr.is_reply()
|| hdr.get_version() != 0x1
|| size != expected
{
return Err(Error::InvalidMessage);
}
Ok(())
}
fn check_attached_rfds(
&self,
hdr: &VhostUserMsgHeader<MasterReq>,
rfds: Option<Vec<RawFd>>,
) -> Result<Option<Vec<RawFd>>> {
match hdr.get_code() {
MasterReq::SET_MEM_TABLE => Ok(rfds),
MasterReq::SET_VRING_CALL => Ok(rfds),
MasterReq::SET_VRING_KICK => Ok(rfds),
MasterReq::SET_VRING_ERR => Ok(rfds),
MasterReq::SET_LOG_BASE => Ok(rfds),
MasterReq::SET_LOG_FD => Ok(rfds),
MasterReq::SET_SLAVE_REQ_FD => Ok(rfds),
MasterReq::SET_INFLIGHT_FD => Ok(rfds),
_ => {
if rfds.is_some() {
Endpoint::<MasterReq>::close_rfds(rfds);
Err(Error::InvalidMessage)
} else {
Ok(rfds)
}
}
}
}
fn extract_request_body<'a, T: Sized + VhostUserMsgValidator>(
&self,
hdr: &VhostUserMsgHeader<MasterReq>,
size: usize,
buf: &'a [u8],
) -> Result<&'a T> {
self.check_request_size(hdr, size, mem::size_of::<T>())?;
let msg = unsafe { &*(buf.as_ptr() as *const T) };
if !msg.is_valid() {
return Err(Error::InvalidMessage);
}
Ok(msg)
}
fn update_reply_ack_flag(&mut self) {
let vflag = VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits();
let pflag = VhostUserProtocolFeatures::REPLY_ACK;
if (self.virtio_features & vflag) != 0
&& (self.acked_virtio_features & vflag) != 0
&& self.protocol_features.contains(pflag)
&& (self.acked_protocol_features & pflag.bits()) != 0
{
self.reply_ack_enabled = true;
} else {
self.reply_ack_enabled = false;
}
}
fn new_reply_header<T: Sized>(
&self,
req: &VhostUserMsgHeader<MasterReq>,
) -> Result<VhostUserMsgHeader<MasterReq>> {
if mem::size_of::<T>() > MAX_MSG_SIZE {
return Err(Error::InvalidParam);
}
self.check_state()?;
Ok(VhostUserMsgHeader::new(
req.get_code(),
VhostUserHeaderFlag::REPLY.bits(),
mem::size_of::<T>() as u32,
))
}
fn send_ack_message(
&mut self,
req: &VhostUserMsgHeader<MasterReq>,
res: Result<()>,
) -> Result<()> {
if self.reply_ack_enabled {
let hdr = self.new_reply_header::<VhostUserU64>(req)?;
let val = match res {
Ok(_) => 0,
Err(_) => 1,
};
let msg = VhostUserU64::new(val);
self.main_sock.send_message(&hdr, &msg, None)?;
}
Ok(())
}
fn send_reply_message<T>(
&mut self,
req: &VhostUserMsgHeader<MasterReq>,
msg: &T,
) -> Result<()> {
let hdr = self.new_reply_header::<T>(req)?;
self.main_sock.send_message(&hdr, msg, None)?;
Ok(())
}
fn send_reply_with_payload<T, P>(
&mut self,
req: &VhostUserMsgHeader<MasterReq>,
msg: &T,
payload: &[P],
) -> Result<()>
where
T: Sized,
P: Sized,
{
let hdr = self.new_reply_header::<T>(req)?;
self.main_sock
.send_message_with_payload(&hdr, msg, payload, None)?;
Ok(())
}
}
impl<S: VhostUserSlaveReqHandler> AsRawFd for SlaveReqHandler<S> {
fn as_raw_fd(&self) -> RawFd {
self.main_sock.as_raw_fd()
}
}

View File

@@ -1,464 +0,0 @@
// Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Used to send and receive messages with file descriptors on sockets that accept control messages
//! (e.g. Unix domain sockets).
// TODO: move this file into the vmm-sys-util crate
use std::fs::File;
use std::mem::size_of;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::os::unix::net::{UnixDatagram, UnixStream};
use std::ptr::{copy_nonoverlapping, null_mut, write_unaligned};
use libc::{
c_long, c_void, cmsghdr, iovec, msghdr, recvmsg, sendmsg, MSG_NOSIGNAL, SCM_RIGHTS, SOL_SOCKET,
};
use vmm_sys_util::errno::{Error, Result};
// Each of the following macros performs the same function as their C counterparts. They are each
// macros because they are used to size statically allocated arrays.
macro_rules! CMSG_ALIGN {
($len:expr) => {
(($len) + size_of::<c_long>() - 1) & !(size_of::<c_long>() - 1)
};
}
macro_rules! CMSG_SPACE {
($len:expr) => {
size_of::<cmsghdr>() + CMSG_ALIGN!($len)
};
}
macro_rules! CMSG_LEN {
($len:expr) => {
size_of::<cmsghdr>() + ($len)
};
}
// This function (macro in the C version) is not used in any compile time constant slots, so is just
// an ordinary function. The returned pointer is hard coded to be RawFd because that's all that this
// module supports.
#[allow(non_snake_case)]
#[inline(always)]
fn CMSG_DATA(cmsg_buffer: *mut cmsghdr) -> *mut RawFd {
// Essentially returns a pointer to just past the header.
cmsg_buffer.wrapping_offset(1) as *mut RawFd
}
// This function is like CMSG_NEXT, but safer because it reads only from references, although it
// does some pointer arithmetic on cmsg_ptr.
#[cfg_attr(feature = "cargo-clippy", allow(clippy::cast_ptr_alignment))]
fn get_next_cmsg(msghdr: &msghdr, cmsg: &cmsghdr, cmsg_ptr: *mut cmsghdr) -> *mut cmsghdr {
let next_cmsg = (cmsg_ptr as *mut u8).wrapping_add(CMSG_ALIGN!(cmsg.cmsg_len)) as *mut cmsghdr;
if next_cmsg
.wrapping_offset(1)
.wrapping_sub(msghdr.msg_control as usize) as usize
> msghdr.msg_controllen
{
null_mut()
} else {
next_cmsg
}
}
const CMSG_BUFFER_INLINE_CAPACITY: usize = CMSG_SPACE!(size_of::<RawFd>() * 32);
enum CmsgBuffer {
Inline([u64; (CMSG_BUFFER_INLINE_CAPACITY + 7) / 8]),
Heap(Box<[cmsghdr]>),
}
impl CmsgBuffer {
fn with_capacity(capacity: usize) -> CmsgBuffer {
let cap_in_cmsghdr_units =
(capacity.checked_add(size_of::<cmsghdr>()).unwrap() - 1) / size_of::<cmsghdr>();
if capacity <= CMSG_BUFFER_INLINE_CAPACITY {
CmsgBuffer::Inline([0u64; (CMSG_BUFFER_INLINE_CAPACITY + 7) / 8])
} else {
CmsgBuffer::Heap(
vec![
cmsghdr {
cmsg_len: 0,
cmsg_level: 0,
cmsg_type: 0,
};
cap_in_cmsghdr_units
]
.into_boxed_slice(),
)
}
}
fn as_mut_ptr(&mut self) -> *mut cmsghdr {
match self {
CmsgBuffer::Inline(a) => a.as_mut_ptr() as *mut cmsghdr,
CmsgBuffer::Heap(a) => a.as_mut_ptr(),
}
}
}
fn raw_sendmsg<D: IntoIovec>(fd: RawFd, out_data: &[D], out_fds: &[RawFd]) -> Result<usize> {
let cmsg_capacity = CMSG_SPACE!(size_of::<RawFd>() * out_fds.len());
let mut cmsg_buffer = CmsgBuffer::with_capacity(cmsg_capacity);
let mut iovecs = Vec::with_capacity(out_data.len());
for data in out_data {
iovecs.push(iovec {
iov_base: data.as_ptr() as *mut c_void,
iov_len: data.size(),
});
}
let mut msg = msghdr {
msg_name: null_mut(),
msg_namelen: 0,
msg_iov: iovecs.as_mut_ptr(),
msg_iovlen: iovecs.len(),
msg_control: null_mut(),
msg_controllen: 0,
msg_flags: 0,
};
if !out_fds.is_empty() {
let cmsg = cmsghdr {
cmsg_len: CMSG_LEN!(size_of::<RawFd>() * out_fds.len()),
cmsg_level: SOL_SOCKET,
cmsg_type: SCM_RIGHTS,
};
unsafe {
// Safe because cmsg_buffer was allocated to be large enough to contain cmsghdr.
write_unaligned(cmsg_buffer.as_mut_ptr() as *mut cmsghdr, cmsg);
// Safe because the cmsg_buffer was allocated to be large enough to hold out_fds.len()
// file descriptors.
copy_nonoverlapping(
out_fds.as_ptr(),
CMSG_DATA(cmsg_buffer.as_mut_ptr()),
out_fds.len(),
);
}
msg.msg_control = cmsg_buffer.as_mut_ptr() as *mut c_void;
msg.msg_controllen = cmsg_capacity;
}
// Safe because the msghdr was properly constructed from valid (or null) pointers of the
// indicated length and we check the return value.
let write_count = unsafe { sendmsg(fd, &msg, MSG_NOSIGNAL) };
if write_count == -1 {
Err(Error::last())
} else {
Ok(write_count as usize)
}
}
fn raw_recvmsg(fd: RawFd, iovecs: &mut [iovec], in_fds: &mut [RawFd]) -> Result<(usize, usize)> {
let cmsg_capacity = CMSG_SPACE!(size_of::<RawFd>() * in_fds.len());
let mut cmsg_buffer = CmsgBuffer::with_capacity(cmsg_capacity);
let mut msg = msghdr {
msg_name: null_mut(),
msg_namelen: 0,
msg_iov: iovecs.as_mut_ptr(),
msg_iovlen: iovecs.len(),
msg_control: null_mut(),
msg_controllen: 0,
msg_flags: 0,
};
if !in_fds.is_empty() {
msg.msg_control = cmsg_buffer.as_mut_ptr() as *mut c_void;
msg.msg_controllen = cmsg_capacity;
}
// Safe because the msghdr was properly constructed from valid (or null) pointers of the
// indicated length and we check the return value.
let total_read = unsafe { recvmsg(fd, &mut msg, libc::MSG_WAITALL) };
if total_read == -1 {
return Err(Error::last());
}
if total_read == 0 && msg.msg_controllen < size_of::<cmsghdr>() {
return Ok((0, 0));
}
let mut cmsg_ptr = msg.msg_control as *mut cmsghdr;
let mut in_fds_count = 0;
while !cmsg_ptr.is_null() {
// Safe because we checked that cmsg_ptr was non-null, and the loop is constructed such that
// that only happens when there is at least sizeof(cmsghdr) space after the pointer to read.
let cmsg = unsafe { (cmsg_ptr as *mut cmsghdr).read_unaligned() };
if cmsg.cmsg_level == SOL_SOCKET && cmsg.cmsg_type == SCM_RIGHTS {
let fd_count = (cmsg.cmsg_len - CMSG_LEN!(0)) / size_of::<RawFd>();
unsafe {
copy_nonoverlapping(
CMSG_DATA(cmsg_ptr),
in_fds[in_fds_count..(in_fds_count + fd_count)].as_mut_ptr(),
fd_count,
);
}
in_fds_count += fd_count;
}
cmsg_ptr = get_next_cmsg(&msg, &cmsg, cmsg_ptr);
}
Ok((total_read as usize, in_fds_count))
}
/// Trait for file descriptors can send and receive socket control messages via `sendmsg` and
/// `recvmsg`.
pub trait ScmSocket {
/// Gets the file descriptor of this socket.
fn socket_fd(&self) -> RawFd;
/// Sends the given data and file descriptor over the socket.
///
/// On success, returns the number of bytes sent.
///
/// # Arguments
///
/// * `buf` - A buffer of data to send on the `socket`.
/// * `fd` - A file descriptors to be sent.
fn send_with_fd<D: IntoIovec>(&self, buf: D, fd: RawFd) -> Result<usize> {
self.send_with_fds(&[buf], &[fd])
}
/// Sends the given data and file descriptors over the socket.
///
/// On success, returns the number of bytes sent.
///
/// # Arguments
///
/// * `bufs` - A list of data buffer to send on the `socket`.
/// * `fds` - A list of file descriptors to be sent.
fn send_with_fds<D: IntoIovec>(&self, bufs: &[D], fds: &[RawFd]) -> Result<usize> {
raw_sendmsg(self.socket_fd(), bufs, fds)
}
/// Receives data and potentially a file descriptor from the socket.
///
/// On success, returns the number of bytes and an optional file descriptor.
///
/// # Arguments
///
/// * `buf` - A buffer to receive data from the socket.
fn recv_with_fd(&self, buf: &mut [u8]) -> Result<(usize, Option<File>)> {
let mut fd = [0];
let mut iovecs = [iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf.len(),
}];
let (read_count, fd_count) = self.recv_with_fds(&mut iovecs[..], &mut fd)?;
let file = if fd_count == 0 {
None
} else {
// Safe because the first fd from recv_with_fds is owned by us and valid because this
// branch was taken.
Some(unsafe { File::from_raw_fd(fd[0]) })
};
Ok((read_count, file))
}
/// Receives data and file descriptors from the socket.
///
/// On success, returns the number of bytes and file descriptors received as a tuple
/// `(bytes count, files count)`.
///
/// # Arguments
///
/// * `iovecs` - A list of iovec to receive data from the socket.
/// * `fds` - A slice of `RawFd`s to put the received file descriptors into. On success, the
/// number of valid file descriptors is indicated by the second element of the
/// returned tuple. The caller owns these file descriptors, but they will not be
/// closed on drop like a `File`-like type would be. It is recommended that each valid
/// file descriptor gets wrapped in a drop type that closes it after this returns.
fn recv_with_fds(&self, iovecs: &mut [iovec], fds: &mut [RawFd]) -> Result<(usize, usize)> {
raw_recvmsg(self.socket_fd(), iovecs, fds)
}
}
impl ScmSocket for UnixDatagram {
fn socket_fd(&self) -> RawFd {
self.as_raw_fd()
}
}
impl ScmSocket for UnixStream {
fn socket_fd(&self) -> RawFd {
self.as_raw_fd()
}
}
/// Trait for types that can be converted into an `iovec` that can be referenced by a syscall for
/// the lifetime of this object.
///
/// This trait is unsafe because interfaces that use this trait depend on the base pointer and size
/// being accurate.
pub unsafe trait IntoIovec {
/// Gets the base pointer of this `iovec`.
fn as_ptr(&self) -> *const c_void;
/// Gets the size in bytes of this `iovec`.
fn size(&self) -> usize;
}
// Safe because this slice can not have another mutable reference and it's pointer and size are
// guaranteed to be valid.
unsafe impl<'a> IntoIovec for &'a [u8] {
// Clippy false positive: https://github.com/rust-lang/rust-clippy/issues/3480
#[cfg_attr(feature = "cargo-clippy", allow(clippy::useless_asref))]
fn as_ptr(&self) -> *const c_void {
self.as_ref().as_ptr() as *const c_void
}
fn size(&self) -> usize {
self.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::mem::size_of;
use std::os::raw::c_long;
use std::os::unix::net::UnixDatagram;
use std::slice::from_raw_parts;
use libc::cmsghdr;
use vmm_sys_util::eventfd::EventFd;
#[test]
fn buffer_len() {
assert_eq!(CMSG_SPACE!(0 * size_of::<RawFd>()), size_of::<cmsghdr>());
assert_eq!(
CMSG_SPACE!(1 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>()
);
if size_of::<RawFd>() == 4 {
assert_eq!(
CMSG_SPACE!(2 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>()
);
assert_eq!(
CMSG_SPACE!(3 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>() * 2
);
assert_eq!(
CMSG_SPACE!(4 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>() * 2
);
} else if size_of::<RawFd>() == 8 {
assert_eq!(
CMSG_SPACE!(2 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>() * 2
);
assert_eq!(
CMSG_SPACE!(3 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>() * 3
);
assert_eq!(
CMSG_SPACE!(4 * size_of::<RawFd>()),
size_of::<cmsghdr>() + size_of::<c_long>() * 4
);
}
}
#[test]
fn send_recv_no_fd() {
let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
let write_count = s1
.send_with_fds(&[[1u8, 1, 2].as_ref(), [21u8, 34, 55].as_ref()], &[])
.expect("failed to send data");
assert_eq!(write_count, 6);
let mut buf = [0u8; 6];
let mut files = [0; 1];
let mut iovecs = [iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf.len(),
}];
let (read_count, file_count) = s2
.recv_with_fds(&mut iovecs[..], &mut files)
.expect("failed to recv data");
assert_eq!(read_count, 6);
assert_eq!(file_count, 0);
assert_eq!(buf, [1, 1, 2, 21, 34, 55]);
}
#[test]
fn send_recv_only_fd() {
let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
let evt = EventFd::new(0).expect("failed to create eventfd");
let write_count = s1
.send_with_fd([].as_ref(), evt.as_raw_fd())
.expect("failed to send fd");
assert_eq!(write_count, 0);
let (read_count, file_opt) = s2.recv_with_fd(&mut []).expect("failed to recv fd");
let mut file = file_opt.unwrap();
assert_eq!(read_count, 0);
assert!(file.as_raw_fd() >= 0);
assert_ne!(file.as_raw_fd(), s1.as_raw_fd());
assert_ne!(file.as_raw_fd(), s2.as_raw_fd());
assert_ne!(file.as_raw_fd(), evt.as_raw_fd());
file.write(unsafe { from_raw_parts(&1203u64 as *const u64 as *const u8, 8) })
.expect("failed to write to sent fd");
assert_eq!(evt.read().expect("failed to read from eventfd"), 1203);
}
#[test]
fn send_recv_with_fd() {
let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair");
let evt = EventFd::new(0).expect("failed to create eventfd");
let write_count = s1
.send_with_fds(&[[237].as_ref()], &[evt.as_raw_fd()])
.expect("failed to send fd");
assert_eq!(write_count, 1);
let mut files = [0; 2];
let mut buf = [0u8];
let mut iovecs = [iovec {
iov_base: buf.as_mut_ptr() as *mut c_void,
iov_len: buf.len(),
}];
let (read_count, file_count) = s2
.recv_with_fds(&mut iovecs[..], &mut files)
.expect("failed to recv fd");
assert_eq!(read_count, 1);
assert_eq!(buf[0], 237);
assert_eq!(file_count, 1);
assert!(files[0] >= 0);
assert_ne!(files[0], s1.as_raw_fd());
assert_ne!(files[0], s2.as_raw_fd());
assert_ne!(files[0], evt.as_raw_fd());
let mut file = unsafe { File::from_raw_fd(files[0]) };
file.write(unsafe { from_raw_parts(&1203u64 as *const u64 as *const u8, 8) })
.expect("failed to write to sent fd");
assert_eq!(evt.read().expect("failed to read from eventfd"), 1203);
}
}

View File

@@ -1,30 +0,0 @@
// Copyright (C) 2019 Alibaba Cloud Computing. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 or BSD-3-Clause
//
// Portions Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-BSD file.
//! Trait to control vhost-vsock backend drivers.
use crate::backend::VhostBackend;
use crate::Result;
/// Trait to control vhost-vsock backend drivers.
pub trait VhostVsock: VhostBackend {
/// Set the CID for the guest.
/// This number is used for routing all data destined for running in the guest.
/// Each guest on a hypervisor must have an unique CID.
///
/// # Arguments
/// * `cid` - CID to assign to the guest
fn set_guest_cid(&mut self, cid: u64) -> Result<()>;
/// Tell the VHOST driver to start performing data transfer.
fn start(&mut self) -> Result<()>;
/// Tell the VHOST driver to stop performing data transfer.
fn stop(&mut self) -> Result<()>;
}

Some files were not shown because too many files have changed in this diff Show More