Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1648,6 +1648,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.16",
"vm_resource",
"windows-sys 0.61.0",
]

[[package]]
Expand Down
4 changes: 3 additions & 1 deletion Guide/src/reference/openvmm/management/grpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ or reopen the file.

Some API fields reference OS handles by name. For example,
`VirtioFs.WindowsOptions.user_token_name` names an access token that virtio-fs
impersonates for host file access.
impersonates for host file access. `HandleDisk.handle_name` names a host block
device handle, such as a physical disk, opened for synchronous (non-overlapped)
I/O.

Clients register these handles over the same socket using the
[resource-passing protocol]. Because Windows Unix sockets cannot carry handles,
Expand Down
115 changes: 111 additions & 4 deletions openvmm/openvmm_entry/src/ttrpc/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2876,7 +2876,7 @@ async fn build_pci_device(
let resource = build_virtio_device(virtio, registry).await?;
VirtioPciDeviceHandle(resource).into_resource()
}
Kind::Nvme(nvme) => build_nvme_controller(nvme).await?,
Kind::Nvme(nvme) => build_nvme_controller(nvme, registry).await?,
Kind::Vfio(vfio) => build_vfio_device(vfio, iommufds)?,
})
}
Expand Down Expand Up @@ -2995,6 +2995,7 @@ fn build_vfio_device(
/// Builds an NVMe controller resource from the proto `NvmeConfig`.
async fn build_nvme_controller(
nvme: vmservice::NvmeConfig,
registry: &ResourceRegistry,
) -> anyhow::Result<Resource<PciDeviceHandleKind>> {
let vmservice::NvmeConfig {
controller_id,
Expand All @@ -3007,8 +3008,12 @@ async fn build_nvme_controller(
backend,
read_only,
} = ns;
let disk =
build_disk_backend(backend.context("missing namespace backend")?, read_only).await?;
let disk = build_disk_backend(
backend.context("missing namespace backend")?,
read_only,
registry,
)
.await?;
namespaces.push(nvme_resources::NamespaceDefinition {
nsid,
read_only,
Expand Down Expand Up @@ -3040,7 +3045,8 @@ async fn build_virtio_device(
serial,
}) => {
let disk =
build_disk_backend(backend.context("missing blk backend")?, read_only).await?;
build_disk_backend(backend.context("missing blk backend")?, read_only, registry)
.await?;
virtio_resources::blk::VirtioBlkHandle {
disk,
read_only,
Expand Down Expand Up @@ -3166,7 +3172,24 @@ fn build_virtio_fs_windows_options(
async fn build_disk_backend(
backend: vmservice::DiskBackend,
read_only: bool,
registry: &ResourceRegistry,
) -> anyhow::Result<Resource<DiskHandleKind>> {
if let Some(vmservice::disk_backend::Kind::Handle(vmservice::HandleDisk { handle_name })) =
backend.kind
{
#[cfg(windows)]
{
let handle = registry
.resolve(&handle_name)
.with_context(|| format!("failed to resolve disk handle '{handle_name}'"))?;
return Ok(disk_backend_resources::FileDiskHandle(handle.into()).into_resource());
Comment thread
damanm24 marked this conversation as resolved.
Resolved
}
#[cfg(not(windows))]
{
let _ = (handle_name, registry);
anyhow::bail!("handle disk backends are only supported on Windows")
}
}
crate::disk_open(&disk_backend_from_proto(backend)?, read_only).await
}

Expand All @@ -3185,6 +3208,9 @@ fn disk_backend_from_proto(backend: vmservice::DiskBackend) -> anyhow::Result<Di
vmservice::disk_backend::Kind::Memory(vmservice::MemoryDisk { size_bytes }) => {
DiskCliKind::Memory(size_bytes)
}
vmservice::disk_backend::Kind::Handle(_) => {
anyhow::bail!("handle disk backends require a standalone disk")
}
vmservice::disk_backend::Kind::MemoryDiff(overlay) => DiskCliKind::MemoryDiff(Box::new(
disk_backend_from_proto(*overlay.lower.context("missing memory diff lower disk")?)?,
)),
Expand Down Expand Up @@ -3760,6 +3786,87 @@ mod tests {
}
}

#[test]
fn unregistered_handle_disk_backend_is_rejected() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
for name in ["", "missing"] {
let backend = vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::Handle(
vmservice::HandleDisk {
handle_name: name.into(),
},
)),
};
let error = build_disk_backend(backend, false, &registry)
.await
.unwrap_err();
#[cfg(windows)]
assert_eq!(
format!("{error:#}"),
format!(
"failed to resolve disk handle '{name}': no handle registered under name '{name}'"
)
);
#[cfg(not(windows))]
assert_eq!(
error.to_string(),
"handle disk backends are only supported on Windows"
);
}
});
}

#[cfg(windows)]
#[test]
fn registered_handle_disk_backends() {
DefaultPool::run_with(async |_driver| {
let registry = ResourceRegistry::default();
let file = tempfile::tempfile().unwrap();
registry.register("disk".into(), file.into()).unwrap();
let backend = || vmservice::DiskBackend {
kind: Some(vmservice::disk_backend::Kind::Handle(
vmservice::HandleDisk {
handle_name: "disk".into(),
},
)),
};

build_nvme_controller(
vmservice::NvmeConfig {
namespaces: vec![vmservice::NvmeNamespace {
nsid: 1,
backend: Some(backend()),
read_only: true,
}],
..Default::default()
},
&registry,
)
.await
.unwrap();
build_virtio_device(
vmservice::VirtioDevice {
kind: Some(vmservice::virtio_device::Kind::Blk(vmservice::VirtioBlk {
backend: Some(backend()),
read_only: true,
..Default::default()
})),
},
&registry,
)
.await
.unwrap();

registry.deregister("disk");
assert!(
build_disk_backend(backend(), true, &registry)
.await
.is_err()
);
});
}

#[test]
fn shutdown_request_acceptance_does_not_halt_or_teardown_vm() {
DefaultPool::run_with(async |driver| {
Expand Down
1 change: 1 addition & 0 deletions openvmm/openvmm_ttrpc_vmservice/src/resource_passing.md
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ the RPC. Once the RPC succeeds, the name may be deregistered.
| Field | Host | Resource |
|-------|------|----------|
| `TapBackend.fd_name` | Linux | tap device fd, used instead of opening `/dev/net/tun` |
| `HandleDisk.handle_name` | Windows | host block device handle opened for synchronous (non-overlapped) I/O |
| `VirtioFs.WindowsOptions.user_token_name` | Windows | access token that virtio-fs impersonates for host file access |

## Wire format examples
Expand Down
13 changes: 13 additions & 0 deletions openvmm/openvmm_ttrpc_vmservice/src/vmservice.proto
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,8 @@ message DiskBackend {
MemoryDisk memory = 2;
// A memory-backed writable overlay over a read-only lower disk.
MemoryDiffDisk memory_diff = 3;
// A host block device opened by the client (Windows only).
HandleDisk handle = 4;
}
}

Expand All @@ -388,6 +390,17 @@ message MemoryDiffDisk {
DiskBackend lower = 1;
}

// A disk backed by a host block device handle, such as `\\.\PhysicalDriveN`.
//
// The client opens the device for synchronous (non-overlapped) I/O and
// registers its handle using the resource-passing protocol
// (see resource_passing.md). OpenVMM duplicates the registered handle while
// processing the request; the name may be deregistered after the RPC succeeds.
message HandleDisk {
// Name of the registered device handle (Windows only).
string handle_name = 1;
}

// A disk backed by a host file.
message FileDisk {
// Path to the backing file.
Expand Down
3 changes: 3 additions & 0 deletions vm/devices/storage/disk_file/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ inspect = { workspace = true, features = ["filepath"] }
blocking.workspace = true
thiserror.workspace = true

[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_System_IO", "Win32_System_Ioctl"] }

[dev-dependencies]
pal_async.workspace = true
storage_tests.workspace = true
Expand Down
32 changes: 26 additions & 6 deletions vm/devices/storage/disk_file/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
// Licensed under the MIT License.

#![expect(missing_docs)]
#![forbid(unsafe_code)]
#![cfg_attr(not(windows), forbid(unsafe_code))]
#![cfg_attr(windows, deny(unsafe_code))]

mod readwriteat;
#[cfg(windows)]
mod windows;

use self::readwriteat::ReadWriteAt;
use blocking::unblock;
Expand Down Expand Up @@ -74,12 +77,29 @@ impl std::os::windows::io::AsHandle for FileDisk {
}

impl FileDisk {
/// Opens a disk backed by a regular file or, on Windows, by a block
/// device such as `\\.\PhysicalDriveN`.
///
/// Block device handles must be opened for synchronous I/O.
pub fn open(file: fs::File, read_only: bool) -> Result<Self, std::io::Error> {
Comment thread
damanm24 marked this conversation as resolved.
Resolved
let metadata = Metadata {
disk_size: file.metadata()?.len(),
sector_size: 512,
physical_sector_size: 4096,
read_only,
let metadata = match file.metadata() {
Ok(m) => Metadata {
disk_size: m.len(),
sector_size: 512,
physical_sector_size: 4096,
read_only,
},
#[cfg(windows)]
Err(err) if windows::is_device_error(&err) => {
let geometry = windows::query_device_geometry(&file)?;
Metadata {
disk_size: geometry.disk_size,
sector_size: geometry.sector_size,
physical_sector_size: geometry.physical_sector_size,
read_only,
}
}
Err(err) => return Err(err),
};
Ok(Self::with_metadata(file, metadata))
}
Expand Down
101 changes: 101 additions & 0 deletions vm/devices/storage/disk_file/src/windows.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Windows block device (for example `\\.\PhysicalDriveN`) metadata queries.

// UNSAFETY: Calling DeviceIoControl with properly sized input and output buffers.
#![expect(unsafe_code)]

use std::fs;
use std::io;
use std::mem::size_of;
use std::os::windows::io::AsRawHandle;
use windows_sys::Win32::Foundation::ERROR_INVALID_FUNCTION;
use windows_sys::Win32::Foundation::ERROR_NOT_SUPPORTED;
use windows_sys::Win32::System::IO::DeviceIoControl;
use windows_sys::Win32::System::Ioctl::GET_LENGTH_INFORMATION;
use windows_sys::Win32::System::Ioctl::IOCTL_DISK_GET_LENGTH_INFO;
use windows_sys::Win32::System::Ioctl::IOCTL_STORAGE_QUERY_PROPERTY;
use windows_sys::Win32::System::Ioctl::PropertyStandardQuery;
use windows_sys::Win32::System::Ioctl::STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR;
use windows_sys::Win32::System::Ioctl::STORAGE_PROPERTY_QUERY;
use windows_sys::Win32::System::Ioctl::StorageAccessAlignmentProperty;

/// Size and sector geometry of a block device.
pub(crate) struct DeviceGeometry {
pub disk_size: u64,
pub sector_size: u32,
pub physical_sector_size: u32,
}

/// Returns true if `err` indicates that the handle is a device that does not
/// support file metadata queries.
pub(crate) fn is_device_error(err: &io::Error) -> bool {
err.raw_os_error() == Some(ERROR_INVALID_FUNCTION as i32)
}

fn ioctl<I, O: Default>(file: &fs::File, code: u32, input: Option<&I>) -> io::Result<O> {
let mut output = O::default();
let mut returned = 0;
let (in_ptr, in_len) = input.map_or((std::ptr::null(), 0), |i| {
(std::ptr::from_ref(i).cast(), size_of::<I>() as u32)
});
// SAFETY: the input and output pointers are valid for the specified
// lengths for the duration of the synchronous call.
let ok = unsafe {
DeviceIoControl(
file.as_raw_handle(),
code,
in_ptr,
in_len,
std::ptr::from_mut(&mut output).cast(),
size_of::<O>() as u32,
&mut returned,
std::ptr::null_mut(),
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
if (returned as usize) < size_of::<O>() {
return Err(io::Error::from_raw_os_error(ERROR_NOT_SUPPORTED as i32));
}
Ok(output)
}

/// Queries the size and sector sizes of a block device.
pub(crate) fn query_device_geometry(file: &fs::File) -> io::Result<DeviceGeometry> {
let length: GET_LENGTH_INFORMATION = ioctl::<(), _>(file, IOCTL_DISK_GET_LENGTH_INFO, None)?;
let query = STORAGE_PROPERTY_QUERY {
PropertyId: StorageAccessAlignmentProperty,
QueryType: PropertyStandardQuery,
AdditionalParameters: [0],
};
let (sector_size, physical_sector_size) = match ioctl::<_, STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR>(
file,
IOCTL_STORAGE_QUERY_PROPERTY,
Some(&query),
) {
Ok(alignment) => (
alignment.BytesPerLogicalSector,
alignment.BytesPerPhysicalSector,
),
Err(_) => (512, 512),
};
let sector_size = if sector_size.is_power_of_two() && sector_size >= 512 {
sector_size
} else {
512
};
let physical_sector_size =
if physical_sector_size.is_power_of_two() && physical_sector_size >= sector_size {
physical_sector_size
} else {
sector_size
};
Ok(DeviceGeometry {
disk_size: length.Length as u64,
sector_size,
physical_sector_size,
})
}
3 changes: 2 additions & 1 deletion vmm_tests/vmm_tests/tests/tests/ttrpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

// Tests for the resource-passing protocols, which share the TTRPC socket. The
// UNIX fd-passing test resolves a tap `fd_name`, which is Linux-only; the
// Windows handle-passing test resolves a virtio-fs user token.
// Windows handle-passing tests resolve a virtio-fs user token and a physical
// disk.
#[cfg(target_os = "linux")]
mod fd_passing;
#[cfg(windows)]
Expand Down
Loading
Loading