isothrum_machine/setup/kvm.rs
1//! Letting VirtualBox share the CPU's virtualization with KVM (Linux,
2//! [`super::Action::ShareVirtualization`]). Since Linux 6.12, KVM's module turns VT-x or AMD-V on
3//! as it loads and keeps it, so no VirtualBox VM starts while KVM is loaded
4//! ([`Unavailable::KvmHoldsVirtualization`]). With `options kvm enable_virt_at_load=0`, KVM takes
5//! it only while one of its own VMs runs: both hypervisors are usable, just not at the same
6//! moment.
7//!
8//! The option goes in a modprobe file of its own ([`OPTION_FILE`]), written as root the way an
9//! install's steps are ([`Elevation`]). It applies the next time KVM's module loads: at once when
10//! nothing uses KVM (no VM of its own running, nothing holding `/dev/kvm`), its modules unloaded
11//! and loaded again; else from the next restart ([`Shared::AfterRestart`],
12//! [`Unavailable::KvmSharesAfterRestart`]).
13
14use crate::context::Context;
15use crate::host::{Host, HostOs};
16use crate::install::linux::Root;
17use crate::install::root::RootScript;
18use crate::install::{Elevation, Step, StepFailed, run_steps};
19#[cfg(doc)]
20use crate::providers::Unavailable;
21use crate::providers::kvm;
22
23/// The modprobe file the option is written to, in `/etc/modprobe.d`.
24pub const OPTION_FILE: &str = "isothrum-kvm.conf";
25
26/// The option itself: KVM turns the CPU's virtualization on only while one of its VMs runs.
27pub const OPTION: &str = "options kvm enable_virt_at_load=0";
28
29/// When VirtualBox can use the CPU's virtualization.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Shared {
32 /// Now: KVM doesn't hold it (it never did, or its modules were loaded again with the option).
33 Now,
34 /// Once the computer restarts: the option is written, but KVM was in use, or couldn't be
35 /// loaded again ([`Unavailable::KvmSharesAfterRestart`]).
36 AfterRestart,
37}
38
39/// Why KVM wasn't set to share the CPU's virtualization.
40#[derive(Debug, Clone, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum ShareFailed {
43 /// Not on Linux: KVM is Linux's.
44 NotHere,
45 /// KVM is built into the kernel, not a module modprobe loads: only the kernel's command line
46 /// (`kvm.enable_virt_at_load=0`) sets its option.
47 BuiltIn,
48 /// The root step failed.
49 Step(StepFailed),
50 /// The step ran, yet KVM is neither sharing now nor set to from its next load.
51 Unchanged,
52}
53
54impl std::fmt::Display for ShareFailed {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 match self {
57 ShareFailed::NotHere => f.write_str("KVM runs on Linux only"),
58 ShareFailed::BuiltIn => f.write_str("KVM is built into this kernel: start Linux with kvm.enable_virt_at_load=0"),
59 ShareFailed::Step(failed) => failed.fmt(f),
60 ShareFailed::Unchanged => f.write_str("KVM still holds the CPU's virtualization, and isn't set to share it"),
61 }
62 }
63}
64
65impl std::error::Error for ShareFailed {}
66
67/// The root script that writes [`OPTION`] to [`OPTION_FILE`] in `modprobe_d`, then, when
68/// `reload` names KVM's CPU module (`kvm_intel`, `kvm_amd`), unloads it and `kvm` and loads it
69/// again, which loads `kvm` with the option. An unload modprobe refuses (a module in use) leaves
70/// the option for the next restart; the CPU module is loaded again either way.
71#[must_use]
72pub fn share_script(modprobe_d: &std::path::Path, reload: Option<&str>) -> RootScript {
73 // A Linux path whatever builds the script: `Path::join` would put a `\` in it on Windows.
74 let file = quoted(&format!("{}/{OPTION_FILE}", modprobe_d.to_string_lossy().trim_end_matches('/')));
75 let dir = quoted(&modprobe_d.to_string_lossy());
76 let mut body = format!(
77 "mkdir -p {dir}; printf '%s\\n' '# KVM takes the CPU'\\''s virtualization only while one of its VMs runs, so other hypervisors can use it.' '{OPTION}' > {file}"
78 );
79 if let Some(module) = reload {
80 body = format!(
81 "{body}; if modprobe -r {module} kvm; then echo 'KVM loaded again: it shares the CPU'\\''s virtualization now.'; \
82 else echo 'KVM is in use: it shares the CPU'\\''s virtualization from the next restart.'; fi; modprobe {module}"
83 );
84 }
85 RootScript::new(body)
86}
87
88/// `text` quoted for `sh`.
89fn quoted(text: &str) -> String {
90 format!("'{}'", text.replace('\'', r"'\''"))
91}
92
93/// The step that sets KVM on `host` to share the CPU's virtualization, elevated by `elevation`:
94/// its modules loaded again when nothing uses KVM now (`kvm::in_use`).
95///
96/// # Errors
97///
98/// [`ShareFailed::NotHere`] off Linux, [`ShareFailed::BuiltIn`] where KVM isn't a module.
99pub fn share_step(host: &Host, elevation: Elevation) -> Result<Step, ShareFailed> {
100 if host.os != HostOs::Linux {
101 return Err(ShareFailed::NotHere);
102 }
103 if !kvm::loadable(host) {
104 return Err(ShareFailed::BuiltIn);
105 }
106 let reload = kvm::cpu_module(host).filter(|_| !kvm::in_use(host));
107 let root = Root { elevation, proxy: Vec::new() };
108 // No proxy: nothing is downloaded, and no private file can fail to be written.
109 root.step(share_script(&host.devices.modprobe_d, reload)).map_err(|_| ShareFailed::Unchanged)
110}
111
112/// When VirtualBox can use the CPU's virtualization on the context's host, as detection reads it
113/// now: none when KVM holds it and isn't set to share it.
114#[must_use]
115pub fn sharing(host: &Host) -> Option<Shared> {
116 if !kvm::holds_virtualization(host) {
117 Some(Shared::Now)
118 } else if kvm::shares_from_next_load(host) {
119 Some(Shared::AfterRestart)
120 } else {
121 None
122 }
123}
124
125/// Sets KVM to share the CPU's virtualization ([`share_step`], each line it prints handed to
126/// `on_line`), then reads when VirtualBox can use it. Nothing runs where KVM doesn't hold it.
127///
128/// # Errors
129///
130/// [`ShareFailed`]: why it wasn't set.
131pub async fn share_virtualization(cx: &Context, elevation: Elevation, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<Shared, ShareFailed> {
132 if cx.host.os != HostOs::Linux {
133 return Err(ShareFailed::NotHere);
134 }
135 if !kvm::holds_virtualization(&cx.host) {
136 return Ok(Shared::Now);
137 }
138 let step = share_step(&cx.host, elevation)?;
139 run_steps(cx, &[step], on_line).await.map_err(ShareFailed::Step)?;
140 sharing(&cx.host).ok_or(ShareFailed::Unchanged)
141}
142
143#[cfg(test)]
144mod tests;