Compare commits

...
Author SHA1 Message Date
Xiaochi You 6527829878 Merge pull request #20 from reims-go/feat/win32-aio-rawdisk-perf
feat(win32): native AIO, raw device in-place, disk cache policy, and bumped fast QEMU
2026-12-05 12:30:18 +08:00
YXC0915 91c0ce917a style(reims-ctl): run rustfmt on qemu and runtime 2026-12-05 12:17:08 +08:00
YXC0915 5a2083b951 feat(win32): enable native AIO, raw disk in-place, disk cache policy, and fast QEMU runtime 2026-12-05 12:01:05 +08:00
8 changed files with 352 additions and 30 deletions

No files matched your search

+36 -9
View File
@@ -720,6 +720,9 @@ pub struct CreateArgs {
/// directory are on one file system that makes them, else a full copy) or in-place
#[arg(long, default_value = "copy")]
pub disk_mode: String,
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
#[arg(long)]
pub disk_cache: Option<String>,
/// Download this macOS from Apple to install: a name (tahoe), a number (26) or latest; with
/// --offline, also a release (26.6.2) or a build (25G83)
#[arg(long, value_name = "VERSION", conflicts_with = "installer")]
@@ -813,6 +816,9 @@ pub struct SetArgs {
/// OpenCore may start it
#[arg(long)]
pub disk_controller: Option<String>,
/// Host I/O cache policy for the system disk: default, writeback, none or unsafe
#[arg(long)]
pub disk_cache: Option<String>,
/// The size each of reims-vgpu's windows opens at, WIDTHxHEIGHT in the desktop's points:
/// one size for every display, or one for each display, comma-separated
/// (2560x1440,1920x1080); on a headless start (start --headless), each display's mode
@@ -1203,7 +1209,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
size_mib: parse_size_mib(sz)?,
}),
(None, Some(p)) => Some(DiskSource::Existing {
path: paths::absolute(&p.to_string_lossy()),
path: if vm::is_windows_raw_device(p) {
p.to_path_buf()
} else {
paths::absolute(&p.to_string_lossy())
},
mode: ImportMode::parse(&a.disk_mode)?,
}),
(None, None) => Some(DiskSource::New {
@@ -1225,6 +1235,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> {
}
});
s.mac = a.mac.clone();
s.disk_cache = a
.disk_cache
.as_deref()
.map(vm::DiskCache::parse)
.transpose()?;
s.graphics = a.graphics.as_deref().map(vm::Graphics::parse).transpose()?;
if let Some(n) = a.displays {
s.display.count = n;
@@ -1446,14 +1461,19 @@ pub fn describe(vm: &Vm, host: Host, full: Option<&runtime::DiskFull>) -> Vec<(S
Err(_) => paths::tilde(&disk),
};
match &c.q35 {
Some(q) => add(
"disk",
format!(
"{disk_name} ({}, {})",
c.disk_format.as_str(),
q.disk_controller.describe()
),
),
Some(q) => {
add(
"disk",
format!(
"{disk_name} ({}, {})",
c.disk_format.as_str(),
q.disk_controller.describe()
),
);
if !q.disk_cache.is_default() {
add("disk cache", q.disk_cache.id().into());
}
}
None => add("disk", format!("{disk_name} ({})", c.disk_format.as_str())),
}
if let Some(a) = &c.vmapple {
@@ -1708,6 +1728,13 @@ fn set(a: SetArgs, host: Host) -> Result<()> {
None => bail!("{}: --disk-controller is for x86-64 VMs", c.name),
}
}
if let Some(dc) = &a.disk_cache {
let dc = vm::DiskCache::parse(dc)?;
match &mut c.q35 {
Some(q) => q.disk_cache = dc,
None => bail!("{}: --disk-cache is for x86-64 VMs", c.name),
}
}
// A count given is checked against the graphics; one kept from reims-vgpu waits unused on
// VMware SVGA, as the resolution does.
if let Some(n) = a.displays {
+32 -5
View File
@@ -92,6 +92,7 @@ pub struct Spec {
pub ssh_port: Option<u16>,
pub mac: Option<String>,
// q35
pub disk_cache: Option<DiskCache>,
/// macOS to download from Apple, for the installer.
pub macos: Option<Download>,
pub opencore: Option<PathBuf>,
@@ -119,6 +120,7 @@ impl Spec {
network: true,
ssh_port: None,
mac: None,
disk_cache: None,
macos: None,
opencore: None,
installer: None,
@@ -224,13 +226,28 @@ pub fn create_with(
check_free(&dir)?;
// What was given is checked before the slow steps: a download, a disk's copy.
let mut foreign = None;
if let Some(DiskSource::Existing { path, .. }) = &spec.disk {
if !path.is_file() {
bail!("the disk {} does not exist", path.display());
let is_raw_dev = matches!(
&spec.disk,
Some(DiskSource::Existing { path, .. }) if crate::vm::is_windows_raw_device(path)
);
if let Some(DiskSource::Existing { path, mode }) = &spec.disk {
if crate::vm::is_windows_raw_device(path) {
if *mode != ImportMode::InPlace {
bail!(
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
path.display()
);
}
} else {
if !path.is_file() {
bail!("the disk {} does not exist", path.display());
}
foreign = foreign_disk(path, profile)?;
}
foreign = foreign_disk(path, profile)?;
}
check_disk_fits(&spec, &dir, foreign.as_ref())?;
if !is_raw_dev {
check_disk_fits(&spec, &dir, foreign.as_ref())?;
}
if let (Some(f), Some(DiskSource::Existing { path, .. })) = (&foreign, &spec.disk) {
check_room(f, path, &dir)?;
}
@@ -1409,6 +1426,7 @@ fn make_q35(
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Ahci,
disk_cache: spec.disk_cache.unwrap_or_default(),
disk_port: 3,
});
Ok(Vm {
@@ -1424,6 +1442,15 @@ fn import_disk(
stem: &str,
progress: &mut dyn FnMut(&str),
) -> Result<(PathBuf, ImageFormat)> {
if crate::vm::is_windows_raw_device(src) {
if mode != ImportMode::InPlace {
bail!(
"raw Windows disk/partition {} can only be used in-place (--disk-mode in-place)",
src.display()
);
}
return Ok((src.to_path_buf(), ImageFormat::Raw));
}
if !src.is_file() {
bail!("the disk {} does not exist", src.display());
}
+4
View File
@@ -43,6 +43,10 @@ pub fn home() -> PathBuf {
/// after a `\`; elsewhere as it is.
pub fn native(p: PathBuf) -> PathBuf {
if cfg!(windows) {
if crate::vm::is_windows_raw_device(&p) {
let s = p.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
p.components().collect()
} else {
p
+182 -12
View File
@@ -169,6 +169,8 @@ pub struct Ctx {
/// The host CPU's brand string ([`crate::host::cpu_brand`]), which an x86-64 guest's CPU
/// gives as its own (`model-id`); None where the host gives none.
pub cpu_brand: Option<String>,
/// Whether this Windows QEMU has the repaired native block AIO backend.
pub win32_native_aio: bool,
/// Whether QEMU's own window can open ([`crate::host::has_screen`]).
pub screen: bool,
/// Whether the start is headless (`reims-ctl start --headless`): it opens no window, and
@@ -451,31 +453,72 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
),
]);
push(&["-device", "ide-hd,bus=sata.2,drive=opencore,bootindex=1"]);
let mut disk = format!(
"id=disk,if=none,format={},file={}",
c.disk_format.as_str(),
optp(&vm.disk())
);
let disk_path = vm.disk();
let is_raw_dev = crate::vm::is_windows_raw_device(&disk_path);
let mut disk = if is_raw_dev {
format!(
"id=disk,if=none,format=raw,file.driver=host_device,file.filename={}",
optp(&disk_path)
)
} else {
format!(
"id=disk,if=none,format={},file={}",
c.disk_format.as_str(),
optp(&disk_path)
)
};
// The qcow2 image's L2 cache, its table of where each cluster is, up to 32 MiB, which maps
// 256 GiB of a disk of 64 KiB clusters (qemu-img's default, which a new disk has). QEMU's own
// limit is 32 MiB on Linux and 8 MiB elsewhere, which maps 64 GiB, half a new 128 GiB disk:
// on Windows a guest access whose table has left the cache reads it from the image again.
// QEMU takes the smaller of this and what the image's size needs (block/qcow2.c,
// `read_cache_sizes`), so a smaller disk keeps a smaller cache.
if c.disk_format == crate::vm::ImageFormat::Qcow2 {
if !is_raw_dev && c.disk_format == crate::vm::ImageFormat::Qcow2 {
disk.push_str(",l2-cache-size=32M");
}
// An install's flushes, which the module's doc measures, are dropped while the installer is
// attached.
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
if ctx.win32_native_aio
&& matches!(
q.disk_controller,
DiskController::Nvme | DiskController::Virtio
)
{
if is_raw_dev {
disk.push_str(",file.aio=native");
} else {
disk.push_str(",aio=native");
}
}
match q.disk_cache {
crate::vm::DiskCache::Default => {
// An install's flushes, which the module's doc measures, are dropped while the
// installer is attached.
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::Writeback => {
disk.push_str(",cache.direct=off");
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::None => {
disk.push_str(",cache.direct=on");
if q.installer.is_some() {
disk.push_str(",cache.no-flush=on");
}
}
crate::vm::DiskCache::Unsafe => {
disk.push_str(",cache.direct=off,cache.no-flush=on");
}
}
let discard_opt = if is_raw_dev { "" } else { ",discard=unmap" };
match q.disk_controller {
// `discard=unmap` passes the guest's TRIMs to the image, which frees their space. QEMU's
// NVMe controller needs a serial, and without an address takes slot 3, virtio-net's.
DiskController::Nvme => push(&[
"-drive",
&format!("{disk},discard=unmap"),
&format!("{disk}{discard_opt}"),
"-device",
"nvme,drive=disk,serial=reims-ctl,addr=0xa",
]),
@@ -492,7 +535,7 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec<String>) -> Result<()> {
"-object",
"iothread,id=io0",
"-drive",
&format!("{disk},discard=unmap"),
&format!("{disk}{discard_opt}"),
"-device",
"virtio-blk-pci,drive=disk,iothread=io0,addr=0x6",
]),
@@ -953,6 +996,7 @@ pub(crate) mod tests {
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Ahci,
disk_cache: crate::vm::DiskCache::Default,
disk_port: 3,
}),
vmapple: None,
@@ -980,6 +1024,7 @@ pub(crate) mod tests {
smbios_error_correction: Some(3),
smbios_memory_slots: None,
cpu_brand: None,
win32_native_aio: false,
screen: true,
headless: false,
graphics_rom: "/d/firmware/ReimsGraphics-0123456789abcdef.rom".into(),
@@ -2231,6 +2276,131 @@ pub(crate) mod tests {
));
}
#[test]
fn only_patched_windows_qemu_gets_native_aio_on_the_system_disk() {
let mut vm = q35_vm();
for controller in [
DiskController::Nvme,
DiskController::Virtio,
DiskController::Ahci,
] {
vm.config.q35.as_mut().unwrap().disk_controller = controller;
for supported in [false, true] {
let c = Ctx {
win32_native_aio: supported,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
let args = invocation(&vm, &c).unwrap().args;
let disk = args.iter().find(|arg| arg.starts_with("id=disk,")).unwrap();
assert_eq!(
disk.split(',').any(|opt| opt == "aio=native"),
supported
&& matches!(controller, DiskController::Nvme | DiskController::Virtio),
);
assert!(args.iter().filter(|arg| arg.contains("aio=native")).count() <= 1);
assert!(!disk.contains("cache.no-flush"));
}
}
}
#[test]
fn disk_cache_modes_emit_expected_qemu_drive_options() {
use crate::vm::{DiskCache, ImageFormat};
for fmt in [ImageFormat::Qcow2, ImageFormat::Raw] {
let mut vm = q35_vm();
vm.config.disk_format = fmt;
vm.config.disk = if fmt == ImageFormat::Raw {
"disk.img".into()
} else {
"disk.qcow2".into()
};
vm.config.q35.as_mut().unwrap().disk_controller = DiskController::Nvme;
let c = Ctx {
win32_native_aio: true,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Default;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(!d.contains("cache.direct"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Writeback;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=off"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::None;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=on"), "{d}");
assert!(!d.contains("cache.no-flush"), "{d}");
vm.config.q35.as_mut().unwrap().disk_cache = DiskCache::Unsafe;
let d = invocation(&vm, &c)
.unwrap()
.args
.into_iter()
.find(|a| a.starts_with("id=disk,"))
.unwrap();
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
}
}
#[test]
fn windows_raw_partition_uses_host_device_with_native_aio() {
use crate::vm::{DiskCache, ImageFormat};
let win_ctx = Ctx {
win32_native_aio: true,
..ctx(Host {
os: Os::Windows,
..linux()
})
};
for raw_path in [
r"\\?\Volume{11111111-2222-3333-4444-555555555555}",
r"\\.\PhysicalDrive2",
] {
let mut vm = q35_vm();
vm.config.disk = raw_path.into();
vm.config.disk_format = ImageFormat::Raw;
let q = vm.config.q35.as_mut().unwrap();
q.disk_controller = DiskController::Nvme;
q.disk_cache = DiskCache::Unsafe;
let args = invocation(&vm, &win_ctx).unwrap().args;
let d = args.iter().find(|a| a.starts_with("id=disk,")).unwrap();
assert!(
d.contains("format=raw,file.driver=host_device,file.filename="),
"{d}"
);
assert!(d.contains(raw_path), "{d}");
assert!(d.contains(",file.aio=native"), "{d}");
assert!(d.contains(",cache.direct=off,cache.no-flush=on"), "{d}");
assert!(!d.contains("discard=unmap"), "{d}");
assert!(!d.contains("l2-cache-size"), "{d}");
}
}
#[test]
fn installer_disk_goes_on_its_own_port_through_an_overlay() {
let mut vm = q35_vm();
+21 -3
View File
@@ -378,9 +378,15 @@ fn preflight_on(vm: &Vm, host: Host, kernel: &dyn Fn() -> Option<(u32, u32)>) ->
}
Ok(())
};
need(&vm.disk(), "the disk")?;
crate::create::check_disk_format(&vm.disk(), c.profile, crate::create::MAKE_A_VM_OF_THE_COPY)?;
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
if !crate::vm::is_windows_raw_device(&vm.disk()) {
need(&vm.disk(), "the disk")?;
crate::create::check_disk_format(
&vm.disk(),
c.profile,
crate::create::MAKE_A_VM_OF_THE_COPY,
)?;
crate::create::check_image_fits(&vm.disk(), c.disk_format)?;
}
match c.profile {
Profile::Q35X86_64 => {
let q = c.q35.as_ref().unwrap();
@@ -973,6 +979,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
let smbios_memory_type = smbios_memory_type(vm, &qemu);
let smbios_error_correction = smbios_error_correction(vm, &qemu);
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
let win32_native_aio = win32_native_aio(vm, host, &qemu);
Ok(Ctx {
host,
qemu,
@@ -985,6 +992,7 @@ pub fn context(vm: &Vm, host: Host) -> Result<Ctx> {
smbios_error_correction,
smbios_memory_slots,
cpu_brand: crate::host::cpu_brand(),
win32_native_aio,
screen,
headless: false,
graphics_rom: graphics_rom(vm)?,
@@ -1044,6 +1052,14 @@ fn smbios_memory_slots(vm: &Vm, qemu: &Path) -> Option<crate::reims_util::Memory
crate::reims_util::model_memory_slots(&config.identity().ok()?.model)
}
/// A version number alone does not distinguish the fixed Windows block backend.
fn win32_native_aio(vm: &Vm, host: Host, qemu: &Path) -> bool {
host.os == Os::Windows
&& vm.config.profile == Profile::Q35X86_64
&& crate::install::qemu_version(qemu)
.is_some_and(|version| version.ends_with(" [reims-win32-native-aio]"))
}
/// The option ROM of reims-vgpu's own device, written into the data directory for an x86-64 VM
/// on it ([`crate::prebuilt::graphics_rom`]); an empty path, which no command names, for another
/// VM. An arm64 VM's device has no option ROM: Ambrosia drives it with its module.
@@ -1094,6 +1110,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
let smbios_memory_type = smbios_memory_type(vm, &qemu);
let smbios_error_correction = smbios_error_correction(vm, &qemu);
let smbios_memory_slots = smbios_memory_slots(vm, &qemu);
let win32_native_aio = win32_native_aio(vm, host, &qemu);
Ctx {
host,
qemu,
@@ -1106,6 +1123,7 @@ pub fn invocation_for_print(vm: &Vm, host: Host) -> Result<Invocation> {
smbios_error_correction,
smbios_memory_slots,
cpu_brand: crate::host::cpu_brand(),
win32_native_aio,
screen: crate::host::has_screen(&vm.config.extra_env),
headless: false,
graphics_rom: graphics_rom(vm).unwrap_or_else(|_| crate::prebuilt::graphics_rom_path()),
+75
View File
@@ -244,6 +244,73 @@ impl DiskController {
}
}
/// Host cache policy for an x86-64 VM's system disk.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiskCache {
/// QEMU's default (`writeback` with flushes forwarded to the host, except
/// during installation when `cache.no-flush=on` is added automatically).
#[default]
Default,
/// Host page cache enabled (`cache.direct=off`), guest flushes forwarded.
Writeback,
/// Bypass host page cache (`cache.direct=on`), guest flushes forwarded.
None,
/// Host page cache enabled and guest flushes ignored (`cache.direct=off,cache.no-flush=on`).
Unsafe,
}
impl DiskCache {
pub const ALL: [DiskCache; 4] = [
DiskCache::Default,
DiskCache::Writeback,
DiskCache::None,
DiskCache::Unsafe,
];
pub fn id(self) -> &'static str {
match self {
DiskCache::Default => "default",
DiskCache::Writeback => "writeback",
DiskCache::None => "none",
DiskCache::Unsafe => "unsafe",
}
}
pub fn parse(s: &str) -> Result<DiskCache> {
let low = s.trim().to_ascii_lowercase();
DiskCache::ALL
.into_iter()
.find(|c| c.id() == low)
.with_context(|| format!("disk cache is default, writeback, none or unsafe, not {s:?}"))
}
pub fn is_default(&self) -> bool {
*self == DiskCache::Default
}
}
/// Reports whether `path` is a Windows raw physical disk or volume/partition
/// device path (`\\.\PhysicalDriveN`, `\\.\HarddiskVolumeN`,
/// `\\.\HarddiskNPartitionM`, `\\.\Volume{...}`, or `\\?\Volume{...}`),
/// excluding extended-length regular file paths like `\\?\D:\...`.
pub fn is_windows_raw_device(path: &Path) -> bool {
let norm = path.to_string_lossy().replace('/', "\\");
let rest = if let Some(r) = norm.strip_prefix(r"\\.\") {
r
} else if let Some(r) = norm.strip_prefix(r"\\?\") {
let low = r.to_ascii_lowercase();
return low.starts_with("volume{");
} else {
return false;
};
let low = rest.to_ascii_lowercase();
low.starts_with("physicaldrive")
|| low.starts_with("harddiskvolume")
|| low.starts_with("harddisk")
|| low.starts_with("volume{")
}
/// reims-vgpu's displays, one by default and up to [`DISPLAYS_MAX`], each in a window of its own:
/// each window opens at its display's size of the resolution ([`Display::window_sizes`]) and keeps
/// the size the person gives it, which its display follows, at the refresh rate of the host
@@ -558,6 +625,9 @@ pub struct Q35 {
/// installer may boot instead.
#[serde(default, skip_serializing_if = "DiskController::is_ahci")]
pub disk_controller: DiskController,
/// Host I/O cache mode for the system disk.
#[serde(default, skip_serializing_if = "DiskCache::is_default")]
pub disk_cache: DiskCache,
/// The system disk's AHCI port, on [`DiskController::Ahci`]: 3, after OpenCore's 2.
#[serde(default = "default_disk_port")]
pub disk_port: u32,
@@ -991,6 +1061,10 @@ impl Vm {
}
pub fn disk(&self) -> PathBuf {
if is_windows_raw_device(&self.config.disk) {
let s = self.config.disk.to_string_lossy().replace('/', "\\");
return PathBuf::from(s.trim_end_matches('\\'));
}
self.path(&self.config.disk)
}
@@ -1411,6 +1485,7 @@ pub(crate) mod tests {
cpu_model: default_cpu_model(),
cpu_flags: default_cpu_flags(),
disk_controller: DiskController::Nvme,
disk_cache: DiskCache::Default,
disk_port: 3,
}),
vmapple: None,
+1
View File
@@ -7,6 +7,7 @@
"win10-compat",
"win10-startup-ipis",
"win32-coroutine-fiber",
"win32-native-aio",
"win32-unicode-input",
"window-file-drop",
"window-text-drop"
Vendored
+1 -1
Submodule vendor/qemu updated: 0c0d881c49...c6f4d7b5c6.