diff --git a/crates/reims-ctl/Cargo.lock b/crates/reims-ctl/Cargo.lock index 64c3667d9..01f9f568e 100644 --- a/crates/reims-ctl/Cargo.lock +++ b/crates/reims-ctl/Cargo.lock @@ -160,15 +160,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "block2" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" -dependencies = [ - "objc2", -] - [[package]] name = "bumpalo" version = "3.20.3" @@ -437,16 +428,6 @@ dependencies = [ "crypto-common", ] -[[package]] -name = "dispatch2" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" -dependencies = [ - "bitflags 2.13.2", - "objc2", -] - [[package]] name = "document-features" version = "0.2.12" @@ -948,69 +929,6 @@ dependencies = [ "libc", ] -[[package]] -name = "objc2" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" -dependencies = [ - "objc2-encode", -] - -[[package]] -name = "objc2-app-kit" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-foundation", -] - -[[package]] -name = "objc2-core-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" -dependencies = [ - "bitflags 2.13.2", - "dispatch2", - "objc2", -] - -[[package]] -name = "objc2-encode" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" - -[[package]] -name = "objc2-foundation" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" -dependencies = [ - "bitflags 2.13.2", - "objc2", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-virtualization" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8edb98625ad1f7dea2e82ab54d5bdf3f477e6645b550f4a7cced1818be9ff59d" -dependencies = [ - "bitflags 2.13.2", - "block2", - "dispatch2", - "objc2", - "objc2-app-kit", - "objc2-core-foundation", - "objc2-foundation", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -1436,14 +1354,10 @@ version = "0.1.0" dependencies = [ "anyhow", "ash", - "block2", "clap", "crc32fast", "flate2", "libc", - "objc2", - "objc2-foundation", - "objc2-virtualization", "plist", "png", "ratatui", diff --git a/crates/reims-ctl/Cargo.toml b/crates/reims-ctl/Cargo.toml index 39fb03284..dffbde0fd 100644 --- a/crates/reims-ctl/Cargo.toml +++ b/crates/reims-ctl/Cargo.toml @@ -38,12 +38,5 @@ toml = "1.1.2" # needs no Vulkan to start. ash = { version = "0.38", default-features = false, features = ["std", "loaded"] } -[target.'cfg(target_os = "macos")'.dependencies] -# Installs macOS from an IPSW into a new VM (vz.rs): only Virtualization.framework restores one. -block2 = "0.6.2" -objc2 = "0.6.5" -objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSError", "NSString", "NSURL", "NSData", "NSProgress", "NSObject", "NSArray", "NSRunLoop", "NSDate"] } -objc2-virtualization = "0.3.2" - [profile.release] debug = "line-tables-only" diff --git a/crates/reims-ctl/src/cli.rs b/crates/reims-ctl/src/cli.rs index 26030c38c..f9788f6f9 100644 --- a/crates/reims-ctl/src/cli.rs +++ b/crates/reims-ctl/src/cli.rs @@ -46,7 +46,7 @@ pub enum Cmd { #[arg(long, short)] yes: bool, }, - /// Start a VM: a window opens for each of its displays + /// Start a VM: a window opens for its display Start { name: String }, /// Shut a VM down; if the guest has not shut down when the timeout ends, power it off Stop { @@ -67,9 +67,6 @@ pub enum Cmd { #[command(after_help = VIEW_HELP)] View { name: String, - /// The display to show, from 1 - #[arg(long, default_value_t = 1)] - display: u32, /// The most frames a second #[arg(long, default_value_t = 15)] fps: u32, @@ -84,12 +81,12 @@ pub enum Cmd { #[arg(long, short)] output: Option, }, - /// Give a VM (x86-64) an installer image for its next start; a DMG is converted to a raw + /// Give a VM an installer image for its next start; a DMG is converted to a raw /// image in the VM's directory Insert { name: String, path: PathBuf }, - /// Take the installer out of a VM (x86-64) + /// Take the installer out of a VM Eject { name: String }, - /// Replace a VM's OpenCore image (x86-64) with one the installed reims-util makes, presenting + /// Replace a VM's OpenCore image with one the installed reims-util makes, presenting /// the same Mac #[command(name = "update-opencore", after_help = UPDATE_OPENCORE_HELP)] UpdateOpencore { @@ -138,21 +135,6 @@ pub enum Cmd { Tui, #[command(name = "__vulkan-probe", hide = true)] VulkanProbe, - #[command(name = "__vz-install", hide = true)] - VzInstall { - #[arg(long)] - ipsw: PathBuf, - #[arg(long)] - dir: PathBuf, - #[arg(long)] - disk_mib: u64, - #[arg(long)] - cpus: u32, - #[arg(long)] - memory_mib: u64, - }, - #[command(name = "__vz-latest", hide = true)] - VzLatest, #[command(name = "__record-install", hide = true)] RecordInstall { #[arg(long)] @@ -175,26 +157,25 @@ buttons on the top row hold that key for the next key or click."; const UPDATE_HELP: &str = "\ After an update, the new reims-ctl's first run (its restart from the interface, or the next \ -command) updates the VMs an older reims-ctl made, once, with a line for each VM. An x86-64 VM \ -whose settings name no graphics, as those an older reims-ctl made on apple-gfx do, moves to \ -reims-vgpu's own GPU device if the macOS on its disk runs its drivers (macOS 26.4 or later), and \ -stays on apple-gfx if not; the choice is saved in its settings. Its OpenCore image is made again \ -for it, presenting the same Mac and without the ported drivers older images held, and the old \ -image is kept beside it as .pre-migration-1. A VM that is running then is updated at its \ -next start. One that can't be updated stays as it was, and its line says why. A VM whose settings \ -name graphics keeps them; where its OpenCore image still loads the ported drivers, the image is \ -made again for those graphics, and the old one is kept as .pre-migration-2."; +command) updates the VMs an older reims-ctl made, once, with a line for each VM. A VM whose \ +settings name no graphics, as those a reims-ctl from before reims-vgpu's own GPU device made, \ +runs that device, and one whose settings name apple-gfx, Apple's paravirtualized GPU, which \ +reims-vgpu no longer has, moves to it. Either's OpenCore image is made again for the device, \ +presenting the same Mac, with its macOS drivers and without the ported drivers older images \ +held, and the old image is kept beside it as .pre-migration-1, or -3 for one that was on \ +apple-gfx. A VM that is running then is updated at its next start. One that can't be updated \ +stays as it was, and its line says why. A VM on VMware SVGA keeps it; where its OpenCore image \ +still loads the ported drivers, the image is made again without them, and the old one is kept \ +as .pre-migration-2."; const UPDATE_OPENCORE_HELP: &str = "\ The new image is made for the VM's graphics. On reims-vgpu it holds the macOS drivers of \ reims-vgpu's own GPU device that this reims-ctl carries. A start makes the image again where it \ holds other builds of them, as one an older reims-ctl made does after an update of reims-ctl; an \ -image that lacks them, as one made for apple-gfx does, stays as it is, which reims-ctl start warns \ -of: make it again here. A change of graphics with reims-ctl set or the interface's edit form makes it \ -again where the VM is stopped, and a start on other graphics than reims-vgpu makes one without its \ -drivers where the image holds them. An image an older reims-util made also lacks what a newer one's \ -carries, such as ReimsVgpu.kext, which macOS 26 needs on apple-gfx for a display wider \ -than 2048 pixels and for GPU-accelerated Chrome. The new image presents the same Mac (its model, \ +image that lacks them, as one of your own may, stays as it is, which reims-ctl start warns of: \ +make it again here. A change of graphics with reims-ctl set or the interface's edit form makes it \ +again where the VM is stopped, and a start on VMware SVGA makes one without the drivers where the \ +image holds them. The new image presents the same Mac (its model, \ serial number, MLB, UUID and ROM, read from the old image's config.plist), so macOS sees no new \ machine, and the VM keeps its OVMF variables, which hold its boot entries. Its boot selection, \ OpenCore's picker, is carried over unless --boot-selection gives it; hidden, OpenCore boots \ @@ -226,11 +207,7 @@ USB devices other than hubs to the kvm group and to the user at this host's scre {rule} Over SSH, without a session at the screen, you need to be in the kvm group (sudo usermod -aG \ -kvm $USER, then log in again). - -macOS hosts have no USB passthrough: macOS gives a USB device that one of its drivers holds, \ -almost any device, only to a program running as root or holding an entitlement Apple grants VM \ -apps.", +kvm $USER, then log in again).", max = vm::USB_DEVICES_MAX, file = crate::usb::UDEV_RULE_FILE, rule = crate::usb::UDEV_RULE, @@ -271,15 +248,7 @@ const CREATE_EXAMPLES: &str = r" # A disk that already has macOS installed (copied; see --disk-mode), with # the OpenCore image it booted from, which keeps its Mac's identity - reims-ctl create mac --disk ~/vms/mac.qcow2 --opencore ~/vms/OpenCore.qcow2 - - An arm64 guest on an Apple silicon Mac: - - # Install the newest macOS this Mac supports, on a new 64G disk - reims-ctl create mac --ipsw latest --start - - # A macosvm or tart VM that already has macOS installed (an APFS clone) - reims-ctl create mac --bundle ~/VMs/macos13"; + reims-ctl create mac --disk ~/vms/mac.qcow2 --opencore ~/vms/OpenCore.qcow2"; #[derive(Args)] pub struct CreateArgs { @@ -307,69 +276,45 @@ pub struct CreateArgs { /// How an existing disk is used: copy (a reflink or clone where it can) or in-place #[arg(long, default_value = "copy")] pub disk_mode: String, - /// x86-64: 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) + /// 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")] pub macos: Option, - /// x86-64: with --macos, an offline installer of one release (13 to 20 GB), which installs - /// with no network, rather than Apple's recovery image (about 1 GB), which downloads the - /// newest release as it installs + /// With --macos, an offline installer of one release (13 to 20 GB), which installs with no + /// network, rather than Apple's recovery image (about 1 GB), which downloads the newest + /// release as it installs #[arg(long, requires = "macos")] pub offline: bool, - /// x86-64: an installer image of your own, attached as a disk: a raw image, such as a - /// recovery image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory + /// An installer image of your own, attached as a disk: a raw image, such as a recovery + /// image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory #[arg(long)] pub installer: Option, - /// x86-64: an OpenCore image of your own to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside - /// it (default: a new one made for the VM, with OVMF and a Mac identity of its own) + /// An OpenCore image of your own to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it + /// (default: a new one made for the VM, with OVMF and a Mac identity of its own) #[arg(long)] pub opencore: Option, /// The network card's MAC, such as 52:54:00:12:34:56 (default: a random one) #[arg(long)] pub mac: Option, - /// arm64: install macOS from this IPSW, or `latest` to download the newest this Mac supports - #[arg(long)] - pub ipsw: Option, - /// arm64: import a Virtualization.framework VM's directory (macosvm's or tart's) - #[arg(long)] - pub bundle: Option, - /// arm64: copy (an APFS clone) or in-place - #[arg(long, default_value = "copy")] - pub bundle_mode: String, - /// arm64: the machine identifier's ECID, where the bundle does not hold it - #[arg(long)] - pub ecid: Option, - /// x86-64: reims-vgpu (the default on macOS 26.4 and later), apple-gfx (the default on an - /// older macOS) or vmware-svga (see reims-ctl set --help); arm64 VMs have apple-gfx alone + /// reims-vgpu (the default) or vmware-svga (see reims-ctl set --help) #[arg(long)] pub graphics: Option, - /// apple-gfx: displays, 1 to 8, each in a window of its own (reims-vgpu has one) - #[arg(long)] - pub displays: Option, - /// apple-gfx: the guest's first mode: WIDTHxHEIGHT, or host for the host screen's modes; - /// reims-vgpu: the size its window opens at, WIDTHxHEIGHT in the desktop's points, which the - /// guest follows + /// The size reims-vgpu's window opens at, WIDTHxHEIGHT in the desktop's points, which the + /// guest follows; it starts a HiDPI desktop by itself in a window at least 3840 pixels + /// wide, and offers one in its Displays settings from 2880 #[arg(long)] pub resolution: Option, - /// apple-gfx: run the mode HiDPI (3840x2160 looks like 1920x1080); on reims-vgpu the guest - /// starts HiDPI by itself in a window at least 3840 pixels wide, and offers it in its - /// Displays settings from 2880 - #[arg(long, num_args = 0..=1, default_missing_value = "true")] - pub hidpi: Option, - /// Borderless windows that fill their screens + /// A borderless window that fills its screen #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub borderless: Option, - /// apple-gfx: the refresh rate offered to the guest (reims-vgpu's is the host screen's) - #[arg(long)] - pub refresh: Option, - /// The GPU (Linux): auto, a number or name from `reims-ctl gpus`, or a Vulkan ICD JSON file + /// The GPU: auto, a number or name from `reims-ctl gpus`, or a Vulkan ICD JSON file #[arg(long)] pub gpu: Option, /// Keep the library's log and the serial console #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub logs: Option, - /// A virtio sound device on the host's sound, with a microphone (on x86-64, also the HDA - /// controller OpenCore's boot chime plays on) + /// A virtio sound device on the host's sound, with a microphone, and the HDA controller + /// OpenCore's boot chime plays on #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub audio: Option, /// Forward this port on 127.0.0.1 to the guest's SSH port; 0 for none @@ -388,46 +333,26 @@ pub struct SetArgs { /// RAM, such as 8G #[arg(long)] pub memory: Option, - /// x86-64: reims-vgpu (the default on macOS 26.4 and later), its own GPU device, which the - /// guest drives with the kexts reims-ctl puts in its OpenCore image (a change of graphics - /// makes the image again for them, as update-opencore does, where the VM is stopped), on one - /// display in a window whose size the guest follows; apple-gfx - /// (the default on an older macOS, which the kexts don't load on), Apple's paravirtualized - /// GPU, the only one of arm64 VMs, with up to 8 displays and the host's video hardware; or - /// vmware-svga, QEMU's VMware SVGA: one display with no GPU acceleration, in QEMU's own - /// window. Without it, a VM runs the default for the macOS its disk holds, saved at its - /// first start + /// reims-vgpu (the default), its own GPU device, which the guest drives with the kexts + /// reims-ctl puts in its OpenCore image (a change of graphics makes the image again for + /// them, as update-opencore does, where the VM is stopped), on one display in a window whose + /// size the guest follows; or vmware-svga, QEMU's VMware SVGA: one display with no GPU + /// acceleration, in QEMU's own window #[arg(long)] pub graphics: Option, - /// x86-64: the system disk's controller: ahci (SATA), or nvme once macOS is installed (an - /// installer may find no disk on NVMe). Once it is installed, eject the installer before a + /// The system disk's controller: ahci (SATA), or nvme once macOS is installed (an installer + /// may find no disk on NVMe). Once it is installed, eject the installer before a /// move, or OpenCore may start it #[arg(long)] pub disk_controller: Option, - /// apple-gfx: 1 to 8 (reims-vgpu has one) - #[arg(long)] - pub displays: Option, - /// apple-gfx: WIDTHxHEIGHT, or host; reims-vgpu: the size its window opens at, WIDTHxHEIGHT - /// in the desktop's points + /// The size reims-vgpu's window opens at, WIDTHxHEIGHT in the desktop's points #[arg(long)] pub resolution: Option, - /// apple-gfx (on reims-vgpu the guest starts HiDPI by itself in a window at least 3840 - /// pixels wide, and offers it in its Displays settings from 2880) - #[arg(long, num_args = 0..=1, default_missing_value = "true")] - pub hidpi: Option, #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub borderless: Option, - /// apple-gfx: the refresh rate offered to the guest; 0 for the host screen's, reims-vgpu's - /// alone - #[arg(long)] - pub refresh: Option, /// auto, a number or name from `reims-ctl gpus`, or a Vulkan ICD JSON file #[arg(long)] pub gpu: Option, - /// On apple-gfx: the host's hardware video decode, encode and scaling for the guest. Off, - /// the guest does them in software - #[arg(long, num_args = 0..=1, default_missing_value = "true")] - pub video_acceleration: Option, #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub logs: Option, /// REIMS_VGPU_LOG's filter, such as info or warn,reims_vgpu_core=debug @@ -435,7 +360,7 @@ pub struct SetArgs { pub log_level: Option, #[arg(long, num_args = 0..=1, default_missing_value = "true")] pub audio: Option, - /// coreaudio, pipewire, pa, alsa, none, or auto + /// pipewire, pa, alsa, none, or auto #[arg(long)] pub audio_backend: Option, #[arg(long, num_args = 0..=1, default_missing_value = "true")] @@ -468,10 +393,7 @@ pub fn main(cli: Cli) -> Result { // The first run after an update brings the VMs an older reims-ctl made up to date, telling // of it on stderr, so a command's output stays as it is; reims-ctl's own commands, which the // installer and reims-ctl run, leave it to the user's. - if !matches!( - cmd, - Cmd::VulkanProbe | Cmd::VzInstall { .. } | Cmd::VzLatest | Cmd::RecordInstall { .. } - ) { + if !matches!(cmd, Cmd::VulkanProbe | Cmd::RecordInstall { .. }) { crate::migrate::run(&mut |s| eprintln!("{s}")); } match cmd { @@ -504,29 +426,21 @@ pub fn main(cli: Cli) -> Result { let t = timeout.map_or(vm.config.stop_timeout(), vm::stop_timeout); runtime::stop(&vm, force, t, |s| println!("{name}: {s}"))?; } - Cmd::Show { name } => show( - &crate::macos::as_started(&Registry::load()?.open(&name)?), - host, - ), + Cmd::Show { name } => show(&Registry::load()?.open(&name)?, host), Cmd::Set(a) => set(*a, host)?, Cmd::View { name, - display, fps, protocol, } => { let vm = Registry::load()?.open(&name)?; - let opts = view::Options { - display, - fps, - protocol, - }; + let opts = view::Options { fps, protocol }; if let Some(m) = view::run(&vm, &opts)? { println!("{m}"); } } Cmd::Command { name, output } => { - let vm = crate::macos::as_started(&Registry::load()?.open(&name)?); + let vm = Registry::load()?.open(&name)?; let script = runtime::invocation_for_print(&vm, host)?.shell_script(&script_comment(&vm)); match output { @@ -593,14 +507,6 @@ pub fn main(cli: Cli) -> Result { Cmd::Doctor => return doctor(host), Cmd::Tui => unreachable!(), Cmd::VulkanProbe => return Ok(gpu::probe_main()), - Cmd::VzInstall { - ipsw, - dir, - disk_mib, - cpus, - memory_mib, - } => return crate::vz::install_main(&ipsw, &dir, disk_mib, cpus, memory_mib), - Cmd::VzLatest => return crate::vz::latest_main(), Cmd::RecordInstall { repo, qemu, commit } => { install::Install { repo: repo.clone(), @@ -627,7 +533,7 @@ pub fn main(cli: Cli) -> Result { pub fn script_comment(vm: &Vm) -> String { let screen = match vm.config.graphics() { - vm::Graphics::ReimsVgpu | vm::Graphics::AppleGfx => "Its window opens under -display none", + vm::Graphics::ReimsVgpu => "Its window opens under -display none", vm::Graphics::VmwareSvga if crate::host::has_screen(&vm.config.extra_env) => { "Its window is QEMU's own, under -display gtk" } @@ -664,11 +570,11 @@ fn list(json: bool) -> Result<()> { return Ok(()); } println!( - "{:<20} {:<9} {:>5} {:>7} {:<9} DIR", - "NAME", "STATE", "CPUS", "MEMORY", "DISPLAYS" + "{:<20} {:<9} {:>5} {:>7} {:<11} DIR", + "NAME", "STATE", "CPUS", "MEMORY", "GRAPHICS" ); for e in ®.vms { - match Vm::load(&e.dir).map(|vm| crate::macos::as_started(&vm)) { + match Vm::load(&e.dir) { Ok(vm) => { let c = &vm.config; let state = if runtime::running(&vm) { @@ -677,17 +583,12 @@ fn list(json: bool) -> Result<()> { "stopped" }; println!( - "{:<20} {:<9} {:>5} {:>7} {:<9} {}", + "{:<20} {:<9} {:>5} {:>7} {:<11} {}", e.name, state, c.cpus, format_mib(c.memory_mib), - match c.graphics() { - vm::Graphics::AppleGfx => { - format!("{}x {}", c.display.count, c.display.resolution) - } - g => g.name().into(), - }, + c.graphics().name(), paths::tilde(&e.dir) ); } @@ -735,12 +636,8 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> { .or(a.name_pos.clone()) .ok_or_else(|| with_create_examples("give the VM a name: reims-ctl create NAME"))?; // Nothing a VM is made from: whatever create says is missing, the examples show the ways. - let source = a.macos.is_some() - || a.installer.is_some() - || a.disk.is_some() - || a.opencore.is_some() - || a.ipsw.is_some() - || a.bundle.is_some(); + let source = + a.macos.is_some() || a.installer.is_some() || a.disk.is_some() || a.opencore.is_some(); let mut s = Spec::new(&name); s.dir = a .dir @@ -756,14 +653,9 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> { path: paths::absolute(&p.to_string_lossy()), mode: ImportMode::parse(&a.disk_mode)?, }), - (None, None) if a.bundle.is_none() => Some(DiskSource::New { - size_mib: if a.ipsw.is_some() { - 64 * 1024 - } else { - 128 * 1024 - }, + (None, None) => Some(DiskSource::New { + size_mib: 128 * 1024, }), - _ => None, }; let abs = |p: &Option| p.as_ref().map(|p| paths::absolute(&p.to_string_lossy())); s.macos = a.macos.clone().map(|version| reims_util::Download { @@ -773,26 +665,11 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> { s.opencore = abs(&a.opencore); s.installer = abs(&a.installer); s.mac = a.mac.clone(); - s.ipsw = a.ipsw.clone().map(|i| { - if i == "latest" { - i - } else { - paths::absolute(&i).to_string_lossy().into_owned() - } - }); - s.bundle = abs(&a.bundle); - s.bundle_mode = ImportMode::parse(&a.bundle_mode)?; - s.ecid = a.ecid; s.graphics = a.graphics.as_deref().map(vm::Graphics::parse).transpose()?; - if let Some(n) = a.displays { - s.display.count = n; - } if let Some(r) = &a.resolution { s.display.resolution = r.clone(); } - s.display.hidpi = a.hidpi.unwrap_or(false); s.display.borderless = a.borderless.unwrap_or(false); - s.display.refresh = a.refresh; s.display.check()?; if let Some(g) = &a.gpu { s.gpu = resolve_gpu(g)?; @@ -810,8 +687,6 @@ fn create_cmd(a: CreateArgs, host: Host) -> Result<()> { println!("created {name} in {}", paths::tilde(&vm.dir)); if let Some(steps) = runtime::install_steps(&vm) { println!("{steps}"); - } else if runtime::needs_error_mode(&vm) { - println!("{name}: {}", runtime::SET_METAL_ERROR_MODE); } if a.start { let mut vm = vm; @@ -969,19 +844,6 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> { ), None => add("disk", format!("{disk_name} ({})", c.disk_format.as_str())), } - let mut disp = format!("{} x {}", c.display.count, c.display.resolution); - if c.display.hidpi { - disp.push_str(" HiDPI"); - } - if let Some((w, h)) = c.display.looks_like() { - disp.push_str(&format!(" (looks like {w}x{h})")); - } - if c.display.borderless { - disp.push_str(", borderless"); - } - if let Some(r) = c.display.refresh { - disp.push_str(&format!(", {r} Hz")); - } let graphics = c.graphics(); match graphics { vm::Graphics::VmwareSvga => add( @@ -990,11 +852,10 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> { ), g => add("graphics", g.describe().into()), } - // reims-vgpu's one display follows its window (vm::check_reims_vgpu_display): of the - // settings, only the window's first size and borderless reach it. - match graphics { - vm::Graphics::AppleGfx => add("displays", disp), - vm::Graphics::ReimsVgpu => add( + // reims-vgpu's one display follows its window: of the settings, only the window's first size + // and borderless reach it. + if graphics == vm::Graphics::ReimsVgpu { + add( "display", if c.display.borderless { "one, filling its screen, borderless".into() @@ -1002,8 +863,7 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> { let (w, h) = c.display.window_size().unwrap_or((1920, 1080)); format!("one, in a window opening at {w}x{h}, whose size the guest follows") }, - ), - vm::Graphics::VmwareSvga => {} + ); } if graphics.library() && c.profile.gpu_choice(host) { add( @@ -1015,17 +875,6 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> { }, ); } - if graphics == vm::Graphics::AppleGfx { - add( - "video", - if c.video_acceleration { - "on (the host's hardware)" - } else { - "off (the guest's software)" - } - .into(), - ); - } if let Some(q) = &c.q35 { add("opencore", paths::tilde(&vm.path(&q.opencore))); add( @@ -1037,9 +886,6 @@ pub fn describe(vm: &Vm, host: Host) -> Vec<(String, String)> { ); add("cpu model", q.cpu_model.clone()); } - if let Some(a) = &c.vmapple { - add("ecid", a.ecid.to_string()); - } add( "audio", if c.audio.enabled { @@ -1159,15 +1005,11 @@ pub fn set_installer( { let _ = std::fs::remove_file(c); } - let error_mode = match runtime::needs_error_mode(vm) { - true => format!("; {}", runtime::SET_METAL_ERROR_MODE), - false => String::new(), - }; Ok(match (&path, running) { (Some(p), false) => format!("{name}: {} attached for the next start", paths::tilde(p)), (Some(_), true) => format!("{name}: the installer changes at the next start"), - (None, false) => format!("{name}: installer removed{error_mode}"), - (None, true) => format!("{name}: the installer goes at the next start{error_mode}"), + (None, false) => format!("{name}: installer removed"), + (None, true) => format!("{name}: the installer goes at the next start"), }) } @@ -1198,31 +1040,15 @@ fn set(a: SetArgs, host: Host) -> Result<()> { None => bail!("{}: --disk-controller is for x86-64 VMs", c.name), } } - if let Some(n) = a.displays { - c.display.count = n; - } if let Some(r) = &a.resolution { c.display.resolution = r.clone(); } - if let Some(b) = a.hidpi { - c.display.hidpi = b; - } if let Some(b) = a.borderless { c.display.borderless = b; } - if let Some(r) = a.refresh { - c.display.refresh = (r != 0).then_some(r); - } - if c.graphics() == vm::Graphics::ReimsVgpu { - vm::check_reims_vgpu_display(a.displays, a.resolution.as_deref(), a.hidpi, a.refresh) - .with_context(|| c.name.clone())?; - } if let Some(g) = &a.gpu { c.gpu = resolve_gpu(g)?; } - if let Some(b) = a.video_acceleration { - c.video_acceleration = b; - } if let Some(b) = a.logs { c.logs.enabled = b; } @@ -1290,16 +1116,13 @@ fn set(a: SetArgs, host: Host) -> Result<()> { ); } } - show(&crate::macos::as_started(&vm), host); + show(&vm, host); Ok(()) } fn gpus(host: Host) { - if host.os != crate::host::Os::Linux { - println!( - "The library runs on the system's default Metal device on {}: there is no GPU to choose.", - qemu::os_word(host) - ); + if host.default_profile().is_none() { + println!("{}", crate::host::UNSUPPORTED); return; } let list = gpu::list(); @@ -1327,8 +1150,8 @@ fn gpus(host: Host) { /// `remove` first. fn usb(host: Host, name: Option<&str>, add: &[String], remove: &[String]) -> Result<()> { use crate::usb; - if host.os != crate::host::Os::Linux { - bail!("{}", usb::MAC_HOST); + if host.default_profile().is_none() { + bail!("{}", crate::host::UNSUPPORTED); } let devices = usb::host_devices(); let Some(name) = name else { @@ -1448,7 +1271,7 @@ fn doctor(host: Host) -> Result { "{host}{}", profile .map(|p| format!(", runs {p} VMs")) - .unwrap_or_else(|| ", which reims-ctl does not support yet".into()) + .unwrap_or_else(|| format!(": {}", crate::host::UNSUPPORTED)) ), ); line( @@ -1636,23 +1459,7 @@ fn doctor(host: Host) -> Result { }, ); } - crate::host::Os::Mac => { - line( - std::path::Path::new(qemu::AVPBOOTER).exists(), - "vmapple boot ROM", - qemu::AVPBOOTER.into(), - ); - line( - crate::vz::entitled(), - "virtualization entitlement", - if crate::vz::entitled() { - "present (installs from IPSWs)".into() - } else { - "missing: installing from an IPSW needs it; rerun scripts/install-ctl.sh".into() - }, - ); - } - crate::host::Os::Other => {} + crate::host::Os::Mac | crate::host::Os::Other => {} } if profile == Profile::Q35X86_64 { // What makes a new VM's OpenCore image, with its OVMF, and downloads its installer. @@ -1726,13 +1533,14 @@ mod tests { format!( r#" name = "{name}" - profile = "vmapple-arm64" + profile = "q35-x86_64" cpus = 2 memory_mib = 4096 disk = "{disk}" - [vmapple] - aux = "aux.img" - ecid = 1 + [q35] + opencore = "opencore.qcow2" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" "# ) }; diff --git a/crates/reims-ctl/src/create.rs b/crates/reims-ctl/src/create.rs index 69b01edfa..0335d31b7 100644 --- a/crates/reims-ctl/src/create.rs +++ b/crates/reims-ctl/src/create.rs @@ -8,11 +8,8 @@ //! needs an installer: one reims-util downloads from Apple (reims_util.rs), before the VM's //! directory is made, so a download stopped part way leaves no VM half made, or one given. An //! installer is used in place, except a DMG, which qemu-img converts to a raw image in the VM's -//! directory ([`installer_media`]). -//! -//! An arm64 VM (`vmapple-arm64`) is one Virtualization.framework made: installed here from an -//! IPSW (vz.rs), or imported from macosvm's or tart's directory (an APFS clone of its disk and -//! auxiliary storage, or used in place). +//! directory ([`installer_media`]). A VM's settings name its graphics: reims-vgpu's own device +//! unless the create chose another. use crate::host::{Host, Profile}; use crate::install; @@ -56,7 +53,7 @@ pub struct Spec { pub cpus: Option, pub memory_mib: Option, pub disk: Option, - /// The graphics device; none for the profile's default ([`Graphics::default_for`]). + /// The graphics device; none for the default, reims-vgpu's own. pub graphics: Option, pub display: Display, pub gpu: Gpu, @@ -69,11 +66,6 @@ pub struct Spec { pub macos: Option, pub opencore: Option, pub installer: Option, - // vmapple - pub ipsw: Option, - pub bundle: Option, - pub bundle_mode: ImportMode, - pub ecid: Option, } impl Spec { @@ -95,10 +87,6 @@ impl Spec { macos: None, opencore: None, installer: None, - ipsw: None, - bundle: None, - bundle_mode: ImportMode::Copy, - ecid: None, } } } @@ -169,29 +157,16 @@ pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result< } let profile = match spec.profile { Some(p) => p, - None => host - .default_profile() - .with_context(|| format!("reims-ctl runs no VMs on {host} yet"))?, + None => host.default_profile().context(crate::host::UNSUPPORTED)?, }; if !Profile::supported_on(host).contains(&profile) { - bail!("{host} cannot run {profile} VMs"); + bail!("{}", crate::host::UNSUPPORTED); } - let graphics = spec - .graphics - .unwrap_or_else(|| Graphics::default_for(profile)); - if graphics == Graphics::ReimsVgpu { - if profile != Profile::Q35X86_64 { - bail!( - "reims-vgpu's own GPU device is for x86-64 VMs: an arm64 macOS guest drives only \ - apple-gfx" - ); - } - let d = &spec.display; - check_reims_vgpu_display(Some(d.count), Some(&d.resolution), Some(d.hidpi), d.refresh)?; - // The image reims-util makes holds them. - if spec.opencore.is_none() { - crate::prebuilt::set()?; - } + let graphics = spec.graphics.unwrap_or_default(); + spec.display.check()?; + // The image reims-util makes holds them. + if graphics == Graphics::ReimsVgpu && spec.opencore.is_none() { + crate::prebuilt::set()?; } let dir = spec.dir.clone().unwrap_or_else(|| default_dir(&spec.name)); // Checked here, before a download, and again as the directory is taken, after it (claim). @@ -207,73 +182,40 @@ pub fn create(spec: Spec, host: Host, progress: &mut dyn FnMut(&str)) -> Result< let mut spec = spec; // The macOS version, where an installer was downloaded for it. let mut macos = None; - // The macOS the VM will run, where reims-ctl knows it: the download's, or the given disk's. - let mut found = Vec::new(); - if profile == Profile::Q35X86_64 { - if spec.macos.is_some() && spec.installer.is_some() { - bail!("give macOS to download or an installer, not both"); - } - if let Some(i) = &spec.installer - && !i.exists() - { - bail!("the installer {} does not exist", i.display()); - } - match &spec.opencore { - Some(oc) => { - own_firmware(oc)?; - } - // reims-util makes one, after the disk's copy. - None => { - reims_util::binary()?; - } - } - if spec.macos.is_none() - && spec.installer.is_none() - && matches!(spec.disk, Some(DiskSource::New { .. })) - { - bail!( - "a new disk needs macOS installed on it: give the macOS to download \ - (--macos tahoe), or an installer" - ); - } - if let Some(d) = spec.macos.take() { - let i = reims_util::installer(&d, progress)?; - spec.installer = Some(i.image); - found.push(crate::macos::Macos { - version: i.version.clone(), - build: i.build, - }); - macos = Some(i.version); - } else if let Some(DiskSource::Existing { path, .. }) = &spec.disk { - match ImageFormat::detect(path).and_then(|f| crate::macos::on_disk(path, f)) { - Ok(f) => found = f, - Err(e) => progress(&format!( - "reims-ctl can't tell which macOS {} holds ({e:#}): it runs on {}", - path.display(), - graphics.id() - )), - } - } - } else if spec.macos.is_some() { - bail!("an arm64 VM installs macOS from an IPSW (--ipsw latest)"); + if spec.macos.is_some() && spec.installer.is_some() { + bail!("give macOS to download or an installer, not both"); } - // A VM whose settings name no graphics runs the device for its macOS, saved by name where - // reims-ctl knows the macOS, and otherwise decided at the first start that finds macOS on - // its disk (macos.rs). - let saved = match profile { - Profile::Q35X86_64 => spec.graphics.or_else(|| crate::macos::graphics_for(&found)), - Profile::VmappleArm64 => Some(graphics), - }; - let graphics = saved.unwrap_or(graphics); - if let Some(note) = - crate::macos::create_note(&spec.name, &found, graphics, spec.graphics.is_some()) + if let Some(i) = &spec.installer + && !i.exists() { - progress(¬e); + bail!("the installer {} does not exist", i.display()); + } + match &spec.opencore { + Some(oc) => { + own_firmware(oc)?; + } + // reims-util makes one, after the disk's copy. + None => { + reims_util::binary()?; + } + } + if spec.macos.is_none() + && spec.installer.is_none() + && matches!(spec.disk, Some(DiskSource::New { .. })) + { + bail!( + "a new disk needs macOS installed on it: give the macOS to download \ + (--macos tahoe), or an installer" + ); + } + if let Some(d) = spec.macos.take() { + let i = reims_util::installer(&d, progress)?; + spec.installer = Some(i.image); + macos = Some(i.version); } let made = claim(&dir)?; let result = match profile { - Profile::Q35X86_64 => make_q35(&spec, saved, graphics, &dir, macos.as_deref(), progress), - Profile::VmappleArm64 => make_vmapple(&spec, host, &dir, progress), + Profile::Q35X86_64 => make_q35(&spec, graphics, &dir, macos.as_deref(), progress), }; let vm = match result { Ok(vm) => vm, @@ -341,11 +283,7 @@ fn base_config(spec: &Spec, profile: Profile, disk: PathBuf, disk_format: ImageF disk_format, stop_timeout_secs: 90, extra_args: vec![], - graphics: Some( - spec.graphics - .unwrap_or_else(|| Graphics::default_for(profile)), - ), - video_acceleration: true, + graphics: Some(spec.graphics.unwrap_or_default()), display: spec.display.clone(), gpu: spec.gpu.clone(), audio: Audio { @@ -362,7 +300,6 @@ fn base_config(spec: &Spec, profile: Profile, disk: PathBuf, disk_format: ImageF ..Logs::default() }, q35: None, - vmapple: None, extra_env: BTreeMap::new(), usb: vec![], } @@ -421,11 +358,9 @@ fn qemu_img(profile: Profile, args: &[&std::ffi::OsStr]) -> Result<()> { Ok(()) } -/// Makes an x86-64 VM on `graphics`, which its settings save as `saved`: none where they name -/// no graphics. +/// Makes an x86-64 VM on `graphics`, which its settings save by name. fn make_q35( spec: &Spec, - saved: Option, graphics: Graphics, dir: &Path, macos: Option<&str>, @@ -494,7 +429,7 @@ fn make_q35( None => None, }; let mut c = base_config(spec, Profile::Q35X86_64, disk, disk_format); - c.graphics = saved; + c.graphics = Some(graphics); c.network.mac = mac; c.q35 = Some(Q35 { opencore: oc_name, @@ -643,203 +578,6 @@ fn own_firmware(opencore: &Path) -> Result<(PathBuf, PathBuf)> { }) } -fn make_vmapple(spec: &Spec, host: Host, dir: &Path, progress: &mut dyn FnMut(&str)) -> Result { - if let Some(bundle) = &spec.bundle { - let b = Bundle::read(bundle)?; - let ecid = spec - .ecid - .or(b.ecid) - .context("the bundle's machine identifier was not found: give its ECID (--ecid)")?; - let (disk, aux) = match spec.bundle_mode { - ImportMode::InPlace => (b.disk.clone(), b.aux.clone()), - ImportMode::Copy => { - progress( - "cloning the disk and auxiliary storage (APFS clones where the volume allows)", - ); - copy_file(&b.disk, &dir.join("disk.img"))?; - copy_file(&b.aux, &dir.join("aux.img"))?; - (PathBuf::from("disk.img"), PathBuf::from("aux.img")) - } - }; - let mut c = base_config(spec, Profile::VmappleArm64, disk, ImageFormat::Raw); - if spec.cpus.is_none() - && let Some(n) = b.cpus - { - c.cpus = n; - } - if spec.memory_mib.is_none() - && let Some(m) = b.memory_mib - { - c.memory_mib = m; - } - c.vmapple = Some(Vmapple { aux, ecid }); - let vm = Vm { - dir: dir.to_path_buf(), - config: c, - }; - crate::runtime::ensure_aux_trimmed(&vm)?; - return Ok(vm); - } - if let Some(ipsw) = &spec.ipsw { - let size = match &spec.disk { - Some(DiskSource::New { size_mib }) => *size_mib, - None => 64 * 1024, - Some(DiskSource::Existing { .. }) => { - bail!("an IPSW installs onto a new disk: give its size, not an image") - } - }; - let mut c = base_config( - spec, - Profile::VmappleArm64, - "disk.img".into(), - ImageFormat::Raw, - ); - let ecid = crate::vz::install(ipsw, dir, size, c.cpus, c.memory_mib, progress)?; - c.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid, - }); - let vm = Vm { - dir: dir.to_path_buf(), - config: c, - }; - crate::runtime::ensure_aux_trimmed(&vm)?; - let _ = host; - return Ok(vm); - } - bail!( - "an arm64 VM is installed from an IPSW (--ipsw PATH, or --ipsw latest), or imported from a Virtualization.framework VM's directory (--bundle)" - ) -} - -// ---------------------------------------------------------------- Virtualization.framework VMs - -/// A Virtualization.framework VM's files, as macosvm or tart keep them. -#[derive(Clone, Debug)] -pub struct Bundle { - pub disk: PathBuf, - pub aux: PathBuf, - pub ecid: Option, - pub cpus: Option, - pub memory_mib: Option, -} - -impl Bundle { - pub fn read(dir: &Path) -> Result { - let dir = std::fs::canonicalize(dir) - .with_context(|| format!("{} does not exist", dir.display()))?; - let disk = dir.join("disk.img"); - if !disk.is_file() { - bail!( - "{} has no disk.img: not a macosvm or tart VM", - dir.display() - ); - } - // macosvm: vm.json, aux.img; its machineId is the identifier's data, in base64. - let vm_json = dir.join("vm.json"); - if vm_json.is_file() && dir.join("aux.img").is_file() { - let j: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&vm_json)?)?; - let ecid = j - .get("machineId") - .and_then(|v| v.as_str()) - .and_then(|b| ecid_from_identifier_base64(b).ok()); - let cpus = j.get("cpus").and_then(|v| v.as_u64()).map(|n| n as u32); - let memory_mib = j - .get("ram") - .and_then(|v| v.as_u64()) - .map(|b| b / (1024 * 1024)); - return Ok(Bundle { - disk, - aux: dir.join("aux.img"), - ecid, - cpus, - memory_mib, - }); - } - // tart: config.json with "ecid" (the identifier's data, in base64), nvram.bin. - let config = dir.join("config.json"); - if config.is_file() && dir.join("nvram.bin").is_file() { - let j: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&config)?)?; - let ecid = j - .get("ecid") - .and_then(|v| v.as_str()) - .and_then(|b| ecid_from_identifier_base64(b).ok()); - let cpus = j.get("cpuCount").and_then(|v| v.as_u64()).map(|n| n as u32); - let memory_mib = j - .get("memorySize") - .and_then(|v| v.as_u64()) - .map(|b| b / (1024 * 1024)); - return Ok(Bundle { - disk, - aux: dir.join("nvram.bin"), - ecid, - cpus, - memory_mib, - }); - } - if dir.join("aux.img").is_file() { - return Ok(Bundle { - disk, - aux: dir.join("aux.img"), - ecid: None, - cpus: None, - memory_mib: None, - }); - } - bail!( - "{} has a disk.img but no aux.img (macosvm) or nvram.bin (tart)", - dir.display() - ) - } -} - -/// The ECID in a `VZMacMachineIdentifier`'s data representation (a property list), given in -/// base64. -pub fn ecid_from_identifier_base64(b64: &str) -> Result { - let data = base64_decode(b64)?; - ecid_from_identifier(&data) -} - -pub fn ecid_from_identifier(data: &[u8]) -> Result { - let mut child = Command::new("plutil") - .args(["-extract", "ECID", "raw", "-o", "-", "-"]) - .stdin(std::process::Stdio::piped()) - .stdout(std::process::Stdio::piped()) - .stderr(std::process::Stdio::null()) - .spawn() - .context("run plutil")?; - use std::io::Write; - child.stdin.take().unwrap().write_all(data)?; - let out = child.wait_with_output()?; - let s = String::from_utf8_lossy(&out.stdout).trim().to_string(); - s.parse() - .with_context(|| format!("no ECID in the machine identifier ({s:?})")) -} - -pub fn base64_decode(s: &str) -> Result> { - let mut out = Vec::new(); - let mut acc: u32 = 0; - let mut bits = 0; - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - b'=' | b'\n' | b'\r' | b' ' => continue, - _ => bail!("not base64"), - } as u32; - acc = (acc << 6) | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - } - } - Ok(out) -} - #[cfg(test)] mod tests { use super::*; @@ -864,9 +602,9 @@ mod tests { let config = |spec: &Spec| { base_config( spec, - Profile::VmappleArm64, - "disk.img".into(), - ImageFormat::Raw, + Profile::Q35X86_64, + "disk.qcow2".into(), + ImageFormat::Qcow2, ) }; spec.ssh_port = Some(0); @@ -966,10 +704,4 @@ mod tests { assert!(!claim(&d).unwrap()); std::fs::remove_dir_all(&d).unwrap(); } - - #[test] - fn base64() { - assert_eq!(base64_decode("aGVsbG8=").unwrap(), b"hello"); - assert_eq!(base64_decode("aGVsbG8gd29ybGQ").unwrap(), b"hello world"); - } } diff --git a/crates/reims-ctl/src/form.rs b/crates/reims-ctl/src/form.rs index cee84fc5b..869dbe2cb 100644 --- a/crates/reims-ctl/src/form.rs +++ b/crates/reims-ctl/src/form.rs @@ -217,17 +217,6 @@ impl Form { } } - pub fn set_help(&mut self, key: &str, help: &str) { - if let Some(f) = self.fields.iter_mut().find(|f| f.key == key) { - f.help = help.into(); - } - } - - #[cfg(test)] - pub fn help(&self, key: &str) -> &str { - self.field(key).map(|f| f.help.as_str()).unwrap_or_default() - } - #[cfg(test)] pub fn focused_key(&self) -> &'static str { self.fields[self.focus].key @@ -640,8 +629,7 @@ mod tests { #[test] fn a_field_shows_in_a_form_without_the_field_it_follows() { - // As an arm64 VM's displays do: its edit form has no Graphics field. - let field = Field::text("displays", "Displays", "1", "").show_if("graphics", &["x"]); - assert_eq!(Form::new("t", "save", vec![field]).text("displays"), "1"); + let field = Field::text("resolution", "Resolution", "1", "").show_if("graphics", &["x"]); + assert_eq!(Form::new("t", "save", vec![field]).text("resolution"), "1"); } } diff --git a/crates/reims-ctl/src/gpu.rs b/crates/reims-ctl/src/gpu.rs index 4163d61b0..885d8bc6a 100644 --- a/crates/reims-ctl/src/gpu.rs +++ b/crates/reims-ctl/src/gpu.rs @@ -6,8 +6,6 @@ //! drives several GPUs, the PCI device ID (`VK_LOADER_DEVICE_ID_FILTER`). The list comes from //! asking each manifest's driver in a child process (`reims-ctl __vulkan-probe`), so a driver //! that hangs or crashes costs only that one. -//! -//! On macOS the library runs on the system's default Metal device; there is nothing to choose. use serde::{Deserialize, Serialize}; use std::path::PathBuf; diff --git a/crates/reims-ctl/src/host.rs b/crates/reims-ctl/src/host.rs index cb4629622..68b254892 100644 --- a/crates/reims-ctl/src/host.rs +++ b/crates/reims-ctl/src/host.rs @@ -1,11 +1,10 @@ //! The host reims-ctl runs on, and the machine profiles it can run there. //! //! A profile is one QEMU machine for one guest architecture: its binary, accelerator, devices -//! and what it can attach. Each host supports the profiles [`Profile::supported_on`] lists: -//! - macOS on arm64: [`Profile::VmappleArm64`], QEMU's `vmapple` machine on HVF, the machine -//! Virtualization.framework gives an arm64 macOS guest, with `apple-gfx-mmio`; -//! - Linux on x86-64: [`Profile::Q35X86_64`], `q35` on KVM, booted through OpenCore, with -//! `apple-gfx-pci`. +//! and what it can attach. Each host supports the profiles [`Profile::supported_on`] lists, and +//! only Linux on x86-64 has one: [`Profile::Q35X86_64`], `q35` on KVM, booted through OpenCore, +//! with reims-vgpu's own GPU device. A Mac host ran arm64 guests on vmapple, which went with +//! apple-gfx, and runs none ([`UNSUPPORTED`]). //! //! Another host or guest architecture is another profile (x86-64 guests on an Intel Mac would be //! `q35` on HVF, without the memfd RAM only Linux has): add it here and in `qemu.rs`. @@ -14,6 +13,9 @@ use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::fmt; +/// What reims-ctl tells a host it runs no VMs on, for a create or a start there. +pub const UNSUPPORTED: &str = "reims-ctl runs VMs on Linux x86-64 hosts"; + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Os { Mac, @@ -96,8 +98,6 @@ impl fmt::Display for Host { #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum Profile { - #[serde(rename = "vmapple-arm64")] - VmappleArm64, #[serde(rename = "q35-x86_64")] Q35X86_64, } @@ -105,7 +105,6 @@ pub enum Profile { impl Profile { pub fn supported_on(host: Host) -> &'static [Profile] { match (host.os, host.arch) { - (Os::Mac, Arch::Aarch64) => &[Profile::VmappleArm64], (Os::Linux, Arch::X86_64) => &[Profile::Q35X86_64], _ => &[], } @@ -113,14 +112,12 @@ impl Profile { pub fn id(self) -> &'static str { match self { - Profile::VmappleArm64 => "vmapple-arm64", Profile::Q35X86_64 => "q35-x86_64", } } pub fn describe(self) -> &'static str { match self { - Profile::VmappleArm64 => "arm64 macOS guest (vmapple, HVF)", Profile::Q35X86_64 => "x86-64 macOS guest (q35 and OpenCore, KVM)", } } @@ -128,18 +125,14 @@ impl Profile { /// The QEMU binary's name in the install's `bin`. pub fn qemu_binary(self) -> &'static str { match self { - Profile::VmappleArm64 => "qemu-system-aarch64", Profile::Q35X86_64 => "qemu-system-x86_64", } } - /// The accelerator on `host`. - pub fn accel(self, host: Host) -> &'static str { - match (self, host.os) { - // vendor/qemu's 4a2e2b3967 boots vmapple guests with the in-kernel GIC. - (Profile::VmappleArm64, _) => "hvf,kernel-irqchip=on", - (Profile::Q35X86_64, Os::Mac) => "hvf", - (Profile::Q35X86_64, _) => "kvm", + /// The accelerator. + pub fn accel(self) -> &'static str { + match self { + Profile::Q35X86_64 => "kvm", } } @@ -149,8 +142,7 @@ impl Profile { host.os == Os::Linux } - /// Whether a Vulkan GPU can be chosen: the library runs on Vulkan on Linux, and on Metal's - /// default device on macOS. + /// Whether a Vulkan GPU can be chosen: the library runs on Vulkan on Linux. pub fn gpu_choice(self, host: Host) -> bool { host.os == Os::Linux } @@ -166,28 +158,23 @@ impl fmt::Display for Profile { mod tests { use super::*; + /// Linux on x86-64 runs x86-64 guests; a Mac, which ran arm64 guests on vmapple, and any + /// other host run none. #[test] - fn each_supported_host_has_one_profile() { - let mac = Host { - os: Os::Mac, - arch: Arch::Aarch64, - }; + fn only_linux_on_x86_64_runs_vms() { let linux = Host { os: Os::Linux, arch: Arch::X86_64, }; - assert_eq!(mac.default_profile(), Some(Profile::VmappleArm64)); assert_eq!(linux.default_profile(), Some(Profile::Q35X86_64)); - assert_eq!( - Host { - os: Os::Linux, - arch: Arch::Aarch64 - } - .default_profile(), - None - ); + for (os, arch) in [ + (Os::Mac, Arch::Aarch64), + (Os::Mac, Arch::X86_64), + (Os::Linux, Arch::Aarch64), + ] { + assert_eq!(Host { os, arch }.default_profile(), None, "{os:?} {arch:?}"); + } assert!(Profile::Q35X86_64.memfd_ram(linux)); - assert!(!Profile::VmappleArm64.memfd_ram(mac)); } #[test] diff --git a/crates/reims-ctl/src/install.rs b/crates/reims-ctl/src/install.rs index b0fb36706..59f7c9d7c 100644 --- a/crates/reims-ctl/src/install.rs +++ b/crates/reims-ctl/src/install.rs @@ -5,7 +5,7 @@ //! the link, so a running VM's binary is never written. //! //! `REIMS_CTL_QEMU` names a QEMU binary to use instead (a build tree's, such as `make qemu`'s -//! `build/qemu/qemu-system-aarch64`); `qemu-img` is taken from beside it. +//! `build/qemu/qemu-system-x86_64`); `qemu-img` is taken from beside it. use crate::host::Profile; use crate::paths; @@ -146,24 +146,14 @@ pub fn has_device(qemu: &Path, name: &'static str) -> Option { /// The audio backend to use where the VM names none: the host's native one, among those built. pub fn default_audio_backend(available: &[String]) -> String { - let wanted: &[&str] = if cfg!(target_os = "macos") { - &["coreaudio"] - } else { - &["pipewire", "pa", "alsa", "sdl"] - }; - for w in wanted { + for w in ["pipewire", "pa", "alsa", "sdl"] { if available.iter().any(|a| a == w) { - return (*w).into(); + return w.into(); } } if available.is_empty() { // QEMU could not be asked (not installed yet): its usual choice. - return if cfg!(target_os = "macos") { - "coreaudio" - } else { - "pipewire" - } - .into(); + return "pipewire".into(); } "none".into() } @@ -201,7 +191,9 @@ mod tests { /// The installer's prune keeps a build older than the newest three while a QEMU runs from /// it, started as reims-ctl starts it, through `qemu/current`, which a newer build then - /// took; and removes the old builds nothing runs. + /// took; and removes the old builds nothing runs. The installer runs on Linux alone, whose + /// /proc names each process's executable. + #[cfg(target_os = "linux")] #[test] fn the_installers_prune_keeps_a_build_a_running_qemu_executes() { // The crate's directory, which cargo and nextest give a test process: read at run time, so @@ -275,7 +267,8 @@ mod tests { } /// The installer's --skip-qemu keeps the installed QEMU: with none installed it ends at - /// once, before it builds or installs anything, saying what to do. + /// once, before it builds or installs anything, saying what to do. On a host other than + /// Linux on x86-64 it ends before that, saying where reims-ctl runs VMs. #[test] fn the_installer_skips_qemu_only_where_one_is_installed() { let dir = std::env::var_os("CARGO_MANIFEST_DIR") @@ -289,24 +282,27 @@ mod tests { .arg("--skip-qemu") .env("XDG_DATA_HOME", root.join("data")) .env("XDG_CACHE_HOME", root.join("cache")) - .env_remove("GPU_ARM") .stdin(std::process::Stdio::null()) .output() .unwrap(); let _ = std::fs::remove_dir_all(&root); let err = String::from_utf8_lossy(&out.stderr); assert_eq!(out.status.code(), Some(1), "{err}"); - assert!( - err.contains("--skip-qemu keeps the installed QEMU, and none is installed") - && err.contains("run this without --skip-qemu, which builds it"), - "{err}" - ); + if cfg!(all(target_os = "linux", target_arch = "x86_64")) { + assert!( + err.contains("--skip-qemu keeps the installed QEMU, and none is installed") + && err.contains("run this without --skip-qemu, which builds it"), + "{err}" + ); + } else { + assert!(err.contains(crate::host::UNSUPPORTED), "{err}"); + } } /// What the installer says of the QEMU build --skip-qemu keeps: nothing where it was built /// from what this checkout builds it from, which a change to reims-ctl alone leaves as it - /// was; else that QEMU or the library changed since its commit, that the checkout lacks - /// that commit, or that it runs on the other GPU arm. + /// was; else that QEMU or the library changed since its commit, or that the checkout lacks + /// that commit. #[test] fn the_installer_says_when_the_qemu_it_keeps_is_not_this_checkouts() { let dir = std::env::var_os("CARGO_MANIFEST_DIR") @@ -349,38 +345,24 @@ mod tests { let built = commit("crates/reims-vgpu/src/lib.rs"); commit("crates/reims-ctl/src/main.rs"); commit("docs/qemu.md"); - let kept = |build: &str, arm_suffix: &str, gpu_arm: &str| { + let kept = |build: &str| { let out = std::process::Command::new("bash") .arg("-c") .arg(format!("set -euo pipefail\n{function}kept_qemu \"$1\"")) .arg("kept") .arg(format!("/data/reims-ctl/qemu/{build}")) .env("ROOT", &repo) - .env("ARM_SUFFIX", arm_suffix) - .env("GPU_ARM", gpu_arm) .output() .unwrap(); assert!(out.status.success(), "{out:?}"); String::from_utf8(out.stdout).unwrap() }; - let this = kept(&format!("20261107-120000-{built}"), "", "vulkan"); - let on_vulkan = kept( - &format!("20261107-120000-{built}-vulkan"), - "-vulkan", - "vulkan", - ); - let other_arm = kept(&format!("20261107-120000-{built}"), "-vulkan", "vulkan"); - let unknown = kept("20261107-120000-0000000", "", "vulkan"); + let this = kept(&format!("20261107-120000-{built}")); + let unknown = kept("20261107-120000-0000000"); commit("crates/reims-vgpu/src/lib.rs"); - let changed = kept(&format!("20261107-120000-{built}"), "", "vulkan"); + let changed = kept(&format!("20261107-120000-{built}")); let _ = std::fs::remove_dir_all(&repo); assert_eq!(this, ""); - assert_eq!(on_vulkan, ""); - assert_eq!( - other_arm, - "the installed QEMU runs on Metal, not GPU_ARM=vulkan: run this without --skip-qemu \ - to build it on vulkan\n" - ); assert_eq!( unknown, "the installed QEMU was built at 0000000, which this checkout does not have: run this \ @@ -398,18 +380,11 @@ mod tests { #[test] fn audio_backend_prefers_the_native_one() { let v = |s: &[&str]| s.iter().map(|x| x.to_string()).collect::>(); - if cfg!(target_os = "macos") { - assert_eq!( - default_audio_backend(&v(&["none", "coreaudio"])), - "coreaudio" - ); - } else { - assert_eq!( - default_audio_backend(&v(&["none", "alsa", "pa", "pipewire"])), - "pipewire" - ); - assert_eq!(default_audio_backend(&v(&["none", "alsa"])), "alsa"); - } + assert_eq!( + default_audio_backend(&v(&["none", "alsa", "pa", "pipewire"])), + "pipewire" + ); + assert_eq!(default_audio_backend(&v(&["none", "alsa"])), "alsa"); assert_eq!(default_audio_backend(&v(&["none", "dbus"])), "none"); } } diff --git a/crates/reims-ctl/src/macos.rs b/crates/reims-ctl/src/macos.rs index 50052f0e0..1674938e0 100644 --- a/crates/reims-ctl/src/macos.rs +++ b/crates/reims-ctl/src/macos.rs @@ -1,257 +1,16 @@ -//! Which macOS an x86-64 VM runs, and the graphics that follows from it. +//! What reims-ctl reads of the macOS on an x86-64 VM's disk: AppleGVA's setting that +//! reims-vgpu's kexts leave in the guest ([`gva_note`]). //! -//! reims-vgpu's own GPU device has a driver only in the guest's kexts reims-ctl carries -//! ([`crate::prebuilt`]), which OpenCore loads on the Darwin versions their MinKernel and MaxKernel -//! bound: macOS 26.4 and later releases of macOS 26. On an older macOS the device has no driver, -//! and the guest no GPU, where Apple's own driver in the guest drives apple-gfx. So a VM whose -//! settings name no graphics runs the device for the macOS it holds ([`graphics_for`]): -//! - at create, the macOS of the installer reims-util downloaded, or of the disk given; -//! - else at the first start that finds macOS on its disk ([`settle`]), which saves it by name, so -//! that it no longer changes with the guest: an update of the guest to macOS 26.4 leaves it on -//! apple-gfx, which still runs it, until its settings choose reims-vgpu. -//! -//! The disk tells its macOS through its APFS container's Preboot volume, which holds for each -//! install, in a directory named by its volume group's UUID (before volume groups, by its system -//! volume's), `System/Library/CoreServices/SystemVersion.plist`, a copy of the system's. Read from -//! an x86-64 macOS 26.7.2 (25G332) guest's disk: the file is 604 bytes, uncompressed, and its -//! directory is named by the volume group's UUID; the system volume itself is sealed, its tree -//! hashed. The reader follows Apple's File System Reference: the latest checkpoint's container -//! superblock, the container's object map, each volume's superblock, and the Preboot volume's -//! object map and file-system tree. It reads what macOS writes there and nothing else: no -//! encrypted volume, no compressed file, and no checkpoint area kept as a tree. +//! The reader follows Apple's File System Reference: the latest checkpoint's container +//! superblock, the container's object map, each volume's superblock, and a volume's object map +//! and file-system tree. It reads what macOS writes there and nothing else: no encrypted volume, +//! no compressed file, and no checkpoint area kept as a tree. Read from an x86-64 macOS 26.7.2 +//! (25G332) guest's disk: the system volume is sealed, its tree hashed, and the Data volume holds +//! the user's files. -use crate::host::Profile; use crate::opencore::{Disk, le16, le32, le64}; -use crate::prebuilt; use crate::vm::{Graphics, Vm}; use anyhow::{Context, Result, bail, ensure}; -use std::collections::BTreeSet; -use std::path::Path; - -/// A macOS release. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Macos { - /// Its version, "26.7.2"; for an online installer only its macOS's number, "26", since its - /// Reinstall macOS installs the newest release of it. - pub version: String, - /// Its build, "25G332", where known. - pub build: Option, -} - -impl Macos { - /// The Darwin version it runs, major and minor. A build names it: its number is Darwin's - /// major version, and its letter the minor, A for 0 (25G332 runs Darwin 25.6). Without one, - /// as an online installer's, only the major follows, from the macOS's number (macOS 26 and - /// later run Darwin one below it, 11 to 15 nine above, and 10.Y Y + 4), and the minor is - /// taken as 99: the newest release, as OpenCore's bound 25.99.99 stands for every release of - /// Darwin 25. - pub fn darwin(&self) -> Option<(u32, u32)> { - if let Some(d) = self.build.as_deref().and_then(build_darwin) { - return Some(d); - } - let mut parts = self.version.trim().split('.'); - let major: u32 = parts.next()?.parse().ok()?; - let darwin = match major { - 10 => parts.next()?.parse::().ok()? + 4, - 11..=15 => major + 9, - 26.. => major - 1, - _ => return None, - }; - Some((darwin, 99)) - } - - /// What to call it: "macOS 26.7.2 (25G332)". - pub fn describe(&self) -> String { - match &self.build { - Some(b) => format!("macOS {} ({b})", self.version), - None => format!("macOS {}", self.version), - } - } -} - -/// The Darwin version a build names: 25G332 is 25.6. -fn build_darwin(build: &str) -> Option<(u32, u32)> { - let digits = build.bytes().take_while(u8::is_ascii_digit).count(); - let major = build[..digits].parse().ok()?; - let letter = *build.as_bytes().get(digits)?; - letter - .is_ascii_uppercase() - .then(|| (major, u32::from(letter - b'A'))) -} - -/// The macOS release that runs Darwin `major`.`minor`, as [`Macos::darwin`] maps them: "26.4" -/// for 25.4. -fn release_of(major: u32, minor: u32) -> String { - match major { - 25.. => format!("{}.{minor}", major + 1), - 20..=24 => format!("{}.{minor}", major - 9), - _ => format!("10.{}", major.saturating_sub(4)), - } -} - -/// The graphics a VM whose settings name none runs, for `found`, each macOS its disk holds or the -/// one its installer installs: reims-vgpu's own device where the guest's kexts load on each, -/// apple-gfx where they don't load on one, and None where nothing is found, or reims-ctl carries -/// no kexts. -pub fn graphics_for(found: &[Macos]) -> Option { - if found.is_empty() { - return None; - } - let mut runs = true; - for m in found { - runs &= prebuilt::loads_on(m.darwin()?)?; - } - Some(if runs { - Graphics::ReimsVgpu - } else { - Graphics::AppleGfx - }) -} - -/// Why reims-vgpu's device has no driver on `m`, a macOS its kexts don't load on: "older than -/// macOS 26.4, the first release reims-vgpu's macOS drivers run on". -pub fn too_old_or_new(m: &Macos) -> String { - let (min, max) = prebuilt::bounds().unwrap_or(((0, 0), (u32::MAX, u32::MAX))); - match m.darwin() { - Some(d) if d > max => format!( - "newer than macOS {}, the last release reims-vgpu's macOS drivers run on", - release_of(max.0, max.1).trim_end_matches(".99") - ), - _ => format!( - "older than macOS {}, the first release reims-vgpu's macOS drivers run on", - release_of(min.0, min.1) - ), - } -} - -/// What a create that chose `graphics` for the VM `name` tells of it, after its name, where its -/// macOS, `found`, decided it, or where the reims-vgpu given has no driver on it. -pub fn create_note(name: &str, found: &[Macos], graphics: Graphics, given: bool) -> Option { - let old = found - .iter() - .find(|m| m.darwin().and_then(prebuilt::loads_on) == Some(false))?; - match (graphics, given) { - (Graphics::AppleGfx, false) => Some(format!( - "{} is {}, so it runs on apple-gfx", - old.describe(), - too_old_or_new(old) - )), - (Graphics::ReimsVgpu, true) => Some(format!( - "its {} is {}: on reims-vgpu macOS has no driver for its GPU, and draws without one. \ - To run it on apple-gfx, run reims-ctl set {name} --graphics apple-gfx.", - old.describe(), - too_old_or_new(old) - )), - _ => None, - } -} - -/// What to tell of a VM on reims-vgpu whose guest, `m`, has no driver for its device. -fn no_driver(name: &str, m: &Macos) -> String { - format!( - "{name} runs on reims-vgpu, but its {} is {}: macOS has no driver for its GPU, and draws \ - without one. To run it on apple-gfx, run reims-ctl set {name} --graphics apple-gfx.", - m.describe(), - too_old_or_new(m) - ) -} - -/// What a start does first for a stopped x86-64 VM on reims-vgpu: the macOS its disk holds. -#[derive(Debug, PartialEq)] -pub enum Settled { - /// Nothing to tell: another device, no macOS on the disk yet, or a macOS that runs the - /// device. - Kept, - /// Its settings named no graphics, and now name the one for its macOS, apple-gfx: what to - /// tell of it, after its name. - Saved(String), - /// A warning: the device has no driver on its macOS, which its settings chose; or reims-ctl - /// can't read its disk, and it runs the default. - Warn(String), -} - -/// For a stopped x86-64 VM on reims-vgpu, the macOS its disk holds: where its settings name no -/// graphics, the device for it is saved in them by name ([`graphics_for`]), and where they name -/// reims-vgpu on a macOS it has no driver on, that is a warning. A disk reims-ctl can't read is a -/// warning where the VM runs the default. -pub fn settle(vm: &mut Vm) -> Result { - if vm.config.profile != Profile::Q35X86_64 || vm.config.graphics() != Graphics::ReimsVgpu { - return Ok(Settled::Kept); - } - let name = vm.name().to_string(); - let found = match on_disk(&vm.disk(), vm.config.disk_format) { - Ok(f) => f, - Err(e) if vm.config.graphics.is_none() => { - return Ok(Settled::Warn(format!( - "reims-ctl can't tell which macOS {name}'s disk holds ({e:#}), so it runs on \ - reims-vgpu, whose macOS drivers need macOS {} or later. If it has an older \ - macOS, run reims-ctl set {name} --graphics apple-gfx.", - prebuilt::bounds() - .map(|(min, _)| release_of(min.0, min.1)) - .unwrap_or_default() - ))); - } - Err(_) => return Ok(Settled::Kept), - }; - let Some(graphics) = graphics_for(&found) else { - return Ok(Settled::Kept); - }; - if vm.config.graphics.is_some() { - return Ok(match graphics { - Graphics::ReimsVgpu => Settled::Kept, - _ => match found - .iter() - .find(|m| m.darwin().and_then(prebuilt::loads_on) == Some(false)) - { - Some(m) => Settled::Warn(no_driver(&name, m)), - None => Settled::Kept, - }, - }); - } - // Saved in the settings as they are now, which another reims-ctl may have changed. - let mut now = Vm::load(&vm.dir)?; - if now.config.graphics.is_some() { - *vm = now; - return Ok(Settled::Kept); - } - now.config.graphics = Some(graphics); - now.save()?; - *vm = now; - Ok(match graphics { - Graphics::ReimsVgpu => Settled::Kept, - _ => { - let m = found - .iter() - .find(|m| m.darwin().and_then(prebuilt::loads_on) == Some(false)) - .unwrap_or(&found[0]); - Settled::Saved(format!( - "its disk holds {}, which is {}, so it runs on apple-gfx, now saved in its \ - settings. Once its macOS is updated to {} or later, reims-ctl set {name} \ - --graphics reims-vgpu moves it to reims-vgpu's own GPU device.", - m.describe(), - too_old_or_new(m), - prebuilt::bounds() - .map(|(min, _)| format!("macOS {}", release_of(min.0, min.1))) - .unwrap_or_default() - )) - } - }) -} - -/// The VM as a start would run it: where its settings name no graphics, on the device -/// [`settle`] would save for the macOS its disk holds. For what `reims-ctl command`, `show` and -/// `list` print. -pub fn as_started(vm: &Vm) -> Vm { - let mut v = vm.clone(); - if v.config.profile == Profile::Q35X86_64 - && v.config.graphics.is_none() - && !crate::runtime::running(vm) - && let Ok(found) = on_disk(&vm.disk(), vm.config.disk_format) - { - v.config.graphics = graphics_for(&found); - } - v -} /// AppleGVA's gvaForceAMDKE as a VM's macOS keeps it, in /// /Library/Preferences/com.apple.AppleGVA.plist on its Data volume. RgfxGate, a kext of the @@ -293,7 +52,7 @@ fn gva_forced(vm: &Vm) -> Option { /// where the guest keeps no such setting. pub fn gva_note(vm: &Vm) -> Option { let graphics = vm.config.graphics(); - if vm.config.profile != Profile::Q35X86_64 || graphics == Graphics::ReimsVgpu { + if graphics == Graphics::ReimsVgpu { return None; } let others = gva_forced(vm)?; @@ -319,17 +78,6 @@ pub fn gva_note(vm: &Vm) -> Option { /// AppleGVA's preferences, from the Data volume's root. const GVA_PREFERENCES: &str = "Library/Preferences/com.apple.AppleGVA.plist"; -/// Each macOS the disk image at `path` holds: none where it has no GPT, no APFS container, or no -/// macOS installed on one yet. -pub fn on_disk(path: &Path, format: crate::vm::ImageFormat) -> Result> { - let disk = Disk::open(path, format)?; - let mut found = Vec::new(); - for start in crate::opencore::partitions(&disk, &APFS_TYPE)? { - found.extend(Container::open(&disk, start)?.macos()?); - } - Ok(found) -} - /// An APFS partition's type GUID, 7C3457EF-0000-11AA-AA11-00306543ECAC, as GPT stores it. const APFS_TYPE: [u8; 16] = [ 0xef, 0x57, 0x34, 0x7c, 0x00, 0x00, 0xaa, 0x11, 0xaa, 0x11, 0x00, 0x30, 0x65, 0x43, 0xec, 0xac, @@ -360,7 +108,6 @@ const APFS_INCOMPAT_CASE_INSENSITIVE: u64 = 1; const APFS_INCOMPAT_NORMALIZATION_INSENSITIVE: u64 = 8; /// `apfs_fs_flags`. const APFS_FS_UNENCRYPTED: u64 = 1; -const APFS_VOL_ROLE_PREBOOT: u16 = 0x10; const APFS_VOL_ROLE_DATA: u16 = 0x40; /// A file-system record's type, the top four bits of its key's first word. const APFS_TYPE_INODE: u8 = 3; @@ -524,61 +271,6 @@ impl<'a> Container<'a> { } Ok(out) } - - /// Each macOS its Preboot volumes hold, for an install whose volumes are in the container. - fn macos(&self) -> Result> { - let volumes = self.volumes()?; - // The UUIDs an install's Preboot directory may be named by. - let ids: BTreeSet = volumes - .iter() - .flat_map(|sb| [uuid(&sb[240..256]), uuid(&sb[1008..1024])]) - .filter(|u| u != "00000000-0000-0000-0000-000000000000") - .collect(); - let mut found = Vec::new(); - for sb in volumes.iter().filter(|sb| { - le16(sb, 964) == APFS_VOL_ROLE_PREBOOT && le64(sb, 264) & APFS_FS_UNENCRYPTED != 0 - }) { - let fs = Volume::open(self, sb)?; - for (name, dir) in fs.children(ROOT_DIR_INO_NUM)? { - if !ids.contains(&name.to_ascii_uppercase()) { - continue; - } - if let Some(file) = - fs.lookup(dir, "System/Library/CoreServices/SystemVersion.plist")? - { - found.push(parse_version(&fs.read(file)?)?); - } - } - } - Ok(found) - } -} - -/// A UUID's 16 bytes as text, as a Preboot directory names it: upper case, in groups. -fn uuid(b: &[u8]) -> String { - let hex: String = b.iter().map(|x| format!("{x:02X}")).collect(); - format!( - "{}-{}-{}-{}-{}", - &hex[..8], - &hex[8..12], - &hex[12..16], - &hex[16..20], - &hex[20..] - ) -} - -/// SystemVersion.plist's ProductVersion and ProductBuildVersion. -fn parse_version(bytes: &[u8]) -> Result { - let v = plist::Value::from_reader(std::io::Cursor::new(bytes)) - .context("read SystemVersion.plist")?; - let d = v - .as_dictionary() - .context("SystemVersion.plist holds no dictionary")?; - let text = |k: &str| d.get(k).and_then(plist::Value::as_string).map(String::from); - Ok(Macos { - version: text("ProductVersion").context("SystemVersion.plist has no ProductVersion")?, - build: text("ProductBuildVersion"), - }) } /// A B-tree node: its entries' table of contents, keys and values. @@ -878,7 +570,7 @@ fn checksum_ok(b: &[u8]) -> bool { #[cfg(test)] pub(crate) mod tests { use super::*; - use crate::vm::ImageFormat; + use std::path::Path; const BS: usize = 4096; @@ -1079,19 +771,14 @@ pub(crate) mod tests { img } - /// A Preboot volume holding SystemVersion.plist's `installs`, each in the directory named. - fn preboot<'a>(installs: &[(&'a str, &'a [u8])]) -> (Vol<'a>, Vec) { - let paths: Vec = installs - .iter() - .map(|(d, _)| format!("{d}/System/Library/CoreServices/SystemVersion.plist")) - .collect(); - let vol = Vol { - role: APFS_VOL_ROLE_PREBOOT, + /// An empty Preboot volume, as an install's container holds beside its Data volume. + fn preboot<'a>() -> Vol<'a> { + Vol { + role: 0x10, uuid: [0; 16], group: [0; 16], files: Vec::new(), - }; - (vol, paths) + } } /// A data volume of the volume group [`GROUP`], holding `files`. @@ -1100,8 +787,11 @@ pub(crate) mod tests { pub(crate) fn gva_disk(path: &Path) { let pref = br#" gvaForceAMDKE"#; - let (pre, _) = preboot(&[]); - std::fs::write(path, disk(&[pre, data(vec![(GVA_PREFERENCES, pref)])])).unwrap(); + std::fs::write( + path, + disk(&[preboot(), data(vec![(GVA_PREFERENCES, pref)])]), + ) + .unwrap(); } fn data<'a>(files: Vec<(&'a str, &'a [u8])>) -> Vol<'a> { @@ -1113,63 +803,11 @@ pub(crate) mod tests { } } - fn system_version(version: &str, build: &str) -> Vec { - format!( - r#" - - ProductBuildVersion{build} - ProductNamemacOS - ProductVersion{version} -"# - ) - .into_bytes() - } - const GROUP: [u8; 16] = [ 0xd3, 0x6e, 0x3c, 0x34, 0xbd, 0xaf, 0x44, 0xaa, 0xbe, 0x65, 0x17, 0xc5, 0xdd, 0x68, 0x6b, 0xc1, ]; - fn read(img: &[u8], name: &str) -> Result> { - let d = std::env::temp_dir().join(format!("reims-ctl-macos-{name}-{}", std::process::id())); - std::fs::write(&d, img).unwrap(); - let r = on_disk(&d, ImageFormat::Raw); - std::fs::remove_file(&d).unwrap(); - r - } - - /// The macOS of an install whose Preboot directory names its volume group, read from its - /// SystemVersion.plist; a directory naming no volume of the container, as an install - /// removed leaves, is none. - #[test] - fn a_disk_tells_the_macos_its_preboot_volume_holds() { - let ours = system_version("15.6.1", "24G90"); - let stale = system_version("14.0", "23A344"); - let installs = [ - ("D36E3C34-BDAF-44AA-BE65-17C5DD686BC1", &ours[..]), - ("00112233-4455-6677-8899-AABBCCDDEEFF", &stale[..]), - ]; - let (mut pre, paths) = preboot(&installs); - pre.files = paths - .iter() - .zip(&installs) - .map(|(p, (_, b))| (p.as_str(), *b)) - .collect(); - let img = disk(&[pre, data(Vec::new())]); - let found = read(&img, "one").unwrap(); - assert_eq!( - found, - [Macos { - version: "15.6.1".into(), - build: Some("24G90".into()) - }] - ); - // A damaged object, the Preboot volume's tree, is an error, not a disk without macOS. - let mut bad = img.clone(); - bad[40 * 512 + 6 * BS + 100] ^= 1; - assert!(read(&bad, "bad").is_err()); - } - /// A guest whose Data volume's AppleGVA preferences set gvaForceAMDKE, as RgfxGate leaves /// them, is told, with the file's other keys counted; one without the key, or without the /// file, is not. @@ -1197,7 +835,7 @@ pub(crate) mod tests { memory_mib = 4096 disk = "disk.img" disk_format = "raw" - graphics = "apple-gfx" + graphics = "vmware-svga" [q35] opencore = "opencore.img" firmware_code = "OVMF_CODE.fd" @@ -1208,8 +846,7 @@ pub(crate) mod tests { let vm = Vm::load(&dir).unwrap(); let note = || gva_note(&vm).unwrap_or_default(); let with = |files: Vec<(&str, &[u8])>| { - let (pre, _) = preboot(&[]); - std::fs::write(dir.join("disk.img"), disk(&[pre, data(files)])).unwrap(); + std::fs::write(dir.join("disk.img"), disk(&[preboot(), data(files)])).unwrap(); gva_forced(&vm) }; assert_eq!(with(vec![(GVA_PREFERENCES, &forced)]), Some(0)); @@ -1227,79 +864,4 @@ pub(crate) mod tests { ); assert_eq!(with(Vec::new()), None); } - - /// A disk with no GPT, as a new one is, or no APFS container, holds no macOS. - #[test] - fn a_new_disk_holds_no_macos() { - assert_eq!(read(&vec![0u8; 1 << 16], "empty").unwrap(), []); - let (pre, _) = preboot(&[]); - let mut img = disk(&[pre, data(Vec::new())]); - assert_eq!(read(&img, "no-install").unwrap(), []); - img[1024] ^= 0xff; - assert_eq!(read(&img, "no-apfs").unwrap(), []); - } - - /// The Darwin version of a release: its build's number and letter, else its macOS's number's - /// major and the newest minor. - #[test] - fn a_release_runs_the_darwin_version_its_build_names() { - let m = |v: &str, b: Option<&str>| Macos { - version: v.into(), - build: b.map(String::from), - }; - assert_eq!(m("26.7.2", Some("25G332")).darwin(), Some((25, 6))); - assert_eq!(m("26.4", Some("25E246")).darwin(), Some((25, 4))); - assert_eq!(m("26.4", Some("25E5207k")).darwin(), Some((25, 4))); - assert_eq!(m("26", None).darwin(), Some((25, 99))); - assert_eq!(m("15", None).darwin(), Some((24, 99))); - assert_eq!(m("15.6.1", None).darwin(), Some((24, 99))); - assert_eq!(m("10.15", None).darwin(), Some((19, 99))); - assert_eq!(m("tahoe", None).darwin(), None); - assert_eq!(release_of(25, 4), "26.4"); - assert_eq!(release_of(24, 6), "15.6"); - } - - /// reims-vgpu where the guest's kexts load on every macOS found, which the tests' set bounds - /// to Darwin 25.4.0 to 25.99.99; apple-gfx where they don't load on one; none for nothing - /// found. - #[test] - fn the_graphics_follow_the_guests_macos() { - let m = |v: &str, b: &str| Macos { - version: v.into(), - build: Some(b.into()), - }; - let online = |v: &str| Macos { - version: v.into(), - build: None, - }; - assert_eq!(graphics_for(&[]), None); - assert_eq!( - graphics_for(&[m("26.4", "25E246")]), - Some(Graphics::ReimsVgpu) - ); - assert_eq!(graphics_for(&[online("26")]), Some(Graphics::ReimsVgpu)); - assert_eq!( - graphics_for(&[m("26.3.1", "25D2128")]), - Some(Graphics::AppleGfx) - ); - assert_eq!(graphics_for(&[online("15")]), Some(Graphics::AppleGfx)); - assert_eq!( - graphics_for(&[m("26.7.2", "25G332"), m("15.6.1", "24G90")]), - Some(Graphics::AppleGfx) - ); - assert_eq!(graphics_for(&[online("27")]), Some(Graphics::AppleGfx)); - let note = create_note("t", &[m("15.6.1", "24G90")], Graphics::AppleGfx, false).unwrap(); - assert!( - note.starts_with("macOS 15.6.1 (24G90) is older than macOS 26.4"), - "{note}" - ); - assert_eq!( - create_note("t", &[m("26.4", "25E246")], Graphics::ReimsVgpu, false), - None - ); - let given = create_note("t", &[online("15")], Graphics::ReimsVgpu, true).unwrap(); - assert!(given.contains("--graphics apple-gfx"), "{given}"); - let newer = create_note("t", &[online("27")], Graphics::AppleGfx, false).unwrap(); - assert!(newer.contains("newer than macOS 26,"), "{newer}"); - } } diff --git a/crates/reims-ctl/src/main.rs b/crates/reims-ctl/src/main.rs index eb9538be9..542142f33 100644 --- a/crates/reims-ctl/src/main.rs +++ b/crates/reims-ctl/src/main.rs @@ -1,4 +1,4 @@ -//! reims-ctl: creates, boots and manages macOS VMs on QEMU's apple-gfx, on the QEMU +//! reims-ctl: creates, boots and manages x86-64 macOS VMs on Linux, on the QEMU //! scripts/install-ctl.sh builds with reims-vgpu. With no command it opens its interactive //! interface. @@ -25,7 +25,6 @@ mod update; mod usb; mod view; mod vm; -mod vz; use clap::Parser; diff --git a/crates/reims-ctl/src/migrate.rs b/crates/reims-ctl/src/migrate.rs index a5ddfb32d..a69bc53ef 100644 --- a/crates/reims-ctl/src/migrate.rs +++ b/crates/reims-ctl/src/migrate.rs @@ -8,25 +8,23 @@ //! `deferred`, the directories of the VMs that were running then. A lock beside it, //! `migrations.lock`, keeps two reims-ctl starting at once from migrating a VM twice. //! -//! Migration 1 is for the x86-64 VMs a reims-ctl from before reims-vgpu's own GPU device made: -//! their settings name no graphics, their OpenCore image has no kexts for that device, and may -//! hold the ported drivers images no longer carry. Each moves to reims-vgpu's own device where -//! the macOS its disk holds runs the device's drivers, as a start would choose -//! ([`crate::macos::graphics_for`]), and stays on apple-gfx otherwise; its image is made again for -//! that, presenting the same Mac ([`crate::opencore::renew`]), the old one kept beside it as -//! `.pre-migration-1`. A VM whose settings name graphics had them set by its user, or by -//! a reims-ctl that knew of the device, and keeps them. -//! -//! Migration 2 is for the x86-64 VMs whose OpenCore image still loads the ported drivers -//! ([`PORTED`]), whatever graphics their settings name: an image reims-util made before -//! reims-ctl's graphics option, which migration 1 left be where the VM's settings named graphics. -//! Each image is made again for the graphics the VM has, presenting the same Mac, the old one -//! kept as `.pre-migration-2`; one whose settings name no graphics is migration 1's case, -//! and gets its plan. +//! Each makes a VM's OpenCore image again, presenting the same Mac ([`crate::opencore::renew`]), +//! for the graphics it runs, the old image kept beside it as `.pre-migration-`: +//! - Migration 1 is for the x86-64 VMs a reims-ctl from before reims-vgpu's own GPU device made: +//! their settings name no graphics, which is that device, and their image has no kexts for it, +//! and may hold the ported drivers images no longer carry. +//! - Migration 2 is for the VMs whose image still loads the ported drivers ([`PORTED`]), whatever +//! graphics their settings name, which stay: an image reims-util made before reims-ctl's +//! graphics option, which migration 1 left be where the VM's settings named graphics. One +//! whose settings name no graphics is migration 1's, and one whose settings name apple-gfx +//! migration 3's. +//! - Migration 3 is for the VMs whose settings name apple-gfx, Apple's paravirtualized GPU, which +//! reims-vgpu no longer has: they read as reims-vgpu's own device ([`Graphics::ReimsVgpu`]), +//! and its image, made for apple-gfx, lacks the device's kexts. The new image's save names the +//! device. -use crate::macos::{self, Macos}; use crate::opencore::{self, Config}; -use crate::vm::{Graphics, Registry, Vm}; +use crate::vm::{CONFIG_FILE, Graphics, Registry, Vm}; use crate::{host::Profile, paths, runtime}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; @@ -35,10 +33,10 @@ use std::os::fd::AsRawFd; use std::path::{Path, PathBuf}; /// The migrations this reims-ctl carries: 1 to this. -pub const CURRENT: u32 = 2; +pub const CURRENT: u32 = 3; /// The ported drivers older OpenCore images load, by bundle name: the seven kexts that run Apple's -/// arm64 GPU driver on x86-64, which reims-util carried until its fe9bfe1 (reims_util::REV). +/// arm64 GPU driver on x86-64, which reims-util carried until its fe9bfe1. const PORTED: [&str; 7] = [ "AppleParavirtGPULoader.kext", "IOGPUFamilyBridge.kext", @@ -95,76 +93,80 @@ enum Plan { Skip, /// It runs: at its next start. Defer, - /// Its disk can't be read, so its macOS is not known: it stays as it was. - Unknown(String), - /// Its image made again for its macOS: on the graphics saved in its settings, or, where its - /// disk holds no macOS yet, on the default, with none saved; the macOS that decided. - Image(Option, Option), - /// Its image made again for the graphics its settings name, which stay. - Again(Graphics), + /// Its image made again for the graphics it runs, for this reason. + Image(Why), } -/// Migration 1's plan for `vm`, `running` or not, its disk's macOS read by `found`. -fn plan(vm: &Vm, running: bool, found: impl FnOnce() -> Result>) -> Plan { +/// Why a VM's image is made again. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Why { + /// Migration 1: its settings name no graphics, which is reims-vgpu's own device. + Default, + /// Migration 2: its image loads the ported drivers; its settings name these graphics. + Ported(Graphics), + /// Migration 3: its settings name apple-gfx. + AppleGfx, +} + +/// Migration 1's plan for `vm`, `running` or not. +fn plan(vm: &Vm, running: bool) -> Plan { if vm.config.profile != Profile::Q35X86_64 || vm.config.graphics.is_some() { return Plan::Skip; } if running { return Plan::Defer; } - match found() { - Err(e) => Plan::Unknown(format!("{e:#}")), - Ok(found) => { - let graphics = macos::graphics_for(&found); - // The one its graphics follow: on apple-gfx, the first the drivers don't run on. - let decided = found - .iter() - .find(|m| { - graphics == Some(Graphics::AppleGfx) - && m.darwin().and_then(crate::prebuilt::loads_on) == Some(false) - }) - .or(found.first()) - .cloned(); - Plan::Image(graphics, decided) - } - } + Plan::Image(Why::Default) } -/// Migration 2's plan for `vm`, `running` or not, from the kexts its image loads; one whose -/// settings name no graphics gets migration 1's, its disk's macOS read by `found`. -fn plan_2( - vm: &Vm, - running: bool, - kexts: &[String], - found: impl FnOnce() -> Result>, -) -> Plan { +/// Migration 2's plan for `vm`, `running` or not, from the kexts its image loads, and whether its +/// settings name apple-gfx (migration 3's); one whose settings name no graphics gets migration +/// 1's. +fn plan_2(vm: &Vm, running: bool, kexts: &[String], apple_gfx: bool) -> Plan { let ported = kexts .iter() .any(|k| PORTED.iter().any(|p| k.eq_ignore_ascii_case(p))); - if vm.config.profile != Profile::Q35X86_64 || !ported { + if vm.config.profile != Profile::Q35X86_64 || !ported || apple_gfx { return Plan::Skip; } match vm.config.graphics { - None => plan(vm, running, found), + None => plan(vm, running), Some(_) if running => Plan::Defer, - Some(g) => Plan::Again(g), + Some(g) => Plan::Image(Why::Ported(g)), } } +/// Migration 3's plan for `vm`, `running` or not, whose settings name apple-gfx or not. +fn plan_3(vm: &Vm, running: bool, apple_gfx: bool) -> Plan { + match (vm.config.profile, apple_gfx, running) { + (Profile::Q35X86_64, true, true) => Plan::Defer, + (Profile::Q35X86_64, true, false) => Plan::Image(Why::AppleGfx), + _ => Plan::Skip, + } +} + +/// Whether `vm`'s settings, as saved, name apple-gfx: they read as reims-vgpu's own device. +fn names_apple_gfx(vm: &Vm) -> bool { + std::fs::read_to_string(vm.dir.join(CONFIG_FILE)) + .ok() + .and_then(|t| t.parse::().ok()) + .is_some_and(|t| t.get("graphics").and_then(toml::Value::as_str) == Some("apple-gfx")) +} + /// Migration `n`'s plan for `vm`, `running` or not. fn plan_of(n: u32, vm: &Vm, running: bool) -> Plan { - let found = || macos::on_disk(&vm.disk(), vm.config.disk_format); match n { - 1 => plan(vm, running, found), - _ => { + 1 => plan(vm, running), + 2 => { let kexts = vm .config .q35 .as_ref() .map(|q| loaded(&vm.path(&q.opencore), q.opencore_format)) .unwrap_or_default(); - plan_2(vm, running, &kexts, found) + plan_2(vm, running, &kexts, names_apple_gfx(vm)) } + _ => plan_3(vm, running, names_apple_gfx(vm)), } } @@ -259,27 +261,13 @@ fn same_dir(a: &Path, b: &Path) -> bool { /// nothing did. fn carry_out(vm: &mut Vm, plan: Plan, n: u32) -> Option { let name = vm.name().to_string(); - let manual = format!( - "reims-ctl set {name} --graphics reims-vgpu (for macOS 26.4 or later) or apple-gfx \ - makes its OpenCore image for one" - ); match plan { Plan::Skip => None, Plan::Defer => Some(format!( "{name} is running: it is updated at its next start, which makes its OpenCore image \ again" )), - Plan::Unknown(why) => Some(format!( - "{name}: left as it was: reims-ctl can't tell which macOS its disk holds ({why}); \ - {manual}" - )), - Plan::Image(graphics, decided) => { - Some(match image(vm, graphics, decided.as_ref(), None, n) { - Ok(line) => format!("{name}: {line}"), - Err(e) => format!("{name}: left as it was: {e:#}; {manual}"), - }) - } - Plan::Again(graphics) => Some(match image(vm, None, None, Some(graphics), n) { + Plan::Image(why) => Some(match image(vm, why, n) { Ok(line) => format!("{name}: {line}"), Err(e) => format!( "{name}: left as it was: {e:#}; reims-ctl update-opencore {name} makes its \ @@ -289,16 +277,9 @@ fn carry_out(vm: &mut Vm, plan: Plan, n: u32) -> Option { } } -/// Saves `graphics` in `vm`'s settings and makes its OpenCore image again for them, or, with -/// `kept`, for the graphics its settings name, keeping the old image beside it as migration `n`'s -/// backup; what changed, or an error with the VM as it was. -fn image( - vm: &mut Vm, - graphics: Option, - decided: Option<&Macos>, - kept: Option, - n: u32, -) -> Result { +/// Makes `vm`'s OpenCore image again for the graphics it runs, keeping the old image beside it as +/// migration `n`'s backup; what changed, or an error with the VM as it was. +fn image(vm: &mut Vm, why: Why, n: u32) -> Result { let q = vm.config.q35.clone().context("it boots no OpenCore")?; let old = vm.path(&q.opencore); let before = loaded(&old, q.opencore_format); @@ -311,50 +292,27 @@ fn image( if let Some(b) = &backup { std::fs::copy(&old, b).with_context(|| format!("copy its image to {}", b.display()))?; } - let undo = |vm: &mut Vm, e: anyhow::Error| { - if let Some(b) = &backup { - let _ = std::fs::remove_file(b); - } - if graphics.is_some() - && let Ok(mut now) = Vm::load(&vm.dir) - { - now.config.graphics = None; - if now.save().is_ok() { - *vm = now; - } - } - e - }; - if let Some(g) = graphics { - vm.config.graphics = Some(g); - if let Err(e) = vm.save() { - return Err(undo(vm, e)); - } - } let made = match opencore::renew(vm, None, &mut |_| {}) { Ok(s) => s, - Err(e) => return Err(undo(vm, e.context("a new OpenCore image couldn't be made"))), + Err(e) => { + if let Some(b) = &backup { + let _ = std::fs::remove_file(b); + } + return Err(e.context("a new OpenCore image couldn't be made")); + } }; let q = vm.config.q35.clone().context("it boots no OpenCore")?; let after = loaded(&vm.path(&q.opencore), q.opencore_format); - let mut line = match (graphics, decided) { - _ if kept.is_some() => format!( + let mut line = match why { + Why::Default => "on reims-vgpu's own GPU device, the default".to_string(), + Why::Ported(g) => format!( "its OpenCore image is made again for {}, without the ported drivers older images \ held", - kept.map(Graphics::name).unwrap_or_default() + g.name() ), - (Some(Graphics::ReimsVgpu), Some(m)) => { - format!( - "now on reims-vgpu's own GPU device, whose drivers {} runs", - m.describe() - ) - } - (Some(Graphics::AppleGfx), Some(m)) => format!( - "stays on apple-gfx: its {} is {}", - m.describe(), - macos::too_old_or_new(m) - ), - _ => "on reims-vgpu's own GPU device, the default, as its disk holds no macOS yet".into(), + Why::AppleGfx => "moved from apple-gfx, which reims-vgpu no longer has, to reims-vgpu's \ + own GPU device" + .to_string(), }; line.push_str("; "); line.push_str( @@ -423,13 +381,6 @@ mod tests { use crate::opencore::tests::{image as oc_image, plist, qcow2}; use std::os::unix::fs::PermissionsExt; - fn macos(version: &str, build: &str) -> Macos { - Macos { - version: version.into(), - build: Some(build.into()), - } - } - fn entry(bundle: &str) -> String { format!( "BundlePath{bundle}\ @@ -485,46 +436,22 @@ mod tests { env.set("REIMS_CTL_UTIL", &util); } - /// Migration 1 is for an x86-64 VM whose settings name no graphics, stopped: on the graphics - /// its macOS runs, the test set's kexts loading on Darwin 25.4 and later (macOS 26.4); an - /// arm64 VM, or one whose settings name graphics, as its user chose, is left be. + /// Migration 1 is for an x86-64 VM whose settings name no graphics, stopped; one whose + /// settings name graphics, as its user chose (apple-gfx among them, migration 3's), is left + /// be. #[test] fn migration_1_is_for_x86_64_vms_with_no_graphics_chosen() { let env = crate::testenv::Env::new("migrate-plan"); - let new = || Ok(vec![macos("26.7.2", "25G332")]); - let old = || Ok(vec![macos("15.7.2", "24G325")]); let v = vm(&env.root.join("a"), "q35-x86_64", None, ""); - assert_eq!( - plan(&v, false, new), - Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))) - ); - assert_eq!( - plan(&v, false, old), - Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))) - ); - // A disk with an old and a new macOS: apple-gfx, for the old one. - assert_eq!( - plan(&v, false, || Ok(vec![ - macos("26.7.2", "25G332"), - macos("15.7.2", "24G325") - ])), - Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))) - ); - assert_eq!(plan(&v, false, || Ok(vec![])), Plan::Image(None, None)); - assert!(matches!( - plan(&v, false, || anyhow::bail!("an encrypted volume")), - Plan::Unknown(why) if why.contains("encrypted") - )); - assert_eq!(plan(&v, true, new), Plan::Defer); + assert_eq!(plan(&v, false), Plan::Image(Why::Default)); + assert_eq!(plan(&v, true), Plan::Defer); for g in ["apple-gfx", "reims-vgpu", "vmware-svga"] { let v = vm(&env.root.join(g), "q35-x86_64", Some(g), ""); - assert_eq!(plan(&v, false, new), Plan::Skip, "{g}"); + assert_eq!(plan(&v, false), Plan::Skip, "{g}"); } - let v = vm(&env.root.join("arm"), "vmapple-arm64", None, ""); - assert_eq!(plan(&v, false, new), Plan::Skip); } - /// A migration makes the image again for the graphics it saves, the old image kept beside + /// A migration makes the image again for the graphics the VM runs, the old image kept beside /// it, and tells what changed in one line; where the image can't be made, the VM's settings /// and image stay as they were, and the line says why and what to run. #[test] @@ -540,17 +467,11 @@ mod tests { let dir = env.root.join("old26"); let mut v = vm(&dir, "q35-x86_64", None, &ported); let old_bytes = std::fs::read(dir.join("opencore.img")).unwrap(); - let line = carry_out( - &mut v, - Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))), - 1, - ) - .unwrap(); + let line = carry_out(&mut v, Plan::Image(Why::Default), 1).unwrap(); assert!( - line.starts_with("old26: now on reims-vgpu's own GPU device"), + line.starts_with("old26: on reims-vgpu's own GPU device, the default"), "{line}" ); - assert!(line.contains("macOS 26.7.2 (25G332)"), "{line}"); assert!( line.contains("without AppleParavirtGPU.kext and with A.kext, B.kext"), "{line}" @@ -565,7 +486,7 @@ mod tests { .contains("--add-kext") ); let saved = Vm::load(&dir).unwrap(); - assert_eq!(saved.config.graphics, Some(Graphics::ReimsVgpu)); + assert_eq!(saved.config.graphics, None); assert_eq!( saved.config.q35.as_ref().unwrap().opencore, Path::new("opencore.qcow2") @@ -575,49 +496,14 @@ mod tests { old_bytes ); - // On apple-gfx, an image without the set's kexts, as reims-util makes for it. - std::fs::write( - &made, - qcow2(&oc_image(plist(&entry("Lilu.kext")).as_bytes())), - ) - .unwrap(); - let dir = env.root.join("old15"); - let mut v = vm(&dir, "q35-x86_64", None, &ported); - let line = carry_out( - &mut v, - Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))), - 1, - ) - .unwrap(); - assert!( - line.starts_with("old15: stays on apple-gfx: its macOS 15.7.2"), - "{line}" - ); - assert!(line.contains("older than macOS 26.4"), "{line}"); - assert!(line.contains("without AppleParavirtGPU.kext"), "{line}"); - assert!( - !std::fs::read_to_string(&args) - .unwrap() - .contains("--add-kext") - ); - assert_eq!( - Vm::load(&dir).unwrap().config.graphics, - Some(Graphics::AppleGfx) - ); - // reims-util fails: the VM as it was. util(&env, &made, &args, true); let dir = env.root.join("stuck"); let mut v = vm(&dir, "q35-x86_64", None, &ported); let before = std::fs::read(dir.join("opencore.img")).unwrap(); - let line = carry_out( - &mut v, - Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))), - 1, - ) - .unwrap(); + let line = carry_out(&mut v, Plan::Image(Why::Default), 1).unwrap(); assert!(line.starts_with("stuck: left as it was:"), "{line}"); - assert!(line.contains("reims-ctl set stuck --graphics"), "{line}"); + assert!(line.contains("reims-ctl update-opencore stuck"), "{line}"); let saved = Vm::load(&dir).unwrap(); assert_eq!(saved.config.graphics, None); assert_eq!( @@ -642,64 +528,74 @@ mod tests { } /// Migration 2 is for an x86-64 VM whose image loads the ported drivers, whatever graphics - /// its settings name, which stay; one whose settings name none gets migration 1's plan. An - /// image reims-util makes since fe9bfe1, or one migration 2 made, holds none, and is left be. + /// its settings name, which stay; one whose settings name none gets migration 1's plan, and + /// one whose settings name apple-gfx is migration 3's. An image reims-util makes since + /// fe9bfe1, or one migration 2 made, holds none, and is left be. #[test] fn migration_2_is_for_images_with_the_ported_drivers() { let env = crate::testenv::Env::new("migrate-plan-2"); - let new = || Ok(vec![macos("26.7.2", "25G332")]); let old = names(&[ "Lilu.kext", "ReimsVgpu.kext", "AppleParavirtGPUIOGPUFamily.kext", ]); - let fresh = names(&["Lilu.kext", "ReimsVgpu.kext"]); + let fresh = names(&["Lilu.kext"]); let ours = names(&["Lilu.kext", "ReimsGraphicsLoader.kext", "RgfxGate.kext"]); for (g, graphics) in [ - ("apple-gfx", Graphics::AppleGfx), ("reims-vgpu", Graphics::ReimsVgpu), ("vmware-svga", Graphics::VmwareSvga), ] { let v = vm(&env.root.join(g), "q35-x86_64", Some(g), ""); - assert_eq!(plan_2(&v, false, &old, new), Plan::Again(graphics), "{g}"); - assert_eq!(plan_2(&v, true, &old, new), Plan::Defer, "{g}"); - assert_eq!(plan_2(&v, false, &fresh, new), Plan::Skip, "{g}"); - assert_eq!(plan_2(&v, false, &ours, new), Plan::Skip, "{g}"); - assert_eq!(plan_2(&v, false, &[], new), Plan::Skip, "{g}"); + assert_eq!( + plan_2(&v, false, &old, false), + Plan::Image(Why::Ported(graphics)), + "{g}" + ); + assert_eq!(plan_2(&v, true, &old, false), Plan::Defer, "{g}"); + assert_eq!(plan_2(&v, false, &fresh, false), Plan::Skip, "{g}"); + assert_eq!(plan_2(&v, false, &ours, false), Plan::Skip, "{g}"); + assert_eq!(plan_2(&v, false, &[], false), Plan::Skip, "{g}"); } // Names compare as FAT32 compares them, case aside. let shouted = names(&["APPLEPARAVIRTGPULOADER.KEXT"]); - let v = vm(&env.root.join("case"), "q35-x86_64", Some("apple-gfx"), ""); - assert_eq!( - plan_2(&v, false, &shouted, new), - Plan::Again(Graphics::AppleGfx) - ); - // No graphics named: migration 1's plan, from its disk's macOS. - let v = vm(&env.root.join("none"), "q35-x86_64", None, ""); - assert_eq!( - plan_2(&v, false, &old, new), - Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))) - ); - assert_eq!(plan_2(&v, false, &fresh, new), Plan::Skip); let v = vm( - &env.root.join("arm"), - "vmapple-arm64", - Some("apple-gfx"), + &env.root.join("case"), + "q35-x86_64", + Some("vmware-svga"), "", ); - assert_eq!(plan_2(&v, false, &old, new), Plan::Skip); - // The plan reads the kexts from the VM's image. + assert_eq!( + plan_2(&v, false, &shouted, false), + Plan::Image(Why::Ported(Graphics::VmwareSvga)) + ); + // No graphics named: migration 1's plan. + let v = vm(&env.root.join("none"), "q35-x86_64", None, ""); + assert_eq!(plan_2(&v, false, &old, false), Plan::Image(Why::Default)); + assert_eq!(plan_2(&v, false, &fresh, false), Plan::Skip); + // apple-gfx named: migration 3's, read from the settings as saved. let v = vm( - &env.root.join("img"), + &env.root.join("apple"), "q35-x86_64", Some("apple-gfx"), &ported(), ); - assert_eq!(plan_of(2, &v, false), Plan::Again(Graphics::AppleGfx)); + assert_eq!(plan_2(&v, false, &old, true), Plan::Skip); + assert_eq!(plan_of(2, &v, false), Plan::Skip); + // The plan reads the kexts from the VM's image. + let v = vm( + &env.root.join("img"), + "q35-x86_64", + Some("vmware-svga"), + &ported(), + ); + assert_eq!( + plan_of(2, &v, false), + Plan::Image(Why::Ported(Graphics::VmwareSvga)) + ); let v = vm( &env.root.join("img2"), "q35-x86_64", - Some("apple-gfx"), + Some("vmware-svga"), &entry("Lilu.kext"), ); assert_eq!(plan_of(2, &v, false), Plan::Skip); @@ -720,11 +616,11 @@ mod tests { .unwrap(); util(&env, &made, &args, false); let dir = env.root.join("gfx"); - let mut v = vm(&dir, "q35-x86_64", Some("apple-gfx"), &ported()); + let mut v = vm(&dir, "q35-x86_64", Some("vmware-svga"), &ported()); let old_bytes = std::fs::read(dir.join("opencore.img")).unwrap(); - let line = carry_out(&mut v, Plan::Again(Graphics::AppleGfx), 2).unwrap(); + let line = carry_out(&mut v, Plan::Image(Why::Ported(Graphics::VmwareSvga)), 2).unwrap(); assert!( - line.starts_with("gfx: its OpenCore image is made again for apple-gfx"), + line.starts_with("gfx: its OpenCore image is made again for VMware SVGA"), "{line}" ); assert!( @@ -738,7 +634,7 @@ mod tests { "{line}" ); let saved = Vm::load(&dir).unwrap(); - assert_eq!(saved.config.graphics, Some(Graphics::AppleGfx)); + assert_eq!(saved.config.graphics, Some(Graphics::VmwareSvga)); assert_eq!( saved.config.q35.as_ref().unwrap().opencore, Path::new("opencore.qcow2") @@ -752,20 +648,20 @@ mod tests { // reims-util fails: the VM as it was. util(&env, &made, &args, true); let dir = env.root.join("stuck"); - let mut v = vm(&dir, "q35-x86_64", Some("apple-gfx"), &ported()); + let mut v = vm(&dir, "q35-x86_64", Some("vmware-svga"), &ported()); let before = std::fs::read(dir.join("opencore.img")).unwrap(); - let line = carry_out(&mut v, Plan::Again(Graphics::AppleGfx), 2).unwrap(); + let line = carry_out(&mut v, Plan::Image(Why::Ported(Graphics::VmwareSvga)), 2).unwrap(); assert!(line.starts_with("stuck: left as it was:"), "{line}"); assert!(line.contains("reims-ctl update-opencore stuck"), "{line}"); assert_eq!(std::fs::read(dir.join("opencore.img")).unwrap(), before); assert!(!dir.join("opencore.img.pre-migration-2").exists()); - // After migration 1: migration 2 alone, on the VM whose image holds the ported drivers. + // After migration 1: migrations 2 and 3, on the VM whose image holds the ported drivers. util(&env, &made, &args, false); let mut reg = Registry::default(); for (name, kexts) in [("ported", ported()), ("fresh", entry("Lilu.kext"))] { let dir = env.root.join(name); - vm(&dir, "q35-x86_64", Some("apple-gfx"), &kexts); + vm(&dir, "q35-x86_64", Some("vmware-svga"), &kexts); reg.add(name, &dir).unwrap(); } reg.save().unwrap(); @@ -788,12 +684,56 @@ mod tests { .exists() ); assert!(!env.root.join("fresh/opencore.img.pre-migration-2").exists()); - assert_eq!(load().done, 2); + assert_eq!(load().done, CURRENT); let mut said = Vec::new(); run(&mut |s| said.push(s.to_string())); assert!(said.is_empty(), "{said:?}"); } + /// Migration 3 is for an x86-64 VM whose settings, as saved, name apple-gfx: its image is made + /// again for reims-vgpu's own device, which its settings then name, the old one kept as + /// `.pre-migration-3`; one running waits for its start. + #[test] + fn migration_3_moves_apple_gfx_vms_to_reims_vgpu() { + let env = crate::testenv::Env::new("migrate-apple"); + let made = env.root.join("made.img"); + let args = env.root.join("args"); + let fresh = entry("Lilu.kext") + &entry("A.kext") + &entry("B.kext"); + std::fs::write(&made, qcow2(&oc_image(plist(&fresh).as_bytes()))).unwrap(); + util(&env, &made, &args, false); + for g in [None, Some("reims-vgpu"), Some("vmware-svga")] { + let v = vm(&env.root.join(g.unwrap_or("none")), "q35-x86_64", g, ""); + assert_eq!(plan_of(3, &v, false), Plan::Skip, "{g:?}"); + } + let dir = env.root.join("apple"); + let mut v = vm(&dir, "q35-x86_64", Some("apple-gfx"), &entry("Lilu.kext")); + assert_eq!(v.config.graphics, Some(Graphics::ReimsVgpu)); + assert_eq!(plan_of(3, &v, true), Plan::Defer); + let p = plan_of(3, &v, false); + assert_eq!(p, Plan::Image(Why::AppleGfx)); + let line = carry_out(&mut v, p, 3).unwrap(); + assert!( + line.starts_with( + "apple: moved from apple-gfx, which reims-vgpu no longer has, to reims-vgpu's \ + own GPU device" + ), + "{line}" + ); + assert!(line.contains(", with A.kext, B.kext"), "{line}"); + assert!( + line.contains("kept as opencore.img.pre-migration-3"), + "{line}" + ); + assert!( + std::fs::read_to_string(&args) + .unwrap() + .contains("--add-kext") + ); + let saved = std::fs::read_to_string(dir.join(CONFIG_FILE)).unwrap(); + assert!(saved.contains("graphics = \"reims-vgpu\""), "{saved}"); + assert_eq!(plan_of(3, &Vm::load(&dir).unwrap(), false), Plan::Skip); + } + #[test] fn a_line_names_up_to_three_kexts() { assert_eq!(some(&["A.kext"]), "A.kext"); @@ -825,12 +765,12 @@ mod tests { let _ = std::fs::remove_file(state_file()); // Three VMs: two whose settings name no graphics, one of them running, and one its user - // set to apple-gfx. + // set to VMware SVGA. let mut reg = Registry::default(); for (name, graphics) in [ ("idle", None), ("busy", None), - ("chosen", Some("apple-gfx")), + ("chosen", Some("vmware-svga")), ] { let dir = env.root.join(name); vm(&dir, "q35-x86_64", graphics, &entry("Lilu.kext")); @@ -852,9 +792,9 @@ mod tests { said.iter().any(|s| s.starts_with("busy is running")), "{said:?}" ); - // The idle one's disk can't be read here (there is none): left as it was. assert!( - said.iter().any(|s| s.starts_with("idle: left as it was")), + said.iter() + .any(|s| s.starts_with("idle: on reims-vgpu's own GPU device")), "{said:?}" ); assert!(!said.iter().any(|s| s.starts_with("chosen")), "{said:?}"); @@ -873,7 +813,10 @@ mod tests { let mut said = Vec::new(); at_start(&mut v, &mut |s| said.push(s.to_string())); assert_eq!(said.len(), 1, "{said:?}"); - assert!(said[0].starts_with("left as it was"), "{said:?}"); + assert!( + said[0].starts_with("on reims-vgpu's own GPU device"), + "{said:?}" + ); assert!(load().deferred.is_empty()); let mut said = Vec::new(); at_start(&mut v, &mut |s| said.push(s.to_string())); diff --git a/crates/reims-ctl/src/opencore.rs b/crates/reims-ctl/src/opencore.rs index 2cd9e8dd5..8e63cb5cd 100644 --- a/crates/reims-ctl/src/opencore.rs +++ b/crates/reims-ctl/src/opencore.rs @@ -1,12 +1,9 @@ //! An x86-64 VM's OpenCore image: the Mac it presents, and making the VM a new one. //! -//! reims-util makes a VM's image when the VM is made (reims_util.rs). A newer reims-util's -//! image can carry what an older one's lacks, such as Lilu and ReimsVgpu.kext, which on macOS -//! 26 let WindowServer run a display wider than 2048 pixels on apple-gfx and Chrome draw on the -//! GPU (docs/qemu.md, "x86-64 macOS guests: displays wider than 2048 pixels"); and a VM on -//! reims-vgpu's own GPU device needs the guest's kexts this reims-ctl carries -//! ([`crate::prebuilt`]), which an image made for apple-gfx, or by an older reims-ctl, lacks or -//! holds other builds of ([`missing_guest_kexts`]). [`renew`] replaces a VM's image with one the +//! reims-util makes a VM's image when the VM is made (reims_util.rs). A VM on reims-vgpu's own +//! GPU device needs the guest's kexts this reims-ctl carries ([`crate::prebuilt`]), which an +//! image of the user's own, or one an older reims-ctl made, may lack or hold other builds of +//! ([`missing_guest_kexts`]). [`renew`] replaces a VM's image with one the //! installed reims-util makes for the VM's graphics, presenting the same Mac, so macOS sees no //! new machine. reims-ctl keeps no copy of that identity: it is read from the old image's //! config.plist. @@ -97,11 +94,6 @@ impl Config { .collect() } - /// Whether OpenCore loads ReimsVgpu.kext: an enabled entry of Kernel > Add names it. - pub fn loads_reims_vgpu(&self) -> bool { - self.loaded_kexts().contains(&"ReimsVgpu.kext") - } - /// Whether OpenCore shows its boot picker at each start: Misc > Boot > ShowPicker. Hidden, /// it boots the default entry, macOS's startup disk. pub fn shows_picker(&self) -> bool { @@ -125,22 +117,6 @@ pub fn shows_picker(vm: &Vm) -> Option { .map(|c| c.shows_picker()) } -/// What to tell of an x86-64 VM whose OpenCore image does not load ReimsVgpu.kext, made by an -/// older reims-util; None where it does, or where the image cannot be read. -pub fn missing_kext(vm: &Vm) -> Option { - let q = vm.config.q35.as_ref()?; - let config = Config::read(&vm.path(&q.opencore), q.opencore_format).ok()?; - (!config.loads_reims_vgpu()).then(|| { - format!( - "Its OpenCore image has no ReimsVgpu.kext, which macOS 26 needs for a display wider \ - than 2048 pixels (WindowServer crashes on one without it) and for GPU-accelerated \ - Chrome. To make it a new image that has it, presenting the same Mac, press U in \ - reims-ctl or run reims-ctl update-opencore {}.", - vm.name() - ) - }) -} - /// How an image holds the guest's kexts for reims-vgpu's own device. #[derive(Debug, PartialEq)] enum GuestKexts { @@ -349,12 +325,7 @@ pub fn renew( id.serial, if picker { "on" } else { "off" } ); - if Config::read(&image, ImageFormat::Qcow2).is_ok_and(|c| !c.loads_reims_vgpu()) { - s.push_str( - "; the installed reims-util put no ReimsVgpu.kext in it: run reims-ctl update, \ - which installs the reims-util it needs, and make it again", - ); - } else if missing_guest_kexts(vm).is_some() { + if missing_guest_kexts(vm).is_some() { s.push_str( "; the installed reims-util did not put reims-vgpu's macOS drivers in it as given: \ run reims-ctl update, which installs the reims-util it needs, and make it again", @@ -991,7 +962,7 @@ pub(crate) mod tests { } /// The image of a VM is made for its graphics: on reims-vgpu with the guest's kexts the - /// tests carry, in their order, written to the data directory; on apple-gfx with none. + /// tests carry, in their order, written to the data directory; on VMware SVGA with none. #[test] fn renew_makes_the_image_for_the_vms_graphics() { use std::os::unix::fs::PermissionsExt; @@ -1050,16 +1021,11 @@ pub(crate) mod tests { assert!(added[1].ends_with("/B.kext"), "{added:?}"); let a = added[0].split(',').next().unwrap(); assert!(Path::new(a).join("Contents/MacOS/A").is_file()); - assert!( - !given - .iter() - .any(|a| ["--no-kexts", "--no-apv-arm64-port", "--no-video"].contains(a)), - "{given:?}" - ); + assert!(!given.contains(&"--no-kexts"), "{given:?}"); std::fs::copy(&made, dir.join("opencore.img")).unwrap(); std::fs::write( dir.join(crate::vm::CONFIG_FILE), - config("graphics = \"apple-gfx\""), + config("graphics = \"vmware-svga\""), ) .unwrap(); let mut vm = Vm::load(&dir).unwrap(); @@ -1068,9 +1034,9 @@ pub(crate) mod tests { assert!(!given.contains("--add-kext"), "{given}"); } - /// A VM on apple-gfx or VMware SVGA whose image loads a kext of the guest's set, as one made - /// for reims-vgpu does, has its image made for other graphics; one whose image loads none - /// does not. On reims-vgpu, an image lacking them is made for other graphics. + /// A VM on VMware SVGA whose image loads a kext of the guest's set, as one made for + /// reims-vgpu does, has its image made for other graphics; one whose image loads none does + /// not. On reims-vgpu, an image lacking them is made for other graphics. #[test] fn an_image_follows_the_graphics_by_the_guest_kexts_it_loads() { let env = crate::testenv::Env::new("follow"); @@ -1105,26 +1071,18 @@ pub(crate) mod tests { }; let lilu = entry("Lilu.kext"); let ours = lilu.clone() + &entry("A.kext") + &entry("B.kext"); - for g in ["apple-gfx", "vmware-svga"] { - let v = vm(g, &ours); - assert!( - holds_unused_guest_kexts(&v) && made_for_other_graphics(&v), - "{g}" - ); - let v = vm(g, &lilu); - assert!( - !holds_unused_guest_kexts(&v) && !made_for_other_graphics(&v), - "{g}" - ); - } + let v = vm("vmware-svga", &ours); + assert!(holds_unused_guest_kexts(&v) && made_for_other_graphics(&v)); + let v = vm("vmware-svga", &lilu); + assert!(!holds_unused_guest_kexts(&v) && !made_for_other_graphics(&v)); let v = vm("reims-vgpu", &ours); assert!(!holds_unused_guest_kexts(&v)); let v = vm("reims-vgpu", &lilu); assert!(!holds_unused_guest_kexts(&v) && made_for_other_graphics(&v)); } - /// A start of a VM on apple-gfx whose image loads the guest's kexts, as one made for - /// reims-vgpu does, makes it a new image for apple-gfx, without them, first, telling of the + /// A start of a VM on VMware SVGA whose image loads the guest's kexts, as one made for + /// reims-vgpu does, makes it a new image for VMware SVGA, without them, first, telling of the /// AppleGVA setting they left in its guest; a start on reims-vgpu leaves an image lacking /// them be, which its warnings tell of. #[test] @@ -1178,7 +1136,7 @@ pub(crate) mod tests { // Its guest keeps what RgfxGate wrote, which the new image's note tells of. crate::macos::tests::gva_disk(&dir.join("disk.img")); let mut v = vm( - "apple-gfx", + "vmware-svga", &(lilu.clone() + &entry("A.kext") + &entry("B.kext")), ); let mut said = Vec::new(); @@ -1326,21 +1284,6 @@ pub(crate) mod tests { ); } - #[test] - fn reims_vgpu_loads_where_an_enabled_entry_names_it() { - let entry = |bundle: &str, enabled: bool| { - format!( - "BundlePath{bundle}\ - Enabled<{enabled}/>" - ) - }; - assert!(!config("").loads_reims_vgpu()); - assert!(!config(&entry("ReimsVgpu.kext", false)).loads_reims_vgpu()); - assert!(!config(&entry("Lilu.kext", true)).loads_reims_vgpu()); - let both = entry("Lilu.kext", true) + &entry("ReimsVgpu.kext", true); - assert!(config(&both).loads_reims_vgpu()); - } - #[test] fn the_picker_shows_where_misc_boot_show_picker_is_true() { let with = |boot: &str| { diff --git a/crates/reims-ctl/src/prebuilt.rs b/crates/reims-ctl/src/prebuilt.rs index ffd8951da..c57628aeb 100644 --- a/crates/reims-ctl/src/prebuilt.rs +++ b/crates/reims-ctl/src/prebuilt.rs @@ -7,8 +7,8 @@ //! ([`guest_kexts`]): OpenCore loads them in that order. //! //! Embedded, they are the ones of the commit reims-ctl was built from, however -//! scripts/install-ctl.sh installed it (`cargo install --path`, on macOS and on Linux, with or -//! without the QEMU of that commit), and need nothing installed beside them. +//! scripts/install-ctl.sh installed it (`cargo install --path`, with or without the QEMU of that +//! commit), and need nothing installed beside them. //! //! Each is written where it is used, into the data directory's `prebuilt`, under a name of its //! content's hash: the ROM where a VM's QEMU command is made, the set where reims-util makes an @@ -70,41 +70,6 @@ fn carried() -> Option<&'static [Kext]> { Some(tests::SET) } -/// A Darwin version bound, X.Y.Z, as its major, minor and patch. -fn version(v: &str) -> Option<(u32, u32, u32)> { - let mut p = v.trim().split('.').map(|n| n.parse::().ok()); - let v = (p.next()??, p.next()??, p.next()??); - p.next().is_none().then_some(v) -} - -/// The Darwin versions, major and minor, that OpenCore loads every kext of the set on: the -/// latest of their MinKernel and the earliest of their MaxKernel. None where reims-ctl carries -/// no set, or the bounds leave none. -pub fn bounds() -> Option<((u32, u32), (u32, u32))> { - let (mut min, mut max) = ((0, 0, 0), (u32::MAX, u32::MAX, u32::MAX)); - for k in carried()? { - if let Some(m) = k.min_kernel { - min = min.max(version(m)?); - } - if let Some(m) = k.max_kernel { - max = max.min(version(m)?); - } - } - (min <= max).then_some(((min.0, min.1), (max.0, max.1))) -} - -/// Whether OpenCore loads every kext of the set on Darwin `major`.`minor` (its patch level taken -/// as 0, as no bound names one but 99); None where reims-ctl carries no set. -pub fn loads_on((major, minor): (u32, u32)) -> Option { - let mut loads = true; - for k in carried()? { - let at = (major, minor, 0); - loads &= k.min_kernel.and_then(version).is_none_or(|m| m <= at) - && k.max_kernel.and_then(version).is_none_or(|m| at <= m); - } - Some(loads) -} - /// The directory the embedded files are written into. fn dir() -> PathBuf { paths::data_dir().join("prebuilt") @@ -307,21 +272,6 @@ mod tests { std::fs::remove_dir_all(&d).unwrap(); } - /// The set loads on the Darwin versions its bounds cover, a whole Darwin version for a - /// bound of 99: the tests' set, Darwin 25.4.0 to 25.99.99, on macOS 26.4 and later releases - /// of macOS 26. - #[test] - fn the_set_loads_within_its_bounds() { - assert_eq!(bounds(), Some(((25, 4), (25, 99)))); - assert_eq!(loads_on((25, 4)), Some(true)); - assert_eq!(loads_on((25, 99)), Some(true)); - assert_eq!(loads_on((25, 3)), Some(false)); - assert_eq!(loads_on((24, 6)), Some(false)); - assert_eq!(loads_on((26, 0)), Some(false)); - assert_eq!(version("25.4.0"), Some((25, 4, 0))); - assert_eq!(version("25.4"), None); - } - /// The set embedded, where the checkout has one, is whole: each kext's executable is one of /// its files, and its bounds are X.Y.Z. #[test] diff --git a/crates/reims-ctl/src/qemu.rs b/crates/reims-ctl/src/qemu.rs index 11bedecbc..ce02ad322 100644 --- a/crates/reims-ctl/src/qemu.rs +++ b/crates/reims-ctl/src/qemu.rs @@ -1,30 +1,29 @@ //! The QEMU command line a VM runs: one [`Invocation`], which `start` runs and `command` //! prints as a shell script, so a printed script runs the VM exactly as reims-ctl does. //! -//! Every profile gets: -//! - on the library's devices (reims-vgpu's and apple-gfx), the library's window for each -//! display: `-display none` with `REIMS_VGPU_WINDOW` unset (`0` would keep the device -//! headless), never a window of QEMU's own; +//! Every VM gets: +//! - on reims-vgpu's own device, the library's window for its display: `-display none` with +//! `REIMS_VGPU_WINDOW` unset (`0` would keep the device headless), never a window of QEMU's +//! own; //! - a QMP socket (`-qmp`), through which reims-ctl stops the VM; //! - QEMU's pid file; //! - user networking with virtio-net, and an optional SSH port forward; with networking off, //! `-nic none`, without which QEMU gives the machine its default NIC on user networking (on //! q35 an e1000e in the first free slot, 1, where the root port's address is); //! - a virtio sound device on the host's audio backend, one output stream and one input stream, -//! which x86-64 macOS's AppleVirtIOSound drives and arm64 macOS's matches (docs/qemu.md, -//! "x86-64 macOS guests: audio"): Safari's Media Source players fail without an output device; -//! - on `q35-x86_64`, also an ICH9 Intel HDA controller with a line-out codec on that backend, -//! for OpenCore's boot chime: its AudioDxe drives HDA, not virtio sound, and x86-64 macOS 26 -//! has no HDA driver, so the guest's only output is the virtio device; +//! which x86-64 macOS's AppleVirtIOSound drives (docs/qemu.md, "x86-64 macOS guests: audio"): +//! Safari's Media Source players fail without an output device; and an ICH9 Intel HDA +//! controller with a line-out codec on that backend, for OpenCore's boot chime: its AudioDxe +//! drives HDA, not virtio sound, and x86-64 macOS 26 has no HDA driver, so the guest's only +//! output is the virtio device; //! - the library's log (`REIMS_VGPU_LOG`) in QEMU's: with logs on at their level, with the -//! serial console and timestamps; with logs off its warnings and device resets alone -//! ([`LOGS_OFF`]), which reims-ctl's warnings read. +//! serial console and timestamps; with logs off its warnings alone ([`LOGS_OFF`]). //! -//! `q35-x86_64` follows the command line the x86-64 guests were measured on (docs/qemu.md): -//! RAM as a shared memfd, which the library on Linux requires; the keyboard and tablet on a -//! qemu-xhci controller, since on ICH9's EHCI the guest stops re-arming a device's interrupt -//! transfers under GPU load and its input freezes, with the host's USB devices the VM's settings -//! give it beside them ([`crate::usb`]); fixed PCI addresses (the AHCI controller, which +//! The machine, `q35-x86_64`, follows the command line the x86-64 guests were measured on +//! (docs/qemu.md): RAM as a shared memfd, which the library on Linux requires; the keyboard and +//! tablet on a qemu-xhci controller, since on ICH9's EHCI the guest stops re-arming a device's +//! interrupt transfers under GPU load and its input freezes, with the host's USB devices the VM's +//! settings give it beside them ([`crate::usb`]); fixed PCI addresses (the AHCI controller, which //! holds OpenCore's image, the installer and, on SATA, the system disk, at slot 2, where //! OpenCore's boot entries name it; on NVMe, the system disk's controller at slot 10, //! [`DiskController`]); `isa-applesmc` with Apple's SMC key, [`OSK`]; @@ -38,43 +37,22 @@ //! stays dark and WindowServer waits on the GPU for good. Without S3, macOS's sleep stops at a //! dark wake, from which input wakes the display (docs/qemu.md). //! -//! An x86-64 VM's graphics ([`Graphics`]) are one of three: -//! - reims-vgpu's own GPU device, `reims-graphics-pci`, at apple-gfx's slot, 4, with the device's -//! id, `gfx`, which the terminal viewer's screendumps name, and the option ROM reims-ctl -//! carries as its `romfile` ([`Ctx::graphics_rom`], [`crate::prebuilt`]), which the device has -//! no default for. The guest drives it with the kexts reims-ctl puts in the VM's OpenCore -//! image. Its BAR 2, the library's region, is 1 GiB below 4 GiB, which macOS gives an address -//! only where q35 leaves room there, so the machine keeps 1 GiB of RAM below 4 GiB +//! A VM's graphics ([`Graphics`]) are one of two, each at slot 4 with the id `gfx`, which the +//! terminal viewer's screendumps name: +//! - reims-vgpu's own GPU device, `reims-graphics-pci`, with the option ROM reims-ctl carries as +//! its `romfile` ([`Ctx::graphics_rom`], [`crate::prebuilt`]), which the device has no default +//! for. The guest drives it with the kexts reims-ctl puts in the VM's OpenCore image. Its +//! BAR 2, the library's region, is 1 GiB below 4 GiB, which macOS gives an address only where +//! q35 leaves room there, so the machine keeps 1 GiB of RAM below 4 GiB //! (`max-ram-below-4g=1G`): with more, the guest's kext finds no region. Its one display opens //! in the library's window at the resolution's size ([`crate::vm::Display::window_size`], //! the device's `resolution`; 1920x1080 by default) and follows the window's size at the host -//! screen's rate: the displays' count, HiDPI and refresh -//! are apple-gfx's, and of the rest only borderless reaches it -//! (`REIMS_VGPU_WINDOW_BORDERLESS`). It has none of apple-gfx's other -//! devices, the IOSurface mapper and the video devices below, whose x86-64 guest drivers were -//! ports, which no image reims-util makes now holds. -//! - apple-gfx, `apple-gfx-pci`, with `apple-gfx-iosurface-pci` after it, at slot 6: the -//! IOSurface device a guest running Apple's arm64 GPU driver, ported, waits for, and the one -//! switch for what that driver needs. The library isolates a task, and device info offers -//! argument buffers, only while the mapper has a descriptor table, which the port's mapper -//! driver writes at its start. Apple's x86-64 driver never touches the mapper, so its tasks run -//! in process as without the device (docs/qemu.md, "The IOSurface device over PCI"). -//! - QEMU's `vmware-svga` in apple-gfx's slot (`graphics = "vmware-svga"`), with the id `gfx`. -//! The library then draws nothing, so the window's and the GPU's variables are left out, and -//! QEMU's own window, GTK's (`-display gtk`), shows the display. Where QEMU's environment names -//! no Wayland compositor or X server, GTK's window would end QEMU as it starts, so it is -//! `-display none` there, and the guest runs headless, as on the library's window. -//! -//! Every VM on apple-gfx also has the VideoToolbox device (`apple-videotoolbox-pci`, 106b:1a03) -//! and the M2 scaler device (`apple-m2scaler-pci`, 106b:1a0b). arm64 macOS ships their guest -//! drivers, which link the IOSurface mapper vmapple builds in. x86-64 macOS ships none: images -//! of reims-util before [`crate::reims_util::REV`] carried ports of them for macOS 26.7, which -//! link the port's mapper driver, so an x86-64 VM on apple-gfx has the devices at slots 8 and 9, -//! after its mapper, -//! and one on reims-vgpu or `vmware-svga`, which have no mapper, has neither. A guest without -//! the drivers leaves both devices without one (docs/qemu.md, "The VideoToolbox device" and "The -//! M2 scaler device"). A VM whose settings turn video acceleration off (`video_acceleration = -//! false`) has neither, and its guest decodes, encodes and scales video in software. +//! screen's rate; borderless reaches it as `REIMS_VGPU_WINDOW_BORDERLESS`. +//! - QEMU's `vmware-svga` (`graphics = "vmware-svga"`). The library then draws nothing, so the +//! window's and the GPU's variables are left out, and QEMU's own window, GTK's (`-display +//! gtk`), shows the display. Where QEMU's environment names no Wayland compositor or X server, +//! GTK's window would end QEMU as it starts, so it is `-display none` there, and the guest runs +//! headless, as on the library's window. //! //! The xHCI controller has seven ports (`p2=7,p3=7`), each taking a USB 2 and a USB 3 device: //! the keyboard, the tablet, and up to [`crate::vm::USB_DEVICES_MAX`] host devices, at their @@ -83,18 +61,12 @@ //! there first (hw/usb/bus.c, `usb_claim_port`), on which a high-speed device does not attach, //! so one port stays free. With as many USB 2 ports as USB 3 ones no port is USB 2 alone: QEMU //! gives a device the first free port, and one freed goes to the back of the line. -//! -//! `vmapple-arm64` follows scripts/internal/run_vmapple.sh, with the video devices besides. -use crate::host::{Host, Os, Profile}; +use crate::host::{Host, Profile}; use crate::vm::{DiskController, Graphics, Vm}; use anyhow::{Context, Result}; use std::path::{Path, PathBuf}; -/// Virtualization.framework's boot ROM for vmapple machines. -pub const AVPBOOTER: &str = - "/System/Library/Frameworks/Virtualization.framework/Resources/AVPBooter.vmapple2.bin"; - /// The SMC key `isa-applesmc` gives every x86-64 guest. pub const OSK: &str = "ourhardworkbythesewordsguardedpleasedontsteal(c)AppleComputerInc"; @@ -138,7 +110,6 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result { push(&["-name", &c.name]); match c.profile { Profile::Q35X86_64 => q35(vm, ctx, &mut a)?, - Profile::VmappleArm64 => vmapple(vm, ctx, &mut a)?, } common(vm, ctx, &mut a)?; a.extend(c.extra_args.iter().cloned()); @@ -157,12 +128,6 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result { if library && c.display.borderless { env.push(("REIMS_VGPU_WINDOW_BORDERLESS".into(), "1".into())); } - // reims-vgpu's display runs at its host screen's rate (the module doc). - if graphics == Graphics::AppleGfx - && let Some(r) = c.display.refresh - { - env.push(("REIMS_VGPU_WINDOW_REFRESH".into(), r.to_string())); - } if library && c.profile.gpu_choice(ctx.host) && let Some(f) = &c.gpu.driver_file @@ -190,10 +155,9 @@ pub fn invocation(vm: &Vm, ctx: &Ctx) -> Result { }) } -/// `REIMS_VGPU_LOG` with logs off: the library's warnings, and its `device reset` lines, into -/// QEMU's log beside QEMU's own errors. [`crate::runtime::warnings`] counts the warnings that -/// name an emptied object entry since the guest's last reset. -const LOGS_OFF: &str = "warn,reims_vgpu_core::device::lifecycle=info"; +/// `REIMS_VGPU_LOG` with logs off: the library's warnings, into QEMU's log beside QEMU's own +/// errors. +const LOGS_OFF: &str = "warn"; fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { let c = &vm.config; @@ -216,7 +180,7 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { &format!("memory-backend-memfd,id=ram,size={mem},share=on"), ]); } - push(&["-accel", c.profile.accel(ctx.host), "-m", &mem]); + push(&["-accel", c.profile.accel(), "-m", &mem]); let mut cpu = format!( "{},kvm=on,vendor=GenuineIntel,+invtsc,vmware-cpuid-freq=on", q.cpu_model @@ -333,30 +297,9 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { .window_size() .map_or(String::new(), |(w, h)| format!(",resolution={w}x{h}")) ), - Graphics::AppleGfx => format!( - "apple-gfx-pci,id=gfx,bus=pcie.0,addr=0x4,displays={},resolution={}", - c.display.count, - c.display.qemu_resolution()? - ), Graphics::VmwareSvga => "vmware-svga,id=gfx,bus=pcie.0,addr=0x4".into(), }; push(&["-device", &gfx]); - // After the GPU it names, which realizes first. - if graphics == Graphics::AppleGfx { - push(&[ - "-device", - "apple-gfx-iosurface-pci,id=iosfc,gpu=gfx,bus=pcie.0,addr=0x6", - ]); - // The video devices, whose guest drivers link the mapper's (the module doc). - if c.video_acceleration { - push(&[ - "-device", - "apple-videotoolbox-pci,id=video,bus=pcie.0,addr=0x8", - "-device", - "apple-m2scaler-pci,id=scaler,bus=pcie.0,addr=0x9", - ]); - } - } push(&[ "-device", "qemu-xhci,id=xhci,addr=0x5,conditional-intr-mapping=on,p2=7,p3=7", @@ -383,70 +326,6 @@ fn q35(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { Ok(()) } -fn vmapple(vm: &Vm, ctx: &Ctx, a: &mut Vec) -> Result<()> { - let c = &vm.config; - let v = c.vmapple.as_ref().context("no [vmapple] settings")?; - let aux = vm.aux_trimmed().context("no auxiliary storage")?; - let disk = vm.disk(); - let mut push = |xs: &[&str]| a.extend(xs.iter().map(|s| s.to_string())); - push(&["-accel", c.profile.accel(ctx.host)]); - push(&["-M", &format!("vmapple,uuid={}", v.ecid)]); - push(&[ - "-m", - &format!("{}M", c.memory_mib), - "-smp", - &c.cpus.to_string(), - ]); - push(&["-bios", AVPBOOTER]); - push(&[ - "-drive", - &format!("file={},if=pflash,format=raw", optp(&aux)), - ]); - push(&[ - "-drive", - &format!("file={},if=pflash,format=raw", optp(&disk)), - ]); - push(&[ - "-drive", - &format!("file={},if=none,id=aux,format=raw", optp(&aux)), - ]); - push(&[ - "-drive", - &format!("file={},if=none,id=root,format=raw", optp(&disk)), - ]); - push(&["-device", "vmapple-virtio-blk-pci,variant=aux,drive=aux"]); - push(&["-device", "vmapple-virtio-blk-pci,variant=root,drive=root"]); - if c.network.enabled { - push(&["-netdev", &netdev(vm)]); - push(&[ - "-device", - &format!("virtio-net-pci,netdev=net0,mac={}", c.network.mac), - ]); - } - push(&[ - "-global", - &format!("apple-gfx-mmio.displays={}", c.display.count), - ]); - push(&[ - "-global", - &format!("apple-gfx-mmio.resolution={}", c.display.qemu_resolution()?), - ]); - // The video devices, whose guest drivers arm64 macOS ships (the module doc). - if c.video_acceleration { - push(&[ - "-device", - "apple-videotoolbox-pci,id=video", - "-device", - "apple-m2scaler-pci,id=scaler", - ]); - } - if c.audio.enabled { - push(&["-audiodev", &audiodev(vm, ctx)]); - push(&["-device", "virtio-sound-pci,id=audio,audiodev=snd0"]); - } - Ok(()) -} - fn netdev(vm: &Vm) -> String { let mut n = "user,id=net0,ipv6=off".to_string(); if let Some(p) = vm.config.network.ssh_port { @@ -543,19 +422,10 @@ pub fn quote(s: &str) -> String { .unwrap_or_else(|_| format!("'{}'", s.replace('\'', "'\\''"))) } -/// The host OS's name, as a short word, for messages. -pub fn os_word(host: Host) -> &'static str { - match host.os { - Os::Mac => "macOS", - Os::Linux => "Linux", - Os::Other => "this OS", - } -} - #[cfg(test)] mod tests { use super::*; - use crate::host::Arch; + use crate::host::{Arch, Os}; use crate::vm::*; use std::collections::BTreeMap; @@ -585,8 +455,7 @@ mod tests { disk_format: ImageFormat::Qcow2, stop_timeout_secs: 90, extra_args: vec![], - graphics: Some(Graphics::AppleGfx), - video_acceleration: true, + graphics: None, display: Display::default(), gpu: Gpu::default(), audio: Audio::default(), @@ -607,7 +476,6 @@ mod tests { disk_controller: DiskController::Ahci, disk_port: 3, }), - vmapple: None, extra_env: BTreeMap::new(), usb: vec![], }, @@ -635,7 +503,10 @@ mod tests { let inv = invocation(&q35_vm(), &ctx(linux())).unwrap(); let a = &inv.args; for pair in [ - &["-machine", "q35,memory-backend=ram,dump-guest-core=off"][..], + &[ + "-machine", + "q35,memory-backend=ram,dump-guest-core=off,max-ram-below-4g=1G", + ][..], &[ "-object", "memory-backend-memfd,id=ram,size=12288M,share=on", @@ -659,21 +530,11 @@ mod tests { "-netdev", "user,id=net0,ipv6=off,hostfwd=tcp:127.0.0.1:2326-:22", ], + &["-vga", "none"], &[ "-device", - "apple-gfx-pci,id=gfx,bus=pcie.0,addr=0x4,displays=1,resolution=1920x1080", - ], - &[ - "-device", - "apple-gfx-iosurface-pci,id=iosfc,gpu=gfx,bus=pcie.0,addr=0x6", - ], - &[ - "-device", - "apple-videotoolbox-pci,id=video,bus=pcie.0,addr=0x8", - ], - &[ - "-device", - "apple-m2scaler-pci,id=scaler,bus=pcie.0,addr=0x9", + "reims-graphics-pci,id=gfx,bus=pcie.0,addr=0x4,\ + romfile=/d/firmware/ReimsGraphics-0123456789abcdef.rom", ], &[ "-device", @@ -698,11 +559,6 @@ mod tests { "the disk on SATA alone" ); assert!(!a.iter().any(|x| x.contains("usb-audio"))); - let at = |device: &str| a.iter().position(|x| x.starts_with(device)).unwrap(); - assert!( - at("apple-gfx-pci,") < at("apple-gfx-iosurface-pci,"), - "the mapper after the GPU it names" - ); assert!(!a.iter().any(|x| x.contains("installer")), "no installer"); assert!(inv.unset.contains(&"REIMS_VGPU_WINDOW".to_string())); assert!(!inv.unset.contains(&"REIMS_VGPU_LOG".to_string())); @@ -745,8 +601,7 @@ mod tests { assert!(!a.iter().any(|x| x.starts_with("usb-host")), "{a:?}"); } - /// With logs off the library still logs its warnings and device resets, which - /// [`crate::runtime::warnings`] reads from QEMU's log; with logs on, at their level. + /// With logs off the library still logs its warnings; with logs on, at their level. #[test] fn the_librarys_warnings_are_logged_with_logs_off() { let mut vm = q35_vm(); @@ -757,7 +612,7 @@ mod tests { env["REIMS_VGPU_LOG"].clone() }; assert!(!vm.config.logs.enabled); - assert_eq!(level(&vm), "warn,reims_vgpu_core::device::lifecycle=info"); + assert_eq!(level(&vm), "warn"); vm.config.logs = Logs { enabled: true, level: "debug".into(), @@ -776,18 +631,9 @@ mod tests { fn network_off_gives_the_machine_no_nic() { let mut q35 = q35_vm(); q35.config.network.enabled = false; - let mut vmapple = q35.clone(); - vmapple.config.profile = Profile::VmappleArm64; - vmapple.config.q35 = None; - vmapple.config.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1234, - }); - for (vm, host) in [(&q35, linux()), (&vmapple, mac())] { - let a = invocation(vm, &ctx(host)).unwrap().args; - assert!(has(&a, &["-nic", "none"]), "{a:?}"); - assert!(!a.iter().any(|x| x == "-netdev" || x.contains("net-pci"))); - } + let a = invocation(&q35, &ctx(linux())).unwrap().args; + assert!(has(&a, &["-nic", "none"]), "{a:?}"); + assert!(!a.iter().any(|x| x == "-netdev" || x.contains("net-pci"))); let a = invocation(&q35_vm(), &ctx(linux())).unwrap().args; assert!(!a.iter().any(|x| x == "-nic")); } @@ -832,36 +678,6 @@ mod tests { assert!(!inv.args.iter().any(|a| a.contains("virtio-sound"))); } - /// With video acceleration off, a VM's command line is the one with it on less the two video - /// devices, on q35 and on vmapple. - #[test] - fn video_acceleration_off_leaves_out_both_video_devices() { - let mut vmapple = q35_vm(); - vmapple.config.profile = Profile::VmappleArm64; - vmapple.config.q35 = None; - vmapple.config.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1234, - }); - for (vm, host) in [(q35_vm(), linux()), (vmapple, mac())] { - let mut on = invocation(&vm, &ctx(host)).unwrap().args; - let i = on - .iter() - .position(|x| x.starts_with("apple-videotoolbox-pci,")) - .unwrap(); - assert!( - on[i - 1] == "-device" - && on[i + 1] == "-device" - && on[i + 2].starts_with("apple-m2scaler-pci,"), - "{on:?}" - ); - on.drain(i - 1..i + 3); - let mut off = vm.clone(); - off.config.video_acceleration = false; - assert_eq!(invocation(&off, &ctx(host)).unwrap().args, on); - } - } - /// A disk moved to NVMe is on a controller of its own, off the AHCI controller. #[test] fn a_disk_on_nvme_has_a_controller_of_its_own() { @@ -927,7 +743,6 @@ mod tests { level: "debug".into(), }; vm.config.display.borderless = true; - vm.config.display.refresh = Some(120); vm.config.gpu = Gpu { driver_file: Some("/icd/nvidia.json".into()), device_id: Some(0x2204), @@ -940,7 +755,6 @@ mod tests { let env: BTreeMap<_, _> = inv.env.iter().cloned().collect(); assert_eq!(env["REIMS_VGPU_LOG"], "trace"); assert_eq!(env["REIMS_VGPU_WINDOW_BORDERLESS"], "1"); - assert_eq!(env["REIMS_VGPU_WINDOW_REFRESH"], "120"); assert_eq!(env["VK_DRIVER_FILES"], "/icd/nvidia.json"); assert_eq!(env["VK_LOADER_DEVICE_ID_FILTER"], "0x2204"); assert!(has(&inv.args, &["-serial", "file:/vms/t/logs/serial.log"])); @@ -949,12 +763,10 @@ mod tests { } #[test] - fn vmware_svga_takes_apple_gfx_slot_in_qemus_window() { + fn vmware_svga_takes_the_gfx_slot_in_qemus_window() { let mut vm = q35_vm(); vm.config.graphics = Some(Graphics::VmwareSvga); - vm.config.display.count = 2; vm.config.display.borderless = true; - vm.config.display.refresh = Some(120); vm.config.gpu.driver_file = Some("/icd/nvidia.json".into()); let inv = invocation(&vm, &ctx(linux())).unwrap(); let a = &inv.args; @@ -964,12 +776,7 @@ mod tests { &["-device", "vmware-svga,id=gfx,bus=pcie.0,addr=0x4"] )); assert!(has(a, &["-display", "gtk"])); - assert!(!a.iter().any(|x| x.contains("apple-gfx")), "{a:?}"); - assert!( - !a.iter() - .any(|x| x.starts_with("apple-videotoolbox") || x.starts_with("apple-m2scaler")), - "no video devices without the mapper their drivers link: {a:?}" - ); + assert!(!a.iter().any(|x| x.contains("reims-graphics")), "{a:?}"); assert!(inv.env.is_empty(), "{:?}", inv.env); // Without a screen for the window, headless. let headless = Ctx { @@ -978,28 +785,19 @@ mod tests { }; let a = invocation(&vm, &headless).unwrap().args; assert!(has(&a, &["-display", "none"])); - // On the library's devices, the library's window, never QEMU's. - let mut vm = q35_vm(); - for g in [Graphics::AppleGfx, Graphics::ReimsVgpu] { - vm.config.graphics = Some(g); - let a = invocation(&vm, &ctx(linux())).unwrap().args; - assert!(has(&a, &["-display", "none"])); - } + // On reims-vgpu's device, the library's window, never QEMU's. + let a = invocation(&q35_vm(), &ctx(linux())).unwrap().args; + assert!(has(&a, &["-display", "none"])); } - /// reims-vgpu's own device, with the ROM reims-ctl carries, in apple-gfx's slot, on a machine - /// that leaves its BAR room below 4 GiB, and none of apple-gfx's devices: the default of an - /// x86-64 VM whose settings name no graphics. Of the display settings only the resolution, - /// as its window's first size, and borderless reach it; the GPU and the logs are the - /// library's, as on apple-gfx. + /// reims-vgpu's own device, with the ROM reims-ctl carries, on a machine that leaves its BAR + /// room below 4 GiB: the default of a VM whose settings name no graphics. The resolution, as + /// its window's first size, and borderless reach it; the GPU and the logs are the library's. #[test] - fn reims_vgpu_has_its_own_device_and_none_of_apple_gfxs() { + fn reims_vgpu_has_its_own_device() { let mut vm = q35_vm(); - vm.config.graphics = None; - vm.config.display.count = 2; vm.config.display.resolution = "2560x1600".into(); vm.config.display.borderless = true; - vm.config.display.refresh = Some(120); vm.config.gpu.driver_file = Some("/icd/nvidia.json".into()); let inv = invocation(&vm, &ctx(linux())).unwrap(); let a = &inv.args; @@ -1018,19 +816,11 @@ mod tests { ] { assert!(has(a, pair), "missing {pair:?} in {a:?}"); } - for device in [ - "apple-gfx", - "apple-videotoolbox", - "apple-m2scaler", - "vmware-svga", - ] { - assert!(!a.iter().any(|x| x.contains(device)), "{device} in {a:?}"); - } + assert!(!a.iter().any(|x| x.contains("vmware-svga")), "{a:?}"); let env: BTreeMap<_, _> = inv.env.iter().cloned().collect(); assert_eq!(env["REIMS_VGPU_WINDOW_BORDERLESS"], "1"); assert_eq!(env["VK_DRIVER_FILES"], "/icd/nvidia.json"); assert!(env.contains_key("REIMS_VGPU_LOG")); - assert!(!env.contains_key("REIMS_VGPU_WINDOW_REFRESH"), "{env:?}"); assert!(inv.unset.contains(&"REIMS_VGPU_WINDOW".to_string())); // A comma in the ROM's path stays in the option's value; without memfd RAM the machine // still leaves the BAR its room. @@ -1053,52 +843,12 @@ mod tests { .any(|x| x.starts_with("reims-graphics-pci,") && !x.contains("resolution")), "{a:?}" ); - // apple-gfx keeps the machine's RAM below 4 GiB as it was. - vm.config.graphics = Some(Graphics::AppleGfx); + // VMware SVGA keeps the machine's RAM below 4 GiB as it was. + vm.config.graphics = Some(Graphics::VmwareSvga); let a = invocation(&vm, &ctx(linux())).unwrap().args; assert!(!a.iter().any(|x| x.contains("max-ram-below-4g")), "{a:?}"); } - #[test] - fn vmapple_follows_run_vmapple_sh() { - let mut vm = q35_vm(); - vm.config.profile = Profile::VmappleArm64; - vm.config.q35 = None; - vm.config.disk = "disk.img".into(); - vm.config.disk_format = ImageFormat::Raw; - vm.config.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1234, - }); - vm.config.display.count = 2; - let mut c = ctx(mac()); - c.audio_backend = "coreaudio".into(); - let a = invocation(&vm, &c).unwrap().args; - for pair in [ - &["-accel", "hvf,kernel-irqchip=on"][..], - &["-M", "vmapple,uuid=1234"], - &["-bios", AVPBOOTER], - &["-drive", "file=/vms/t/aux.img.trimmed,if=pflash,format=raw"], - &["-drive", "file=/vms/t/disk.img,if=none,id=root,format=raw"], - &["-device", "vmapple-virtio-blk-pci,variant=root,drive=root"], - &["-global", "apple-gfx-mmio.displays=2"], - &["-global", "apple-gfx-mmio.resolution=1920x1080"], - &["-device", "apple-videotoolbox-pci,id=video"], - &["-device", "apple-m2scaler-pci,id=scaler"], - &["-audiodev", "coreaudio,id=snd0"], - &["-device", "virtio-sound-pci,id=audio,audiodev=snd0"], - ] { - assert!(has(&a, pair), "missing {pair:?} in {a:?}"); - } - assert!( - !a.iter() - .any(|x| x.contains("usb-audio") || x.contains("hda")) - ); - assert!(!a.iter().any(|x| x.contains("memfd"))); - assert!(!a.iter().any(|x| x.contains("dump-guest-core"))); - assert!(!a.iter().any(|x| x.contains("ICH9-LPC"))); - } - /// A variable for QEMU's environment is named as the printed script's export takes it: a /// space or a `;` in its name would break the script or run more than QEMU. #[test] diff --git a/crates/reims-ctl/src/reims_util.rs b/crates/reims-ctl/src/reims_util.rs index 10fe0d51d..366746b7d 100644 --- a/crates/reims-ctl/src/reims_util.rs +++ b/crates/reims-ctl/src/reims_util.rs @@ -1,9 +1,9 @@ //! reims-util () makes what a new x86-64 VM boots from: //! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded //! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore -//! image presenting the same Mac (opencore.rs). An image holds Lilu and ReimsVgpu.kext, which -//! reims-util adds itself, and, for a VM on reims-vgpu's own device, the guest's kexts reims-ctl -//! carries, each given by `--add-kext` in the set's order ([`kext_args`]). reims-ctl runs it +//! image presenting the same Mac (opencore.rs). An image holds Lilu, which reims-util adds +//! itself, and, for a VM on reims-vgpu's own device, the guest's kexts reims-ctl carries, each +//! given by `--add-kext` in the set's order ([`kext_args`]). reims-ctl runs it //! with `--json`: each line on its stdout is an event, `step`, `progress` or `note`, and the last //! is `done`, with what it made, or `error`. //! @@ -40,7 +40,7 @@ use std::time::{Duration, Instant}; pub const REPO: &str = "https://github.com/steelbrain/reims-util"; /// The commit [`install`] installs. -pub const REV: &str = "fe9bfe1a622ae1be8d254effa74b5354bd098e43"; +pub const REV: &str = "5ca3b10683be28938c01f977b89af5ffa8685754"; /// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are /// installed, else the first on PATH. @@ -164,8 +164,6 @@ pub struct Installer { /// Its macOS's version: the macOS's number ("26") for an online installer, the release /// ("26.6.2") for an offline one. pub version: String, - /// An offline installer's build ("25G83"); none for an online one. - pub build: Option, } #[derive(Deserialize)] @@ -183,8 +181,6 @@ struct OfflineResult { #[derive(Deserialize)] struct OfflineRelease { version: String, - #[serde(default)] - build: Option, } /// Downloads `d`'s installer into the installers directory, or continues its download, or @@ -214,14 +210,12 @@ pub fn installer(d: &Download, progress: &mut dyn FnMut(&str)) -> Result Result> { @@ -597,7 +591,6 @@ mod tests { ); let comma = vec![PathBuf::from("/d,e/A.kext")]; assert!(add_kexts(&SET[..1], &comma).is_err()); - assert!(kext_args(Graphics::AppleGfx).unwrap().is_empty()); assert!(kext_args(Graphics::VmwareSvga).unwrap().is_empty()); } diff --git a/crates/reims-ctl/src/runtime.rs b/crates/reims-ctl/src/runtime.rs index 3809764dd..3cacf872d 100644 --- a/crates/reims-ctl/src/runtime.rs +++ b/crates/reims-ctl/src/runtime.rs @@ -103,7 +103,7 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> { let c = &vm.config; c.check()?; if !crate::host::Profile::supported_on(host).contains(&c.profile) { - bail!("{} is a {} VM, which {host} cannot run", c.name, c.profile); + bail!("{}", crate::host::UNSUPPORTED); } let need = |p: &Path, what: &str| -> Result<()> { if !p.exists() { @@ -129,14 +129,6 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> { ); } } - Profile::VmappleArm64 => { - need( - Path::new(qemu::AVPBOOTER), - "Virtualization.framework's boot ROM", - )?; - let v = c.vmapple.as_ref().unwrap(); - need(&vm.path(&v.aux), "the auxiliary storage")?; - } } if host.os == Os::Linux { let kvm = std::fs::OpenOptions::new() @@ -153,16 +145,6 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> { Ok(()) } -/// The reminder where an x86-64 VM on apple-gfx gets its macOS installed ([`needs_error_mode`]). -pub const SET_METAL_ERROR_MODE: &str = "set Metal's error mode once macOS is installed (README)"; - -/// Whether the VM's macOS needs Metal's error mode set (README; docs/qemu.md, "x86-64 macOS guests: -/// Metal's error mode"): an x86-64 VM on apple-gfx, whose icon service otherwise ends as it starts. -/// On reims-vgpu's own device a 26.7.2 guest without it comes up with its Dock and icon services. -pub fn needs_error_mode(vm: &Vm) -> bool { - vm.config.q35.is_some() && vm.config.graphics() == Graphics::AppleGfx -} - /// The host's `vm.max_map_count` (Linux). pub fn host_max_map_count() -> Option { std::fs::read_to_string("/proc/sys/vm/max_map_count") @@ -346,10 +328,6 @@ pub fn install_steps(vm: &Vm) -> Option { "pick Reinstall macOS" }; let name = vm.name(); - let error_mode = match needs_error_mode(vm) { - true => " and set Metal's error mode (README)", - false => "", - }; let first = match q.disk_controller { DiskController::Ahci => String::new(), DiskController::Nvme => format!( @@ -362,7 +340,7 @@ pub fn install_steps(vm: &Vm) -> Option { "{first}To install macOS, start {name}: OpenCore boots its installer into macOS \ Recovery. If the VM's disk is new, open Disk Utility, erase it (QEMU HARDDISK Media) as \ APFS and quit Disk Utility. Then {last}. Once macOS is installed, eject the installer \ - (reims-ctl eject {name}){error_mode}." + (reims-ctl eject {name})." )) } @@ -377,28 +355,6 @@ pub fn warnings(vm: &Vm, host: Host) -> Vec { if graphics == Graphics::ReimsVgpu { w.extend(crate::opencore::missing_guest_kexts(vm)); } - if graphics == Graphics::AppleGfx && vm.config.profile == Profile::Q35X86_64 { - w.extend(crate::opencore::missing_kext(vm)); - // docs/qemu.md, "x86-64 macOS guests: Metal's error mode": without it, macOS 26's icon - // service ends as it starts, again and again, and the library logs each command it left - // queued, which QEMU's log keeps with logs off too. From Recovery, the `cd` expands the - // Data volume's name, and `defaults` leaves the file at mode 0600, which the user's - // processes cannot read. - let n = emptied_entry_lines(&vm.qemu_log()); - if n >= 3 { - w.push(format!( - "QEMU's latest log has {n} lines on GPU work left by crashed macOS processes. On \ - x86-64 macOS 26 that's most likely its icon service, crashing because Metal's \ - error mode isn't set: the desktop can stay on its wallpaper with no menu bar, or \ - come up gray with a menu bar but no Dock. To set it, turn its boot selection \ - on (press e in reims-ctl, or run reims-ctl update-opencore {} --boot-selection), \ - boot Recovery from OpenCore's picker, open Utilities > Terminal and run: cd \ - /Volumes/*Data/Library/Preferences && defaults write \"$PWD/.GlobalPreferences\" \ - METAL_ERROR_MODE -int 5 && chmod 644 .GlobalPreferences.plist && reboot", - vm.name() - )); - } - } if host.os == Os::Linux && let Some(problem) = udmabuf_problem() { @@ -407,41 +363,6 @@ pub fn warnings(vm: &Vm, host: Host) -> Vec { w } -/// How many lines of a QEMU log, since the guest's last reset, name an object entry the guest -/// had emptied: the library logs them at its warn level when a command of a guest process that -/// has ended runs, and `device reset` at its info level; reims-ctl turns both on with logs off -/// too. The TUI asks at every draw, so the count carries on from the bytes already read while the -/// file is the same (by inode) and has not shrunk. -fn emptied_entry_lines(log: &Path) -> usize { - use std::os::unix::fs::MetadataExt; - const EMPTIED: &[u8] = b"has an empty entry"; - static READ: std::sync::Mutex<(std::path::PathBuf, u64, u64, usize)> = - std::sync::Mutex::new((std::path::PathBuf::new(), 0, 0, 0)); - let Ok(mut f) = std::fs::File::open(log) else { - return 0; - }; - let Ok(meta) = f.metadata() else { return 0 }; - let mut r = READ.lock().unwrap_or_else(|e| e.into_inner()); - if r.0 != log || r.1 != meta.ino() || r.2 > meta.len() { - *r = (log.to_path_buf(), meta.ino(), 0, 0); - } - let mut buf = Vec::new(); - if f.seek(SeekFrom::Start(r.2)).is_ok() { - let _ = f.take(meta.len() - r.2).read_to_end(&mut buf); - } - // Whole lines only: the rest is read again once its line ends. - let end = buf.iter().rposition(|&b| b == b'\n').map_or(0, |i| i + 1); - for l in buf[..end].split(|&b| b == b'\n') { - if l.ends_with(b"device reset") { - r.3 = 0; - } else if l.windows(EMPTIED.len()).any(|w| w == EMPTIED) { - r.3 += 1; - } - } - r.2 += end as u64; - r.3 -} - /// Keeps the last five of a log: `x.log` becomes `x.1.log`, and so on. fn rotate(path: &Path) { let stem = path.file_stem().unwrap().to_string_lossy().into_owned(); @@ -454,26 +375,6 @@ fn rotate(path: &Path) { let _ = std::fs::rename(path, nth(1)); } -/// Writes the trimmed auxiliary storage a vmapple VM boots, if missing: the image without its -/// first 16 KiB block (docs/system/arm/vmapple.rst in vendor/qemu). -pub fn ensure_aux_trimmed(vm: &Vm) -> Result<()> { - let Some(trimmed) = vm.aux_trimmed() else { - return Ok(()); - }; - if trimmed.exists() { - return Ok(()); - } - let aux = vm.path(&vm.config.vmapple.as_ref().unwrap().aux); - let mut src = std::fs::File::open(&aux).with_context(|| format!("open {}", aux.display()))?; - src.seek(SeekFrom::Start(0x4000))?; - let tmp = trimmed.with_extension("trimmed.tmp"); - let mut dst = std::fs::File::create(&tmp)?; - std::io::copy(&mut src, &mut dst)?; - dst.sync_all()?; - std::fs::rename(&tmp, &trimmed)?; - Ok(()) -} - pub fn context(vm: &Vm, host: Host) -> Result { let qemu = crate::install::qemu_binary(vm.config.profile)?; let backends = crate::install::audio_backends(&qemu); @@ -617,10 +518,8 @@ fn private_dir(d: &Path) -> Result<()> { } /// What a start of a stopped VM does to its settings and OpenCore image first, before [`start`]: -/// an update's change that waited while it ran ([`crate::migrate::at_start`]); for an x86-64 VM -/// on reims-vgpu, its disk's macOS ([`crate::macos::settle`]), which may save -/// the graphics its settings named none of; then a new image ([`crate::opencore::renew`]) for -/// one on another device whose image loads reims-vgpu's guest kexts, as an image made for +/// an update's change that waited while it ran ([`crate::migrate::at_start`]); then a new image +/// ([`crate::opencore::renew`]) for one on another device whose image loads reims-vgpu's guest kexts, as an image made for /// reims-vgpu does after a change of graphics, without them; and for one on reims-vgpu whose /// image holds other builds of them, as one an older reims-ctl made does after an update, with /// this reims-ctl's ([`crate::opencore::holds_other_guest_kexts`]). An image reims-vgpu's kexts @@ -634,12 +533,6 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec { } // An update's change that waited while the VM ran (crate::migrate). crate::migrate::at_start(vm, progress); - match crate::macos::settle(vm) { - Ok(crate::macos::Settled::Kept) => {} - Ok(crate::macos::Settled::Saved(note)) => progress(¬e), - Ok(crate::macos::Settled::Warn(s)) => w.push(s), - Err(e) => w.push(format!("{e:#}")), - } let name = vm.name().to_string(); if crate::opencore::holds_unused_guest_kexts(vm) { let graphics = vm.config.graphics().name(); @@ -685,9 +578,6 @@ pub fn start(vm: &Vm, host: Host) -> Result { ); } preflight(vm, host)?; - if vm.config.profile == Profile::VmappleArm64 { - ensure_aux_trimmed(vm)?; - } let ctx = context(vm, host)?; let inv = qemu::invocation(vm, &ctx)?; let sock = prepare_run(vm)?; @@ -757,7 +647,7 @@ pub fn start(vm: &Vm, host: Host) -> Result { /// Stops the VM: macOS's Control-Option-Command-Power on the USB keyboard ("quit all apps, /// then shut down", which asks about unsaved documents), then, a third of `timeout` in, the -/// machine's power button (ACPI's on q35, a GPIO on vmapple), and at `timeout` a power-off; with +/// machine's power button (ACPI's on q35), and at `timeout` a power-off; with /// `force`, the power-off at once. With no `timeout` it waits until the guest shuts down, the /// button a third of [`DEFAULT_STOP_TIMEOUT`] in, and never powers the VM off: where neither the /// keys nor the button reach the guest, it ends with an error instead. `progress` hears each @@ -994,13 +884,14 @@ mod tests { let config = format!( r#" name = "{name}" - profile = "vmapple-arm64" + profile = "q35-x86_64" cpus = 2 memory_mib = 4096 disk = "{}" - [vmapple] - aux = "aux.img" - ecid = 1 + [q35] + opencore = "opencore.qcow2" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" "#, disk.display() ); @@ -1027,13 +918,14 @@ mod tests { std::fs::create_dir_all(&d).unwrap(); let config = r#" name = "t" - profile = "vmapple-arm64" + profile = "q35-x86_64" cpus = 2 memory_mib = 4096 disk = "disk.img" - [vmapple] - aux = "aux.img" - ecid = 1 + [q35] + opencore = "opencore.qcow2" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" "#; let vm = Vm { dir: d.clone(), @@ -1111,14 +1003,15 @@ mod tests { std::fs::create_dir_all(&d).unwrap(); let config = r#" name = "t" - profile = "vmapple-arm64" + profile = "q35-x86_64" cpus = 2 memory_mib = 4096 disk = "disk.img" stop_timeout_secs = 0 - [vmapple] - aux = "aux.img" - ecid = 1 + [q35] + opencore = "opencore.qcow2" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" "#; let vm = Vm { dir: d.clone(), @@ -1164,46 +1057,6 @@ mod tests { assert!(e.ends_with("a forced stop powers it off"), "{e}"); } - #[test] - fn emptied_entry_lines_count_on_from_what_was_read() { - let d = std::env::temp_dir().join(format!("reims-ctl-emptied-{}", std::process::id())); - std::fs::create_dir_all(&d).unwrap(); - let log = d.join("qemu.log"); - let fault = "reims-vgpu WARN reims_vgpu_core::tasks::local::exec: task 2: exec faulted: \ - resource 3 not found: object 3 has an empty entry\n"; - let append = |s: &str| { - let mut f = std::fs::OpenOptions::new() - .create(true) - .append(true) - .open(&log) - .unwrap(); - f.write_all(s.as_bytes()).unwrap(); - }; - assert_eq!(emptied_entry_lines(&log), 0); - append("reims-ctl 0.1.0 started t\n"); - append(fault); - assert_eq!(emptied_entry_lines(&log), 1); - // A line still being written counts once it ends. - append(&fault[..40]); - assert_eq!(emptied_entry_lines(&log), 1); - append(&fault[40..]); - append(fault); - assert_eq!(emptied_entry_lines(&log), 3); - // The guest's reboot in the same run (as after setting the key from Recovery) counts - // from the device's reset. - append("reims-vgpu INFO reims_vgpu_core::device::lifecycle: device reset\n"); - assert_eq!(emptied_entry_lines(&log), 0); - append(fault); - assert_eq!(emptied_entry_lines(&log), 1); - // A start's rotation leaves a new file, counted from its start. - std::fs::rename(&log, d.join("qemu.1.log")).unwrap(); - append(&"x".repeat(4096)); - append("\n"); - append(fault); - assert_eq!(emptied_entry_lines(&log), 1); - std::fs::remove_dir_all(&d).unwrap(); - } - /// An x86-64 VM with an installer has install steps, which for a disk on NVMe first say to /// move it to SATA. #[test] @@ -1238,10 +1091,9 @@ mod tests { assert_eq!(install_steps(&vm), None); } - /// An x86-64 VM's install steps say to set Metal's error mode on apple-gfx alone: reims-vgpu's - /// own device, the default, needs none. + /// An x86-64 VM's install steps end with ejecting the installer. #[test] - fn install_steps_name_the_error_mode_on_apple_gfx_alone() { + fn install_steps_end_with_ejecting_the_installer() { let config = r#" name = "t" profile = "q35-x86_64" @@ -1254,23 +1106,15 @@ mod tests { firmware_vars = "OVMF_VARS.fd" installer = "installer.img" "#; - let mut vm = Vm { + let vm = Vm { dir: "/vms/t".into(), config: toml::from_str(config).unwrap(), }; - assert!(!needs_error_mode(&vm)); let steps = install_steps(&vm).unwrap(); assert!( steps.ends_with("eject the installer (reims-ctl eject t).") && !steps.contains("error mode"), "{steps}" ); - vm.config.graphics = Some(Graphics::AppleGfx); - assert!(needs_error_mode(&vm)); - let steps = install_steps(&vm).unwrap(); - assert!( - steps.ends_with("(reims-ctl eject t) and set Metal's error mode (README)."), - "{steps}" - ); } } diff --git a/crates/reims-ctl/src/tui.rs b/crates/reims-ctl/src/tui.rs index 85b20c19d..6b2438510 100644 --- a/crates/reims-ctl/src/tui.rs +++ b/crates/reims-ctl/src/tui.rs @@ -15,9 +15,7 @@ use crate::form::{self, Field, Form, opts}; use crate::gpu::GpuInfo; use crate::host::{Host, Os, Profile}; use crate::update::Channel; -use crate::vm::{ - DiskController, Graphics, Registry, Vm, format_mib, parse_resolution, parse_size_mib, -}; +use crate::vm::{DiskController, Graphics, Registry, Vm, format_mib, parse_size_mib}; use crate::{install, logs, opencore, paths, reims_util, runtime, update, usb}; use anyhow::{Context, Result, bail}; use ratatui::DefaultTerminal; @@ -557,10 +555,7 @@ impl App { } match self.overlay.take() { Some(Overlay::Form(kind, mut f)) => match f.handle_key(k) { - form::Event::None => { - display_help(&mut f); - self.overlay = Some(Overlay::Form(kind, f)) - } + form::Event::None => self.overlay = Some(Overlay::Form(kind, f)), form::Event::Cancel => { if let Some((id, _)) = f.busy { self.closed_forms.insert(id, (kind, f)); @@ -1111,12 +1106,11 @@ impl App { title: format!("Make {name} a new OpenCore image?"), body: format!( "reims-util makes it a new OpenCore image for its graphics, {}, with what it \ - carries now, such as ReimsVgpu.kext, which macOS 26 needs for a display wider \ - than 2048 pixels and for GPU-accelerated Chrome on apple-gfx, and on reims-vgpu \ - the macOS drivers of its GPU device that this reims-ctl carries. It presents the \ - same Mac, a {} with serial {}, and the VM keeps its OVMF variables, which hold \ - its boot entries, and its boot selection (e changes it).\n\nThe image it \ - replaces is deleted, with anything else changed in it.", + carries now, and on reims-vgpu the macOS drivers of its GPU device that this \ + reims-ctl carries. It presents the same Mac, a {} with serial {}, and the VM \ + keeps its OVMF variables, which hold its boot entries, and its boot selection \ + (e changes it).\n\nThe image it replaces is deleted, with anything else \ + changed in it.", vm.config.graphics().id(), id.model, id.serial @@ -1440,67 +1434,50 @@ impl App { fn open_create(&mut self) { let Some(profile) = self.host.default_profile() else { - self.say( - &format!("reims-ctl runs no VMs on {} yet", self.host), - Level::Error, - ); + self.say(crate::host::UNSUPPORTED, Level::Error); return; }; - let name = match profile { - Profile::Q35X86_64 => Field::text( + let mut fields = vec![ + Field::text( "name", "Name", "", "Letters, digits, '-', '_' and '.'. Empty names a VM of downloaded macOS after it.", ) .placeholder("the macOS version's, such as tahoe"), - Profile::VmappleArm64 => { - Field::text("name", "Name", "", "Letters, digits, '-', '_' and '.'.") - } - }; - let mut fields = vec![name]; - match profile { - Profile::Q35X86_64 => { - if !matches!(self.macos_versions, Some(Ok(_))) { - self.macos_versions = - Some(reims_util::versions().map_err(|e| format!("{e:#}"))); - } - let (options, version_help) = match &self.macos_versions { - Some(Ok(list)) if !list.is_empty() => ( - list.iter() - .map(|v| (v.slug.clone(), v.name.clone())) - .collect(), - "The macOS to download from Apple. x86-64 macOS 26 is the one we've tested.".to_string(), - ), - Some(Ok(_)) => (opts(&[("", "none")]), "reims-util lists no versions.".to_string()), - Some(Err(e)) => (opts(&[("", "unavailable")]), e.clone()), - None => (opts(&[("", "unavailable")]), String::new()), - }; - let first = options.first().map(|o| o.0.clone()).unwrap_or_default(); - fields.extend([ - Field::choice("source", "macOS from", opts(&[("download", "Download it from Apple"), ("installer", "An installer image of my own"), ("disk", "A disk that has macOS already")]), "download", "reims-ctl downloads the installer, makes the VM's OpenCore image and a new disk, and the VM boots into the installer."), - Field::choice("macos", "macOS version", options, &first, &version_help).show_if("source", &["download"]), - Field::choice("installer_kind", "Installer", opts(&[("online", "Online, about 1 GB"), ("offline", "Offline, 13 to 20 GB")]), "online", "Online is Apple's recovery image: macOS downloads the newest release as it installs. Offline holds one release whole, and installs with no network (macOS 11 and later). Either is kept for the next VM, and a stopped download picks up where it stopped.").show_if("source", &["download"]), - Field::text("release", "Release", "", "Optional: an exact release of that macOS, such as 26.6.2; empty for the newest. reims-util offline-installer list lists them.").placeholder("the newest").show_if("installer_kind", &["offline"]), - Field::path("installer", "Installer image", "", "An installer to boot (Tab completes): a raw image, such as a recovery image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory. Eject it once macOS is installed (e).").show_if("source", &["installer"]), - Field::text("disk_size", "Disk size", "128G", "The new disk's size; it takes only what the guest writes.").show_if("source", &["download", "installer"]), - Field::path("disk_path", "Disk image", "", "A qcow2 or raw image (Tab completes).").show_if("source", &["disk"]), - Field::choice("disk_mode", "Use the disk by", opts(&[("copy", "Copying it (instant where the file system reflinks)"), ("in-place", "Using it in place")]), "copy", "A copy leaves the image as it was; in place, the VM writes the image itself.") - .show_if("source", &["disk"]), - Field::path("opencore", "OpenCore image", "", "Empty makes one for this VM, with OVMF and a Mac identity of its own. Or an OpenCore image of yours to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it, such as the one a disk of macOS booted from, which keeps its Mac's identity.") - .placeholder("made for this VM"), - ]); - } - Profile::VmappleArm64 => { - fields.extend([ - Field::choice("source", "macOS from", opts(&[("ipsw", "Install from an IPSW"), ("import", "Import a Virtualization.framework VM")]), "ipsw", "Install a fresh macOS, or bring a VM made with macosvm or tart."), - Field::path("ipsw", "IPSW", "latest", "An .ipsw restore image (Tab completes), or latest to download the newest this Mac supports (about 15 GB).").show_if("source", &["ipsw"]), - Field::text("disk_size", "Disk size", "64G", "The new disk's size; it takes only what the guest writes.").show_if("source", &["ipsw"]), - Field::path("bundle", "VM directory", "", "macosvm's directory (disk.img, aux.img, vm.json) or tart's (disk.img, nvram.bin, config.json).").show_if("source", &["import"]), - Field::choice("bundle_mode", "Use it by", opts(&[("copy", "Cloning it (instant on the same APFS volume)"), ("in-place", "Using it in place")]), "copy", "A clone leaves the original as it was.").show_if("source", &["import"]), - ]); - } + ]; + if !matches!(self.macos_versions, Some(Ok(_))) { + self.macos_versions = Some(reims_util::versions().map_err(|e| format!("{e:#}"))); } + let (options, version_help) = match &self.macos_versions { + Some(Ok(list)) if !list.is_empty() => ( + list.iter() + .map(|v| (v.slug.clone(), v.name.clone())) + .collect(), + "The macOS to download from Apple. x86-64 macOS 26 is the one we've tested." + .to_string(), + ), + Some(Ok(_)) => ( + opts(&[("", "none")]), + "reims-util lists no versions.".to_string(), + ), + Some(Err(e)) => (opts(&[("", "unavailable")]), e.clone()), + None => (opts(&[("", "unavailable")]), String::new()), + }; + let first = options.first().map(|o| o.0.clone()).unwrap_or_default(); + fields.extend([ + Field::choice("source", "macOS from", opts(&[("download", "Download it from Apple"), ("installer", "An installer image of my own"), ("disk", "A disk that has macOS already")]), "download", "reims-ctl downloads the installer, makes the VM's OpenCore image and a new disk, and the VM boots into the installer."), + Field::choice("macos", "macOS version", options, &first, &version_help).show_if("source", &["download"]), + Field::choice("installer_kind", "Installer", opts(&[("online", "Online, about 1 GB"), ("offline", "Offline, 13 to 20 GB")]), "online", "Online is Apple's recovery image: macOS downloads the newest release as it installs. Offline holds one release whole, and installs with no network (macOS 11 and later). Either is kept for the next VM, and a stopped download picks up where it stopped.").show_if("source", &["download"]), + Field::text("release", "Release", "", "Optional: an exact release of that macOS, such as 26.6.2; empty for the newest. reims-util offline-installer list lists them.").placeholder("the newest").show_if("installer_kind", &["offline"]), + Field::path("installer", "Installer image", "", "An installer to boot (Tab completes): a raw image, such as a recovery image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory. Eject it once macOS is installed (e).").show_if("source", &["installer"]), + Field::text("disk_size", "Disk size", "128G", "The new disk's size; it takes only what the guest writes.").show_if("source", &["download", "installer"]), + Field::path("disk_path", "Disk image", "", "A qcow2 or raw image (Tab completes).").show_if("source", &["disk"]), + Field::choice("disk_mode", "Use the disk by", opts(&[("copy", "Copying it (instant where the file system reflinks)"), ("in-place", "Using it in place")]), "copy", "A copy leaves the image as it was; in place, the VM writes the image itself.") + .show_if("source", &["disk"]), + Field::path("opencore", "OpenCore image", "", "Empty makes one for this VM, with OVMF and a Mac identity of its own. Or an OpenCore image of yours to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it, such as the one a disk of macOS booted from, which keeps its Mac's identity.") + .placeholder("made for this VM"), + ]); fields.extend([ Field::path( "dir", @@ -1528,9 +1505,7 @@ impl App { ), ), ]); - if profile == Profile::Q35X86_64 { - fields.push(graphics_field(Graphics::default_for(profile))); - } + fields.push(graphics_field(Graphics::default())); if profile.gpu_choice(self.host) { fields.push( self.gpu_field(&crate::vm::Gpu::default()) @@ -1538,16 +1513,8 @@ impl App { ); } fields.extend([ - Field::text( - "displays", - "Displays", - "1", - "1 to 8, each in a window of its own.", - ) - .show_if("graphics", APPLE_GFX), Field::text("resolution", "Resolution", "1920x1080", RESOLUTION_HELP) .show_if("graphics", LIBRARY), - Field::toggle("hidpi", "HiDPI", false, HIDPI_HELP).show_if("graphics", APPLE_GFX), Field::toggle( "logs", "Logs", @@ -1562,8 +1529,7 @@ impl App { ) .placeholder("optional"), ]); - let mut form = Form::new("New VM", "create", fields); - display_help(&mut form); + let form = Form::new("New VM", "create", fields); self.overlay = Some(Overlay::Form(FormKind::Create, form)); } @@ -1579,19 +1545,9 @@ impl App { ), Field::text("memory", "Memory", &format_mib(c.memory_mib), "Such as 8G."), ]; - // The displays' and video acceleration's fields are apple-gfx's, and borderless and the - // GPU's the library's devices'; an arm64 VM has no other than apple-gfx. - if c.profile == Profile::Q35X86_64 { - fields.push(graphics_field(c.graphics())); - } + // The resolution's, borderless's and the GPU's fields are reims-vgpu's. + fields.push(graphics_field(c.graphics())); fields.extend([ - Field::text( - "displays", - "Displays", - &c.display.count.to_string(), - "1 to 8, each in a window of its own.", - ) - .show_if("graphics", APPLE_GFX), Field::text( "resolution", "Resolution", @@ -1599,42 +1555,24 @@ impl App { RESOLUTION_HELP, ) .show_if("graphics", LIBRARY), - Field::toggle("hidpi", "HiDPI", c.display.hidpi, HIDPI_HELP) - .show_if("graphics", APPLE_GFX), Field::toggle( "borderless", "Borderless", c.display.borderless, - "Windows without borders that fill their screens.", + "A window without borders that fills its screen.", ) .show_if("graphics", LIBRARY), - Field::text( - "refresh", - "Refresh rate", - &c.display.refresh.map(|r| r.to_string()).unwrap_or_default(), - "Hz offered to the guest; empty for the host screen's.", - ) - .placeholder("the host screen's") - .show_if("graphics", APPLE_GFX), ]); if c.profile.gpu_choice(self.host) { fields.push(self.gpu_field(&c.gpu).show_if("graphics", LIBRARY)); } fields.extend([ - Field::toggle( - "video_acceleration", - "Video acceleration", - c.video_acceleration, - "The guest decodes, encodes and scales video on the host's hardware. Off, it \ - does all of that in software.", - ) - .show_if("graphics", APPLE_GFX), Field::toggle( "audio", "Audio", c.audio.enabled, - "A virtio sound device on the host's sound, with a microphone (on x86-64, also \ - the HDA controller OpenCore's boot chime plays on).", + "A virtio sound device on the host's sound, with a microphone, and the HDA \ + controller OpenCore's boot chime plays on.", ), Field::toggle( "logs", @@ -1742,8 +1680,7 @@ impl App { } else { "" }; - let mut form = Form::new(&format!("Edit {}{note}", c.name), "save", fields); - display_help(&mut form); + let form = Form::new(&format!("Edit {}{note}", c.name), "save", fields); self.overlay = Some(Overlay::Form(FormKind::Edit(c.name.clone()), form)); } @@ -1757,8 +1694,6 @@ impl App { let vm = create::create(spec, host, p)?; let next = if runtime::install_steps(&vm).is_some() { "; its details say how to install macOS" - } else if runtime::needs_error_mode(&vm) { - "; set Metal's error mode in its macOS if it isn't (README)" } else { "" }; @@ -1872,46 +1807,15 @@ impl App { } s.opencore = opt_path("opencore"); } - Some(Profile::VmappleArm64) => { - if f.choice("source") == "ipsw" { - let i = f.text("ipsw"); - if i.is_empty() { - bail!("give an IPSW, or latest"); - } - s.ipsw = Some(if i == "latest" { - i - } else { - paths::absolute(&i).to_string_lossy().into_owned() - }); - s.disk = Some(DiskSource::New { - size_mib: parse_size_mib(&f.text("disk_size")).context("disk size")?, - }); - } else { - s.bundle = Some(opt_path("bundle").context("give the VM's directory")?); - s.bundle_mode = ImportMode::parse(&f.choice("bundle_mode"))?; - } - } - None => bail!("this host runs no VMs"), + None => bail!(crate::host::UNSUPPORTED), } - // The default, as the form offers it, is none given: the VM runs the device for its - // macOS (macos.rs), the default where its macOS runs it. if f.is_shown("graphics") { - let g = Graphics::parse(&f.choice("graphics"))?; - s.graphics = self - .host - .default_profile() - .is_none_or(|p| g != Graphics::default_for(p)) - .then_some(g); + s.graphics = Some(Graphics::parse(&f.choice("graphics"))?); } - // Hidden on reims-vgpu, whose one display follows its window: the defaults, which it - // honors. The resolution is its window's first size there. + // Hidden on VMware SVGA, which opens at the firmware's resolution: the default. if f.is_shown("resolution") { s.display.resolution = f.text("resolution"); } - if f.is_shown("displays") { - s.display.count = f.text("displays").parse().context("displays: a number")?; - s.display.hidpi = f.toggle("hidpi"); - } s.display.check()?; s.logs = f.toggle("logs"); s.ssh_port = ssh_port_field(f)?; @@ -2290,8 +2194,8 @@ fn vm_menu(row: &VmRow, all: bool, host: Host) -> Vec<(VmCommand, &'static str)> /// Whether the VM can be given the host's USB devices: an x86-64 VM on a Linux host. Else why /// not, to say. fn usb_available(host: Host, vm: &Vm) -> Result<(), String> { - if host.os != Os::Linux { - return Err(usb::MAC_HOST.into()); + if host.default_profile().is_none() { + return Err(crate::host::UNSUPPORTED.into()); } if vm.config.q35.is_none() { return Err(format!( @@ -2336,16 +2240,15 @@ fn gpu_from_choice(id: &str, list: &[GpuInfo]) -> crate::vm::Gpu { } } -const RESOLUTION_HELP: &str = "apple-gfx: the guest's first mode, WIDTHxHEIGHT, or host for the \ - host screen's own modes and density. reims-vgpu: the size its window opens at, \ - WIDTHxHEIGHT in the desktop's points, shrunk to fit the screen; the guest takes the \ - window's size in pixels, and follows it as you resize it."; +const RESOLUTION_HELP: &str = "The size the window opens at, WIDTHxHEIGHT in the desktop's \ + points, shrunk to fit the screen; the guest takes the window's size in pixels, and follows \ + it as you resize it. It starts a HiDPI desktop by itself in a window at least 3840 pixels \ + wide."; -/// The graphics field's values that show a field of apple-gfx's alone, and one of the library's. -const APPLE_GFX: &[&str] = &["apple-gfx"]; -const LIBRARY: &[&str] = &["reims-vgpu", "apple-gfx"]; +/// The graphics field's values that show a field of the library's. +const LIBRARY: &[&str] = &["reims-vgpu"]; -/// The graphics choice of an x86-64 VM, at `current`. +/// The graphics choice of a VM, at `current`. fn graphics_field(current: Graphics) -> Field { let options = Graphics::ALL.map(|g| (g.id().to_string(), g.describe().to_string())); Field::choice( @@ -2355,47 +2258,12 @@ fn graphics_field(current: Graphics) -> Field { current.id(), "reims-vgpu is its own GPU device, which macOS drives with the drivers reims-ctl puts in \ the VM's OpenCore image (after a change to it, U makes the image again): one display, \ - in a window whose size the guest follows. apple-gfx is Apple's paravirtualized GPU, \ - with up to 8 displays and the host's video hardware. VMware SVGA is QEMU's: one \ + in a window whose size the guest follows. VMware SVGA is QEMU's: one \ display at the firmware's resolution, with no GPU acceleration (macOS has no driver \ for it), in QEMU's own window.", ) } -const HIDPI_HELP: &str = "Run the mode at twice the density, as a Retina screen does: the desktop \ - looks like half the mode, so a larger mode makes everything smaller (3840x2160 looks like \ - 1920x1080, 3200x1800 like 1600x900, 2560x1440 like 1280x720). Needs a mode at least 1920 \ - pixels wide."; - -/// The resolution's and HiDPI's help, each ending with what the desktop looks like at the -/// values the form holds now. -fn display_help(f: &mut Form) { - if !f.is_shown("resolution") || !f.is_shown("hidpi") { - return; - } - let resolution = f.text("resolution"); - let hidpi = f.toggle("hidpi"); - let looks_like = |hidpi| { - crate::vm::Display { - resolution: resolution.clone(), - hidpi, - ..Default::default() - } - .looks_like() - }; - let now = match (parse_resolution(&resolution), looks_like(true)) { - _ if resolution == "host" && hidpi => { - "host takes the host screen's own density: turn HiDPI off.".to_string() - } - (Ok(_), Some((w, h))) if hidpi => format!("Now {resolution} looks like {w}x{h}."), - (Ok(_), Some((w, h))) => format!("At HiDPI, {resolution} would look like {w}x{h}."), - (Ok((w, _)), None) if hidpi => format!("{w} pixels wide is narrower than 1920."), - _ => String::new(), - }; - f.set_help("resolution", &format!("{RESOLUTION_HELP} {now}")); - f.set_help("hidpi", &format!("{HIDPI_HELP} {now}")); -} - /// The VM's installer as the edit form shows it: its full path, or empty. fn installer_shown(vm: &Vm) -> String { vm.config @@ -2445,36 +2313,19 @@ fn apply_edit(vm: &mut Vm, f: &Form, gpus: Option<&[GpuInfo]>) -> Result<()> { let c = &mut vm.config; c.cpus = f.text("cpus").parse().context("CPU cores: a number")?; c.memory_mib = parse_size_mib(&f.text("memory")).context("memory")?; - // A VM whose settings name no graphics keeps none where the choice stays the default it - // runs, which its first start may decide from its macOS (macos.rs). if f.is_shown("graphics") { - let g = Graphics::parse(&f.choice("graphics"))?; - if c.graphics.is_some() || g != c.graphics() { - c.graphics = Some(g); - } + c.graphics = Some(Graphics::parse(&f.choice("graphics"))?); } if f.is_shown("disk_controller") && let Some(q) = &mut c.q35 { q.disk_controller = DiskController::parse(&f.choice("disk_controller"))?; } - // Hidden on reims-vgpu and VMware SVGA, the displays' settings stay as they were for - // apple-gfx; the resolution, its window's first size, and borderless are reims-vgpu's too. + // Hidden on VMware SVGA, the resolution, the window's first size, and borderless stay as + // they were. if f.is_shown("resolution") { c.display.resolution = f.text("resolution"); - if c.graphics() == Graphics::ReimsVgpu { - crate::vm::check_reims_vgpu_display(None, Some(&c.display.resolution), None, None)?; - } - } - if f.is_shown("displays") { - c.display.count = f.text("displays").parse().context("displays: a number")?; - c.display.hidpi = f.toggle("hidpi"); - let r = f.text("refresh"); - c.display.refresh = if r.is_empty() { - None - } else { - Some(r.parse().context("refresh rate: a number")?) - }; + c.display.check()?; } if f.is_shown("borderless") { c.display.borderless = f.toggle("borderless"); @@ -2485,10 +2336,6 @@ fn apply_edit(vm: &mut Vm, f: &Form, gpus: Option<&[GpuInfo]>) -> Result<()> { c.gpu = gpu_from_choice(&id, gpus.unwrap_or(&[])); } } - // Hidden on reims-vgpu and VMware SVGA, which have no video devices, it stays as it was. - if f.is_shown("video_acceleration") { - c.video_acceleration = f.toggle("video_acceleration"); - } c.audio.enabled = f.toggle("audio"); c.logs.enabled = f.toggle("logs"); if f.is_shown("log_level") && !f.text("log_level").is_empty() { @@ -2608,16 +2455,15 @@ fn copy_to_clipboard(s: &str) -> Option<&'static str> { } const HELP: &str = "\ -reims-ctl runs macOS VMs on QEMU with reims-vgpu: each VM's displays open in windows of their own. -An x86-64 VM runs reims-vgpu's own GPU device on macOS 26.4 and later, and apple-gfx on an older -macOS, unless its settings choose another (e, graphics). +reims-ctl runs x86-64 macOS VMs on QEMU with reims-vgpu: each VM's display opens in a window of +its own. A VM runs reims-vgpu's own GPU device unless its settings choose another (e, graphics). ↑ ↓ / j k choose a VM, or click it Enter open its menu: what can be done with it now, each with its key. A right click on a VM opens its menu too. Hold Ctrl as you press Enter or right click for a menu of everything, whether it can be done now or not (Ctrl-Enter needs a terminal that tells it from Enter, such as kitty, foot or Ghostty on a Mac) - n create a VM. On Linux, choose a macOS version: reims-ctl downloads its + n create a VM. Choose a macOS version: reims-ctl downloads its installer from Apple and makes the VM's OpenCore image and disk, and the VM boots into the installer; its details then say how to install macOS. The form stays open until the VM is made, and shows what failed, to fix and create again; @@ -2626,19 +2472,16 @@ macOS, unless its settings choose another (e, graphics). x stop it: the guest is asked to shut down, and powered off if it has not when its shutdown timeout ends (edit e to change it) K kill it: power it off at once - e edit its settings: CPUs, memory, displays, resolution, HiDPI, borderless, - GPU, video acceleration (the host's hardware video decode, encode and - scaling), audio, network, logs, extra QEMU arguments (they apply at its next - start), and on x86-64 its disk controller (SATA, or NVMe once macOS is - installed), its installer image, its boot selection (OpenCore's picker, which - makes it a new OpenCore image) and graphics: reims-vgpu, its own GPU device, - on one display in a window whose size the guest follows, with the macOS - drivers reims-ctl puts in its OpenCore image (made again on a change); apple-gfx, - Apple's paravirtualized GPU, with up to 8 displays and the host's video - hardware; or QEMU's VMware SVGA, one display with no GPU acceleration, in - QEMU's own window. Displays, resolution, HiDPI, refresh rate and video - acceleration are apple-gfx's - p give it this host's USB devices (Linux): Space gives the selected one to + e edit its settings: CPUs, memory, resolution, borderless, GPU, audio, + network, logs, extra QEMU arguments (they apply at its next start), its disk + controller (SATA, or NVMe once macOS is installed), its installer image, its + boot selection (OpenCore's picker, which makes it a new OpenCore image) and + graphics: reims-vgpu, its own GPU device, on one display in a window whose + size the guest follows, with the macOS drivers reims-ctl puts in its OpenCore + image (made again on a change); or QEMU's VMware SVGA, one display with no GPU + acceleration, in QEMU's own window. Resolution, borderless and GPU are + reims-vgpu's + p give it this host's USB devices: Space gives the selected one to the guest or takes it back, at once while the VM runs; a device you gave it joins the guest when it is plugged in. More in reims-ctl usb --help c show the QEMU command it runs, to write as launch.sh (w) or copy (y): @@ -2651,12 +2494,10 @@ macOS, unless its settings choose another (e, graphics). b write a bug report: its logs, settings, command and this host's details, zipped into your Downloads folder d delete it - U make it a new OpenCore image (x86-64) with the installed reims-util, presenting - the same Mac, for its graphics: on reims-vgpu with the macOS drivers of its GPU - device that this reims-ctl carries, which an image made for apple-gfx or by an - older reims-ctl lacks; on apple-gfx with ReimsVgpu.kext, which an older image - lacks and macOS 26 needs for displays wider than 2048 pixels and GPU-accelerated - Chrome + U make it a new OpenCore image with the installed reims-util, presenting the + same Mac, for its graphics: on reims-vgpu with the macOS drivers of its GPU + device that this reims-ctl carries, which an image an older reims-ctl made + lacks u update reims-ctl and QEMU from your reims-vgpu checkout r reload the list ? this help @@ -3036,8 +2877,8 @@ mod tests { assert!(key_hints().width() <= 80); } - /// A stopped VM's row, x86-64 or arm64, whose files do not exist. - fn vm_row(name: &str, q35: bool) -> VmRow { + /// A stopped VM's row, whose files do not exist. + fn vm_row(name: &str) -> VmRow { let config = format!( r#" name = "{name}" @@ -3052,14 +2893,10 @@ mod tests { "# ); let dir = std::env::temp_dir().join(format!("reims-ctl-tui-{}-{name}", std::process::id())); - let mut vm = Vm { + let vm = Vm { dir: dir.clone(), config: toml::from_str(&config).unwrap(), }; - if !q35 { - vm.config.profile = Profile::VmappleArm64; - vm.config.q35 = None; - } VmRow { name: name.into(), dir, @@ -3120,8 +2957,8 @@ mod tests { }; let every = [ShowCommand, ToggleLogs, ViewLogs, Report]; let stopped = [&[Start, Edit, Usb][..], &every, &[UpdateOpencore, Delete]].concat(); - assert_eq!(commands(&vm_row("t", true)), stopped); - let mut running = vm_row("t", true); + assert_eq!(commands(&vm_row("t")), stopped); + let mut running = vm_row("t"); running.pid = Some(1); let running_menu = [&[View, Stop, PowerOff, Edit, Usb][..], &every].concat(); assert_eq!(commands(&running), running_menu); @@ -3131,27 +2968,24 @@ mod tests { arch: Arch::Aarch64, }; assert!( - !vm_menu(&vm_row("t", true), false, mac) + !vm_menu(&vm_row("t"), false, mac) .iter() .any(|it| it.0 == Usb) ); - // Only x86-64 VMs boot OpenCore. - let arm64 = [&[Start, Edit][..], &every, &[Delete]].concat(); - assert_eq!(commands(&vm_row("t", false)), arm64); let broken = VmRow { vm: Err("parse vm.toml".into()), - ..vm_row("t", true) + ..vm_row("t") }; assert_eq!(commands(&broken), [Delete]); - let mut row = vm_row("t", true); + let mut row = vm_row("t"); assert!(vm_menu(&row, false, LINUX).contains(&(ToggleLogs, "Turn logs on"))); row.vm.as_mut().unwrap().config.logs.enabled = true; assert!(vm_menu(&row, false, LINUX).contains(&(ToggleLogs, "Turn logs off"))); // The menu of everything holds every command, whatever the VM's state. let each = VmCommand::ALL.map(|c| c.0); - for row in [&vm_row("t", true), &running, &vm_row("t", false), &broken] { + for row in [&vm_row("t"), &running, &broken] { let all = vm_menu(row, true, LINUX); assert_eq!(all.iter().map(|it| it.0).collect::>(), each); // Each item is labelled as in the menu of what can be done now. @@ -3170,7 +3004,7 @@ mod tests { let env = crate::testenv::Env::new("tui-usb"); let dir = env.root.join("vms/t"); std::fs::create_dir_all(&dir).unwrap(); - let mut vm = vm_row("t", true).vm.unwrap(); + let mut vm = vm_row("t").vm.unwrap(); vm.dir = dir.clone(); vm.config.usb = vec![crate::vm::UsbDevice { id: "fffe:0001".into(), @@ -3189,7 +3023,7 @@ mod tests { app.reload().unwrap(); press(&mut app, [KeyCode::Char('p')]); assert!(app.overlay.is_none()); - assert!(app.status.as_ref().unwrap().0.contains("Linux host")); + assert_eq!(app.status.as_ref().unwrap().0, crate::host::UNSUPPORTED); let mut app = App::with(LINUX); app.reload().unwrap(); @@ -3234,15 +3068,15 @@ mod tests { assert!(app.overlay.is_none()); } - /// An x86-64 VM's edit form offers its disk's controller as its settings have it, and saves - /// the one picked; an arm64 VM's form has none. + /// A VM's edit form offers its disk's controller as its settings have it, and saves the one + /// picked. #[test] - fn the_edit_form_picks_an_x86_64_vms_disk_controller() { - let mut nvme = vm_row("n", true); + fn the_edit_form_picks_a_vms_disk_controller() { + let mut nvme = vm_row("n"); let q = nvme.vm.as_mut().unwrap().config.q35.as_mut().unwrap(); q.disk_controller = DiskController::Nvme; - let mut app = test_app(vec![vm_row("t", true), vm_row("a", false), nvme]); - app.table.select(Some(2)); + let mut app = test_app(vec![vm_row("t"), nvme]); + app.table.select(Some(1)); app.open_edit(); assert_eq!(form(&app).choice("disk_controller"), "nvme"); app.overlay = None; @@ -3256,92 +3090,26 @@ mod tests { press(&mut app, [KeyCode::Down]); } press(&mut app, [KeyCode::Right]); - let mut vm = vm_row("t", true).vm.unwrap(); + let mut vm = vm_row("t").vm.unwrap(); apply_edit(&mut vm, form(&app), None).unwrap(); assert_eq!(vm.config.q35.unwrap().disk_controller, DiskController::Nvme); - - app.overlay = None; - app.table.select(Some(1)); - app.open_edit(); - assert!(!form(&app).is_shown("disk_controller")); } - /// The edit form turns video acceleration off on apple-gfx, on either kind of VM, and has no - /// such field on reims-vgpu or VMware SVGA, which have no video devices, whose setting stays - /// as it was. + /// A VM's edit form shows the resolution and borderless on reims-vgpu, and hides them on + /// VMware SVGA, whose settings keep them as they were. #[test] - fn the_edit_form_turns_video_acceleration_off() { - let mut apple = vm_row("t", true); - apple.vm.as_mut().unwrap().config.graphics = Some(Graphics::AppleGfx); - let mut svga = vm_row("s", true); - let c = &mut svga.vm.as_mut().unwrap().config; - c.graphics = Some(Graphics::VmwareSvga); - c.video_acceleration = false; - let mut arm64 = vm_row("a", false); - arm64.vm.as_mut().unwrap().config.vmapple = Some(crate::vm::Vmapple { - aux: "aux.img".into(), - ecid: 1234, - }); - let mut reims = vm_row("r", true); - reims.vm.as_mut().unwrap().config.video_acceleration = false; - let mut app = test_app(vec![apple, arm64, svga, reims]); - for row in [0, 1] { - app.overlay = None; - app.table.select(Some(row)); - app.open_edit(); - assert!(form(&app).toggle("video_acceleration")); - for _ in 0..form(&app).fields.len() { - if form(&app).focused_key() == "video_acceleration" { - break; - } - press(&mut app, [KeyCode::Down]); - } - press(&mut app, [KeyCode::Right]); - let mut vm = app.rows[row].vm.as_ref().unwrap().clone(); - apply_edit(&mut vm, form(&app), None).unwrap(); - assert!(!vm.config.video_acceleration); - } - - for row in [2, 3] { - app.overlay = None; - app.table.select(Some(row)); - app.open_edit(); - assert!(!form(&app).is_shown("video_acceleration")); - let mut vm = app.rows[row].vm.as_ref().unwrap().clone(); - vm.config.video_acceleration = true; - apply_edit(&mut vm, form(&app), None).unwrap(); - assert!( - vm.config.video_acceleration, - "a hidden field changes nothing" - ); - } - } - - /// An x86-64 VM whose settings name no graphics is on reims-vgpu, whose edit form shows - /// the resolution and borderless alone of the displays' settings, the rest staying as they - /// were for apple-gfx; saved as it is, it still names none, and choosing apple-gfx shows - /// them, and saves it by name. - #[test] - fn the_edit_form_shows_reims_vgpu_its_display_settings_alone() { - let mut row = vm_row("t", true); + fn the_edit_form_shows_reims_vgpu_its_display_settings() { + let mut row = vm_row("t"); let c = &mut row.vm.as_mut().unwrap().config; - c.display.count = 3; - c.display.hidpi = true; + c.graphics = None; c.display.resolution = "3840x2160".into(); let mut app = test_app(vec![row]); app.open_edit(); assert_eq!(form(&app).choice("graphics"), "reims-vgpu"); - for hidden in ["displays", "hidpi", "refresh"] { - assert!(!form(&app).is_shown(hidden), "{hidden}"); - } assert!(form(&app).is_shown("borderless") && form(&app).is_shown("resolution")); let mut vm = app.rows[0].vm.as_ref().unwrap().clone(); apply_edit(&mut vm, form(&app), None).unwrap(); - assert_eq!(vm.config.graphics, None); - assert_eq!( - (vm.config.display.count, vm.config.display.hidpi), - (3, true) - ); + assert_eq!(vm.config.graphics, Some(Graphics::ReimsVgpu)); for _ in 0..form(&app).fields.len() { if form(&app).focused_key() == "graphics" { break; @@ -3349,16 +3117,20 @@ mod tests { press(&mut app, [KeyCode::Down]); } press(&mut app, [KeyCode::Right]); - assert_eq!(form(&app).choice("graphics"), "apple-gfx"); - assert!(form(&app).is_shown("displays") && form(&app).is_shown("hidpi")); + assert_eq!(form(&app).choice("graphics"), "vmware-svga"); + assert!(!form(&app).is_shown("borderless") && !form(&app).is_shown("resolution")); + vm.config.display.resolution = "1280x720".into(); apply_edit(&mut vm, form(&app), None).unwrap(); - assert_eq!(vm.config.graphics, Some(Graphics::AppleGfx)); - assert_eq!(vm.config.display.count, 3); + assert_eq!(vm.config.graphics, Some(Graphics::VmwareSvga)); + assert_eq!( + vm.config.display.resolution, "1280x720", + "a hidden field changes nothing" + ); } #[test] fn ctrl_with_enter_or_a_right_click_opens_the_menu_of_everything() { - let mut app = test_app(vec![vm_row("alpha", true), vm_row("beta", false)]); + let mut app = test_app(vec![vm_row("alpha"), vm_row("beta")]); app.rows[0].pid = Some(1); let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap(); @@ -3381,21 +3153,28 @@ mod tests { let said = app.status.as_ref().map(|s| s.0.as_str()); assert_eq!(said, Some("alpha is running: stop it first")); - // A Ctrl right click: an arm64 VM's menu holds the OpenCore image's item too. A right - // click without Ctrl, on the same VM, opens its menu of what can be done now. + // A Ctrl right click: a stopped VM's menu holds a running VM's items too. A right click + // without Ctrl, on the same VM, opens its menu of what can be done now. let mut ctrl_click = mouse(MouseEventKind::Down(MouseButton::Right), beta); ctrl_click.modifiers = KeyModifiers::CONTROL; app.mouse(ctrl_click); assert!(matches!(&app.overlay, Some(Overlay::Menu { vm, all: true, .. }) if vm == "beta")); let screen = draw(&mut app); - assert!(find(&screen, app.menu_area, "Make a new OpenCore image…").is_some()); + assert!(find(&screen, app.menu_area, "View screen in terminal").is_some()); app.mouse(mouse(MouseEventKind::Down(MouseButton::Right), beta)); assert!(matches!(&app.overlay, Some(Overlay::Menu { vm, all: false, .. }) if vm == "beta")); + let screen = draw(&mut app); + assert_eq!( + find(&screen, app.menu_area, "View screen in terminal"), + None + ); } #[test] fn a_right_click_or_enter_opens_a_vms_menu_whose_items_do_their_commands() { - let mut app = test_app(vec![vm_row("alpha", true), vm_row("beta", false)]); + let mut app = test_app(vec![vm_row("alpha"), vm_row("beta")]); + // A running VM's menu has no OpenCore image item. + app.rows[1].pid = Some(1); let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap(); let mut draw = |app: &mut App| { @@ -3499,13 +3278,14 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let config = r#" name = "t" - profile = "vmapple-arm64" + profile = "q35-x86_64" cpus = 2 memory_mib = 4096 - disk = "disk.img" - [vmapple] - aux = "aux.img" - ecid = 1 + disk = "disk.qcow2" + [q35] + opencore = "opencore.qcow2" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" "#; std::fs::write(dir.join(crate::vm::CONFIG_FILE), config).unwrap(); let mut reg = Registry::default(); @@ -3521,40 +3301,4 @@ mod tests { assert!(saved.logs.enabled); assert_eq!(saved.memory_mib, 8192); } - - #[test] - fn display_help_says_what_the_desktop_looks_like() { - let now = |resolution: &str, hidpi: bool| { - let mut f = Form::new( - "t", - "save", - vec![ - Field::text("resolution", "Resolution", resolution, RESOLUTION_HELP), - Field::toggle("hidpi", "HiDPI", hidpi, HIDPI_HELP), - ], - ); - display_help(&mut f); - assert_eq!( - f.help("resolution").strip_prefix(RESOLUTION_HELP), - f.help("hidpi").strip_prefix(HIDPI_HELP) - ); - f.help("hidpi")[HIDPI_HELP.len()..].trim().to_string() - }; - assert_eq!(now("3200x1800", true), "Now 3200x1800 looks like 1600x900."); - assert_eq!( - now("3840x2160", false), - "At HiDPI, 3840x2160 would look like 1920x1080." - ); - assert_eq!( - now("1280x800", true), - "1280 pixels wide is narrower than 1920." - ); - assert_eq!(now("1280x800", false), ""); - assert_eq!( - now("host", true), - "host takes the host screen's own density: turn HiDPI off." - ); - assert_eq!(now("host", false), ""); - assert_eq!(now("19x", true), ""); - } } diff --git a/crates/reims-ctl/src/usb.rs b/crates/reims-ctl/src/usb.rs index 16bebab23..5ddcd8707 100644 --- a/crates/reims-ctl/src/usb.rs +++ b/crates/reims-ctl/src/usb.rs @@ -18,7 +18,6 @@ //! - QEMU opens the device's file, `/dev/bus/usb/BBB/DDD`, which only root may write unless a //! udev rule says otherwise: scripts/install-ctl.sh adds one ([`UDEV_RULE`]), which gives USB //! devices other than hubs to the kvm group and to the user at the host's screen. -//! - A macOS host has none ([`MAC_HOST`]). use crate::vm::{UsbDevice, Vm, parse_usb_port}; use crate::{qmp, runtime}; @@ -27,15 +26,6 @@ use serde_json::json; use std::path::{Path, PathBuf}; use std::time::Duration; -/// Why a macOS host passes no USB device through: macOS's IOKit gives a USB device that one of -/// its drivers holds, which is almost every device, to another process only when that process -/// runs as root or holds `com.apple.vm.device-access`, an entitlement Apple grants VM apps with -/// a provisioning profile (libusb's `darwin_detach_kernel_driver`), which no QEMU built here -/// can hold. -pub const MAC_HOST: &str = "USB passthrough needs a Linux host: macOS gives a USB device that \ - one of its drivers holds, almost any device, only to a program running as root or holding an \ - entitlement Apple grants VM apps, and QEMU here can't hold it"; - /// The udev rule scripts/install-ctl.sh writes, and where: USB devices other than hubs to the /// kvm group (over SSH too) and to the user at the host's screen (`uaccess`, which needs a file /// that sorts before systemd's 73-seat-late.rules). Group and others keep the read access diff --git a/crates/reims-ctl/src/view.rs b/crates/reims-ctl/src/view.rs index 29607cf67..a01bb2227 100644 --- a/crates/reims-ctl/src/view.rs +++ b/crates/reims-ctl/src/view.rs @@ -6,10 +6,10 @@ //! Everything goes through the VM's QMP socket, so it works on any running VM: //! - A frame is QMP's `screendump` of the display's console: a PPM, written into a directory of //! the viewer's own under `$XDG_RUNTIME_DIR` (or `/dev/shm`, or the temporary directory), -//! removed when it ends, or by the next viewer where it was killed (`FrameDir`). For -//! it, apple-gfx draws the guest's newest frame into the console's surface -//! (vendor/qemu hw/display/apple-gfx.c, `apple_gfx_fb_update_display`), rendering and reading -//! it back only when the guest has presented a frame since the last. +//! removed when it ends, or by the next viewer where it was killed (`FrameDir`). For it, +//! reims-graphics-pci reads back what its display shows from the library at each of the +//! console's updates (vendor/qemu hw/display/reims-graphics-pci.c, +//! `rvg_graphics_device_read_display`). //! - Input is `input-send-event`: the USB tablet's absolute position and buttons, and the USB //! keyboard's keys (keys.rs). //! @@ -37,7 +37,6 @@ mod term; pub use term::Protocol; -use crate::host::Profile; use crate::qmp::Qmp; use crate::runtime; use crate::vm::Vm; @@ -67,8 +66,6 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; pub struct Options { - /// The display, from 1. - pub display: u32, /// The most frames a second. pub fps: u32, /// How to draw frames; asked of the terminal when `None`. @@ -78,7 +75,6 @@ pub struct Options { impl Default for Options { fn default() -> Options { Options { - display: 1, fps: 15, protocol: None, } @@ -105,7 +101,7 @@ pub fn run(vm: &Vm, opts: &Options) -> Result> { if unsafe { libc::isatty(0) == 0 || libc::isatty(1) == 0 } { bail!("reims-ctl view draws in a terminal: run it in one"); } - let target = Target::for_vm(vm, opts.display)?; + let target = Target::for_vm(vm); let dir = FrameDir::new()?; let file = dir.0.join("frame.ppm"); // A screendump before the terminal is taken, so that what stops one shows plainly. @@ -172,7 +168,6 @@ pub fn run(vm: &Vm, opts: &Options) -> Result> { let mut v = View { name, - display: opts.display, proto, caps, blocks: None, @@ -194,40 +189,21 @@ pub fn run(vm: &Vm, opts: &Options) -> Result> { /// Where QMP finds the display. struct Target { socket: PathBuf, - /// The display device's id and the display's head. vmapple's apple-gfx-mmio has no id; its - /// first display is console 0, QMP's default. - device: Option<(&'static str, u32)>, + /// The display device's id: qemu.rs gives reims-graphics-pci or vmware-svga the id gfx. + device: &'static str, } impl Target { - fn for_vm(vm: &Vm, display: u32) -> Result { - let count = vm.config.display_count(); - if display == 0 || display > count { - bail!( - "{} has {count} display{}: --display takes 1 to {count}", - vm.name(), - if count == 1 { "" } else { "s" } - ); - } - let device = match vm.config.profile { - // qemu.rs gives reims-graphics-pci, apple-gfx-pci or vmware-svga the id gfx. - Profile::Q35X86_64 => Some(("gfx", display - 1)), - Profile::VmappleArm64 if display == 1 => None, - Profile::VmappleArm64 => { - bail!("a vmapple VM's displays past the first have no name QMP can take") - } - }; - Ok(Target { + fn for_vm(vm: &Vm) -> Target { + Target { socket: vm.qmp_socket(), - device, - }) + device: "gfx", + } } fn with_device(&self, mut v: Value) -> Value { - if let Some((d, head)) = self.device { - v["device"] = json!(d); - v["head"] = json!(head); - } + v["device"] = json!(self.device); + v["head"] = json!(0); v } @@ -448,7 +424,6 @@ enum Ui { struct View { name: String, - display: u32, proto: Protocol, caps: term::Caps, /// Half blocks on the screen, where they draw the frame. @@ -623,14 +598,14 @@ fn toolbar(name: &str, latch: Mods) -> (Line<'static>, Vec<(u16, u16, Mods)>) { } fn status(v: &View) -> Line<'static> { - let mut s = format!(" display {}", v.display); + let mut s; if let Some(Shown { frame: (fw, fh), sent: (sw, sh), bytes, }) = v.frame { - s.push_str(&format!(" · {fw}×{fh}")); + s = format!(" {fw}×{fh}"); match v.proto { Protocol::Blocks => s.push_str(" · half blocks"), p => s.push_str(&format!(" · {} {sw}×{sh}", p.name())), @@ -640,7 +615,7 @@ fn status(v: &View) -> Line<'static> { s.push_str(&format!(" · {} KB a frame", bytes.div_ceil(1024))); } } else { - s.push_str(&format!(" · {}", v.proto.name())); + s = format!(" {}", v.proto.name()); } let mut spans = vec![Span::styled(s, BAR)]; if let Some((n, at)) = &v.note diff --git a/crates/reims-ctl/src/view/keys.rs b/crates/reims-ctl/src/view/keys.rs index ea6e50387..3b404d3b1 100644 --- a/crates/reims-ctl/src/view/keys.rs +++ b/crates/reims-ctl/src/view/keys.rs @@ -289,7 +289,7 @@ pub fn point(x: u16, y: u16, pixel: Option<(u16, u16)>, p: Place) -> (f64, f64, } /// The tablet's position at a fraction of the way across and down the display: the pixel there -/// times 0x7fff over the display's size, as apple-gfx's own window sends it. +/// times 0x7fff over the display's size, as QEMU's own windows send it. pub fn abs(fx: f64, fy: f64) -> Ev { let axis = |f: f64| (f.clamp(0.0, 1.0) * 32767.0).round() as u16; Ev::Abs(axis(fx), axis(fy)) diff --git a/crates/reims-ctl/src/vm.rs b/crates/reims-ctl/src/vm.rs index 954d765f7..79eaaf12b 100644 --- a/crates/reims-ctl/src/vm.rs +++ b/crates/reims-ctl/src/vm.rs @@ -30,19 +30,11 @@ pub struct VmConfig { pub stop_timeout_secs: u64, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub extra_args: Vec, - /// The guest's graphics device ([`VmConfig::graphics`]). None, as settings saved before the - /// choice of three have it, is the profile's default ([`Graphics::default_for`]) until the - /// first start that finds macOS on the VM's disk saves the device for that macOS by name - /// (macos.rs): an x86-64 VM saved then, which ran apple-gfx, runs reims-vgpu's own device - /// on macOS 26.4 and later, and stays on apple-gfx on an older macOS. A create saves it by - /// name where it knows the macOS, apple-gfx too. + /// The guest's graphics device ([`VmConfig::graphics`]): None, as settings an older + /// reims-ctl saved may have it, is reims-vgpu's own device, the default. A create saves it + /// by name. #[serde(default, skip_serializing_if = "Option::is_none")] pub graphics: Option, - /// The host's video decode, encode and scaling for the guest, on apple-gfx: the - /// VideoToolbox and M2 scaler devices (`qemu`'s module doc). Off, the VM has neither, and - /// the guest does all three in software. On unless its settings say off. - #[serde(default = "on", skip_serializing_if = "is_on")] - pub video_acceleration: bool, #[serde(default)] pub display: Display, #[serde(default)] @@ -55,8 +47,6 @@ pub struct VmConfig { pub logs: Logs, #[serde(default, skip_serializing_if = "Option::is_none")] pub q35: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub vmapple: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub extra_env: BTreeMap, /// The host's USB devices the guest is given while the VM runs (usb.rs), x86-64 VMs'. @@ -68,14 +58,6 @@ fn default_stop_timeout() -> u64 { DEFAULT_STOP_TIMEOUT.as_secs() } -fn on() -> bool { - true -} - -fn is_on(b: &bool) -> bool { - *b -} - /// How long `stop` waits for the guest by default. pub const DEFAULT_STOP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(90); @@ -111,32 +93,28 @@ impl ImageFormat { } /// The guest's graphics device. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum Graphics { - /// reims-vgpu's own GPU device, QEMU's `reims-graphics-pci`, on an x86-64 VM: the guest - /// drives it with reims-vgpu's kexts, which reims-ctl puts in the VM's OpenCore image - /// ([`crate::prebuilt`]), on one display in a window of the library's. The default on x86-64. + /// reims-vgpu's own GPU device, QEMU's `reims-graphics-pci`: the guest drives it with + /// reims-vgpu's kexts, which reims-ctl puts in the VM's OpenCore image + /// ([`crate::prebuilt`]), on one display in a window of the library's. The default. Settings + /// an older reims-ctl saved for apple-gfx, Apple's paravirtualized GPU, which reims-vgpu no + /// longer has, read as it ([`crate::migrate`] makes their OpenCore image again for it). + #[default] + #[serde(alias = "apple-gfx")] ReimsVgpu, - /// apple-gfx on the library: the device Apple's paravirtualized graphics drivers drive, - /// each display in a window of the library's. The only device an arm64 VM has. - AppleGfx, - /// QEMU's VMware SVGA II, on an x86-64 VM: one display, the firmware's framebuffer, with no - /// GPU acceleration (macOS has no driver for the device), in QEMU's own window. + /// QEMU's VMware SVGA II: one display, the firmware's framebuffer, with no GPU acceleration + /// (macOS has no driver for the device), in QEMU's own window. VmwareSvga, } impl Graphics { - pub const ALL: [Graphics; 3] = [ - Graphics::ReimsVgpu, - Graphics::AppleGfx, - Graphics::VmwareSvga, - ]; + pub const ALL: [Graphics; 2] = [Graphics::ReimsVgpu, Graphics::VmwareSvga]; pub fn id(self) -> &'static str { match self { Graphics::ReimsVgpu => "reims-vgpu", - Graphics::AppleGfx => "apple-gfx", Graphics::VmwareSvga => "vmware-svga", } } @@ -145,7 +123,6 @@ impl Graphics { pub fn name(self) -> &'static str { match self { Graphics::ReimsVgpu => "reims-vgpu", - Graphics::AppleGfx => "apple-gfx", Graphics::VmwareSvga => "VMware SVGA", } } @@ -154,7 +131,6 @@ impl Graphics { pub fn describe(self) -> &'static str { match self { Graphics::ReimsVgpu => "reims-vgpu, its own GPU device and macOS drivers", - Graphics::AppleGfx => "apple-gfx, Apple's paravirtualized GPU", Graphics::VmwareSvga => "VMware SVGA, no GPU acceleration", } } @@ -163,70 +139,15 @@ impl Graphics { Graphics::ALL .into_iter() .find(|g| g.id() == s.trim()) - .with_context(|| format!("graphics is reims-vgpu, apple-gfx or vmware-svga, not {s:?}")) + .with_context(|| format!("graphics is reims-vgpu or vmware-svga, not {s:?}")) } - /// The device a VM of `profile` has where its settings name none, and its macOS is not known - /// yet: reims-vgpu's own on x86-64, apple-gfx, the only one, on arm64. An x86-64 VM on a - /// macOS reims-vgpu's kexts don't load on runs apple-gfx ([`crate::macos::graphics_for`]). - pub fn default_for(profile: Profile) -> Graphics { - match profile { - Profile::Q35X86_64 => Graphics::ReimsVgpu, - Profile::VmappleArm64 => Graphics::AppleGfx, - } - } - - /// Whether the library runs the device, and draws its displays in its windows. + /// Whether the library runs the device, and draws its display in its window. pub fn library(self) -> bool { self != Graphics::VmwareSvga } } -/// Refuses a display setting reims-vgpu's device does not honor, each given for a VM on it: -/// the device has one display, whose window opens at the resolution's size -/// ([`Display::window_size`]) and keeps the size the person gives it, which the guest follows, -/// at the refresh rate of the host screen it is on; the guest starts a HiDPI desktop by itself -/// in a window at least 3840 pixels wide, and offers one in its Displays settings from 2880 (the -/// kext's HiDPI modes, whose pixels halve exactly: the guest is offered the window's pixels -/// rounded down to even). A refresh of 0 is none, as `set` takes it. Settings saved for -/// apple-gfx are not given: they stay for it, and of them reims-vgpu takes the resolution alone, -/// as its window's first size. -pub fn check_reims_vgpu_display( - count: Option, - resolution: Option<&str>, - hidpi: Option, - refresh: Option, -) -> Result<()> { - const APPLE: &str = "choose apple-gfx (--graphics apple-gfx)"; - if let Some(n) = count.filter(|&n| n != 1) { - bail!("reims-vgpu has one display, not {n}: for more, {APPLE}"); - } - if let Some(r) = resolution { - let r = r.trim(); - if r == "host" { - bail!( - "reims-vgpu's display follows its window, which opens at a size you give, such as \ - 2560x1440, not at the host screen's modes: for host, {APPLE}" - ); - } - parse_resolution(r)?; - } - if hidpi == Some(true) { - bail!( - "on reims-vgpu the guest picks HiDPI itself (it starts HiDPI in a window at least \ - 3840 pixels wide, and offers it in its Displays settings from 2880): turn HiDPI \ - off, or {APPLE}" - ); - } - if let Some(r) = refresh.filter(|&r| r != 0) { - bail!( - "reims-vgpu's display runs at the host screen's refresh rate, not {r} Hz: leave the \ - refresh rate empty, or {APPLE}" - ); - } - Ok(()) -} - /// The controller an x86-64 VM's system disk is on, which its settings choose. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] @@ -270,96 +191,51 @@ impl DiskController { } } +/// reims-vgpu's one display: its window opens at the resolution's size +/// ([`Display::window_size`]) and keeps the size the person gives it, which the guest follows, at +/// the refresh rate of the host screen it is on. The guest starts a HiDPI desktop by itself in a +/// window at least 3840 pixels wide, and offers one in its Displays settings from 2880 (the +/// kext's HiDPI modes, whose pixels halve exactly: the guest is offered the window's pixels +/// rounded down to even). Settings an older reims-ctl saved for apple-gfx's displays (their +/// count, HiDPI and refresh rate) are read past, and left out of the next save. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Display { - /// The guest's display ports, 1 to 8, each with a window of its own. - pub count: u32, - /// The mode the guest runs first, `x`, or `host` for the host screen's own - /// modes at its density. + /// The size the window opens at, `x`. pub resolution: String, - /// Whether the guest is told a density at which it runs a HiDPI desktop at the mode's pixels - /// (3840x2160 then looks like 1920x1080). - pub hidpi: bool, - /// Borderless windows that fill their screens. + /// A borderless window that fills its screen. pub borderless: bool, - /// The refresh rate of the modes offered to the guest; the host screen's by default. - #[serde(skip_serializing_if = "Option::is_none")] - pub refresh: Option, } impl Default for Display { fn default() -> Display { Display { - count: 1, resolution: "1920x1080".into(), - hidpi: false, borderless: false, - refresh: None, } } } impl Display { - /// The `resolution` property apple-gfx takes, checked as QEMU checks it. - pub fn qemu_resolution(&self) -> Result { - let r = self.resolution.trim(); - if r == "host" { - if self.hidpi { - bail!("resolution host takes the host screen's own density: turn HiDPI off"); - } - return Ok("host".into()); - } - let (w, h) = parse_resolution(r)?; - if !self.hidpi { - return Ok(format!("{w}x{h}")); - } - match hidpi_ppi(w) { - Some(ppi) => Ok(format!("{w}x{h}@{ppi}")), - None => bail!( - "a HiDPI desktop needs a mode at least 1920 pixels wide (it looks half that size), \ - not {w}x{h}" - ), - } - } - /// The size reims-vgpu's window opens at, the resolution's, in the host's points (a guest /// point per host point), shrunk to fit the screen, which its guest takes in pixels and /// follows: measured on a Linux desktop at 2.1x, 1280x720 opened 1280x720 points and the - /// guest ran 2688x1512. None for the device's own, 1920x1080, and for `host`, which names no - /// size. + /// guest ran 2688x1512. None for the device's own, 1920x1080. pub fn window_size(&self) -> Option<(u32, u32)> { parse_resolution(self.resolution.trim()) .ok() .filter(|&size| size != (1920, 1080)) } - /// The size a HiDPI desktop looks like, half the mode's pixels, where it runs one. - pub fn looks_like(&self) -> Option<(u32, u32)> { - if !self.hidpi { - return None; - } - let (w, h) = parse_resolution(self.resolution.trim()).ok()?; - hidpi_ppi(w).map(|_| (w / 2, h / 2)) - } - pub fn check(&self) -> Result<()> { - if !(1..=8).contains(&self.count) { - bail!("displays must be 1 to 8, not {}", self.count); - } - if let Some(r) = self.refresh - && !(1..=1000).contains(&r) - { - bail!("refresh must be 1 to 1000 Hz, not {r}"); - } - self.qemu_resolution().map(|_| ()) + parse_resolution(self.resolution.trim()).map(|_| ()) } } pub fn parse_resolution(s: &str) -> Result<(u32, u32)> { let (w, h) = s .split_once(['x', 'X']) - .with_context(|| format!("resolution must be x or host, not {s:?}"))?; + .with_context(|| format!("resolution must be x, not {s:?}"))?; let w: u32 = w .trim() .parse() @@ -374,44 +250,6 @@ pub fn parse_resolution(s: &str) -> Result<(u32, u32)> { Ok((w, h)) } -/// The millimetres a guest is told for `width` pixels at `ppi`, as apple-gfx computes them -/// (`apple_gfx_guest_millimeters`): in single precision, rounded. -fn guest_millimeters(width: u32, ppi: u32) -> u64 { - let mm = width as f32 / (ppi as f64 / 25.46) as f32; - (mm as f64 + 0.5) as u64 -} - -/// The whole centimetres the guest reads them as, rounded up. -fn guest_centimeters(width: u32, ppi: u32) -> u64 { - guest_millimeters(width, ppi).div_ceil(10) -} - -/// apple-gfx's `apple_gfx_guest_scale_unknown`: whether the scale a macOS guest runs a mode at -/// is not known from the density it is told, which QEMU refuses. -fn guest_scale_unknown(width: u32, ppi: u32) -> bool { - let cm = guest_centimeters(width, ppi); - let w = width as u64; - if cm == 0 || guest_millimeters(width, ppi) > u16::MAX as u64 { - return true; - } - if w * 35 >= 2021 * cm { - return width < 1920 || cm < 29; - } - width > 3811 || w * 66 > 3811 * cm -} - -/// A density at which the guest runs `width` HiDPI: about 29.5 cm across, so it reads 30 cm and -/// at least 146.667 ppi, where apple-gfx knows the scale (widths of 1920 and more). -pub fn hidpi_ppi(width: u32) -> Option { - if width < 1920 { - return None; - } - let ppi = (width as f64 * 25.46 / 295.0).round() as u32; - let cm = guest_centimeters(width, ppi); - let hidpi = width as u64 * 35 >= 2021 * cm; - (hidpi && !guest_scale_unknown(width, ppi)).then_some(ppi) -} - #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Gpu { @@ -430,7 +268,7 @@ pub struct Gpu { #[serde(default)] pub struct Audio { pub enabled: bool, - /// QEMU's audio backend (`coreaudio`, `pipewire`, `pa`, `alsa`, `none`); the host's best + /// QEMU's audio backend (`pipewire`, `pa`, `alsa`, `none`); the host's best /// by default. #[serde(skip_serializing_if = "Option::is_none")] pub backend: Option, @@ -618,15 +456,6 @@ pub fn parse_usb_port(p: &str) -> Option<(u32, &str)> { Some((bus.parse().ok()?, ports)) } -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct Vmapple { - /// The auxiliary storage Virtualization.framework made, relative to the VM's directory. QEMU - /// boots a copy without its first 16 KiB block (`aux.img.trimmed`). - pub aux: PathBuf, - /// The machine identifier's ECID, which `-M vmapple,uuid=` takes. - pub ecid: u64, -} - impl VmConfig { pub fn check(&self) -> Result<()> { check_name(&self.name)?; @@ -642,40 +471,15 @@ impl VmConfig { } check_mac(&self.network.mac)?; self.check_usb()?; - if self.profile != Profile::Q35X86_64 { - match self.graphics() { - Graphics::AppleGfx => {} - Graphics::ReimsVgpu => bail!( - "{}: reims-vgpu's own GPU device is for x86-64 VMs: an arm64 macOS guest \ - drives only apple-gfx (reims-ctl set {} --graphics apple-gfx)", - self.name, - self.name - ), - Graphics::VmwareSvga => bail!( - "{}: VMware SVGA is for x86-64 VMs: an arm64 macOS guest drives only apple-gfx", - self.name - ), - } - } - match self.profile { - Profile::Q35X86_64 if self.q35.is_none() => bail!("{}: no [q35] settings", self.name), - Profile::VmappleArm64 if self.vmapple.is_none() => { - bail!("{}: no [vmapple] settings", self.name) - } - _ => Ok(()), + if self.q35.is_none() { + bail!("{}: no [q35] settings", self.name); } + Ok(()) } - /// Refuses USB devices the VM cannot be given: on an arm64 VM, whose host is a Mac, any - /// ([`crate::usb::MAC_HOST`]); more than [`USB_DEVICES_MAX`]; one named twice, which QEMU - /// would refuse by its id; and an ID or port that names no device. + /// Refuses USB devices the VM cannot be given: more than [`USB_DEVICES_MAX`]; one named + /// twice, which QEMU would refuse by its id; and an ID or port that names no device. fn check_usb(&self) -> Result<()> { - if self.usb.is_empty() { - return Ok(()); - } - if self.profile != Profile::Q35X86_64 { - bail!("{}: {}", self.name, crate::usb::MAC_HOST); - } if self.usb.len() > USB_DEVICES_MAX { bail!( "{}: a VM takes {USB_DEVICES_MAX} USB devices at most, not {}", @@ -703,30 +507,18 @@ impl VmConfig { stop_timeout(self.stop_timeout_secs) } - /// The guest's graphics device: the settings', else the profile's default. + /// The guest's graphics device: the settings', else reims-vgpu's own. pub fn graphics(&self) -> Graphics { - self.graphics - .unwrap_or_else(|| Graphics::default_for(self.profile)) - } - - /// The displays the guest has: apple-gfx's, or reims-vgpu's or VMware SVGA's one. - pub fn display_count(&self) -> u32 { - match self.graphics() { - Graphics::AppleGfx => self.display.count, - Graphics::ReimsVgpu | Graphics::VmwareSvga => 1, - } + self.graphics.unwrap_or_default() } } impl VmConfig { /// What in these settings the VM's guest does not work with, each a sentence to show the - /// user; empty for an arm64 VM. For an x86-64 VM: audio off, without which Safari's - /// streaming players fail (docs/qemu.md, "x86-64 macOS guests: audio"). + /// user: audio off, without which Safari's streaming players fail (docs/qemu.md, "x86-64 + /// macOS guests: audio"). pub fn incompatibilities(&self) -> Vec { let mut w = Vec::new(); - if self.profile != Profile::Q35X86_64 { - return w; - } if !self.audio.enabled { w.push(format!( "Audio is off, and without an audio device an x86-64 macOS guest's Safari can't \ @@ -910,17 +702,13 @@ impl Vm { } /// The files the VM runs on, wherever they are: its disk, and its OpenCore image, firmware - /// and installer, or its auxiliary storage and the trimmed copy QEMU boots. + /// and installer. pub fn files(&self) -> Vec { let mut v = vec![self.disk()]; if let Some(q) = &self.config.q35 { v.extend([&q.opencore, &q.firmware_code, &q.firmware_vars].map(|p| self.path(p))); v.extend(q.installer.as_deref().map(|p| self.path(p))); } - if let Some(a) = &self.config.vmapple { - v.push(self.path(&a.aux)); - v.extend(self.aux_trimmed()); - } v } @@ -933,15 +721,6 @@ impl Vm { &paths::short_runtime_dir(), ) } - - /// The trimmed auxiliary storage QEMU boots (vmapple). - pub fn aux_trimmed(&self) -> Option { - let v = self.config.vmapple.as_ref()?; - let aux = self.path(&v.aux); - let mut name = aux.file_name()?.to_os_string(); - name.push(".trimmed"); - Some(aux.with_file_name(name)) - } } /// The pid file QEMU writes in a VM's directory while it runs. @@ -1046,63 +825,22 @@ impl Registry { mod tests { use super::*; - #[test] - fn hidpi_densities_are_ones_qemu_accepts() { - for w in [1920, 2048, 2560, 2880, 3024, 3456, 3840, 5120, 6016] { - let ppi = hidpi_ppi(w).unwrap_or_else(|| panic!("no density for {w}")); - assert!(!guest_scale_unknown(w, ppi), "{w}@{ppi}"); - let cm = guest_centimeters(w, ppi); - assert!( - w as f64 / cm as f64 * 2.54 >= 146.667, - "{w}@{ppi} is not HiDPI ({cm} cm)" - ); - } - assert_eq!(hidpi_ppi(1280), None); - } - - #[test] - fn densities_match_apple_gfx_examples() { - // docs/qemu.md: 2560x1600@200 runs HiDPI; @148 reads 44 cm, @146 45 cm. - assert_eq!(guest_centimeters(2560, 148), 44); - assert_eq!(guest_centimeters(2560, 146), 45); - assert!(!guest_scale_unknown(2560, 200)); - } - - #[test] - fn resolution_property() { - let mut d = Display::default(); - assert_eq!(d.qemu_resolution().unwrap(), "1920x1080"); - d.hidpi = true; - d.resolution = "3840x2160".into(); - assert!(d.qemu_resolution().unwrap().starts_with("3840x2160@")); - assert_eq!(d.looks_like(), Some((1920, 1080))); - d.resolution = "1280x800".into(); - assert!(d.qemu_resolution().is_err()); - assert_eq!(d.looks_like(), None); - d.resolution = "host".into(); - assert!(d.qemu_resolution().is_err()); - d.hidpi = false; - assert_eq!(d.qemu_resolution().unwrap(), "host"); - d.resolution = "19x".into(); - assert!(d.qemu_resolution().is_err()); - } - - /// reims-vgpu's window opens at the resolution's size, HiDPI or not; the device's own - /// 1920x1080 and `host` name none. + /// A resolution is the window's first size, `x`; reims-vgpu's window opens + /// at it, and the device's own 1920x1080 names none. #[test] fn reims_vgpu_s_window_opens_at_the_resolution_s_size() { - let d = |resolution: &str, hidpi| { - Display { - resolution: resolution.into(), - hidpi, - ..Default::default() - } - .window_size() + let d = |resolution: &str| Display { + resolution: resolution.into(), + ..Default::default() }; - assert_eq!(d("2560x1440", false), Some((2560, 1440))); - assert_eq!(d("3840x2160", true), Some((3840, 2160))); - assert_eq!(d("1920x1080", false), None); - assert_eq!(d("host", false), None); + assert_eq!(d("2560x1440").window_size(), Some((2560, 1440))); + assert_eq!(d(" 3840x2160").window_size(), Some((3840, 2160))); + assert_eq!(d("1920x1080").window_size(), None); + assert!(d("2560x1600").check().is_ok()); + for bad in ["host", "2560", "19x", "0x1080", "70000x10"] { + assert!(d(bad).check().is_err(), "{bad}"); + assert_eq!(d(bad).window_size(), None, "{bad}"); + } } #[test] @@ -1241,7 +979,6 @@ mod tests { stop_timeout_secs: 90, extra_args: vec!["-boot".into(), "menu=on".into()], graphics: None, - video_acceleration: true, display: Display::default(), gpu: Gpu { driver_file: Some("/usr/share/vulkan/icd.d/nvidia_icd.json".into()), @@ -1266,7 +1003,6 @@ mod tests { disk_controller: DiskController::Nvme, disk_port: 3, }), - vmapple: None, extra_env: BTreeMap::from([("A".into(), "b".into())]), usb: vec![], } @@ -1341,21 +1077,6 @@ mod tests { } assert_eq!(parse_usb_port("3-2.1"), Some((3, "2.1"))); assert_eq!(parse_usb_port("1-10"), Some((1, "10"))); - // An arm64 VM, which runs on a Mac, takes none. - c.usb = vec![u("1050:0407", None)]; - c.profile = Profile::VmappleArm64; - c.q35 = None; - c.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1, - }); - assert!( - refused(&c).contains("needs a Linux host"), - "{}", - refused(&c) - ); - c.usb.clear(); - assert!(c.check().is_ok()); } #[test] @@ -1374,93 +1095,29 @@ mod tests { } } - /// A VM whose settings name no graphics, as every VM on apple-gfx saved before there were - /// three had them, runs its profile's default: reims-vgpu's own device on x86-64, apple-gfx - /// on arm64. One on apple-gfx is saved by name, so it stays there. + /// A VM whose settings name no graphics runs reims-vgpu's own device. Settings an older + /// reims-ctl saved for apple-gfx read as reims-vgpu, and save naming it; the names parse + /// back to their devices. #[test] - fn a_vm_naming_no_graphics_runs_its_profiles_default() { + fn a_vm_naming_no_graphics_or_apple_gfx_runs_reims_vgpu() { let mut c = x86_64_config(); let text = toml::to_string_pretty(&c).unwrap(); assert!(!text.contains("graphics"), "{text}"); let loaded = toml::from_str::(&text).unwrap(); assert_eq!(loaded.graphics(), Graphics::ReimsVgpu); assert_eq!(toml::to_string_pretty(&loaded).unwrap(), text); - c.graphics = Some(Graphics::AppleGfx); - let apple = toml::to_string_pretty(&c).unwrap(); - assert!(apple.contains("graphics = \"apple-gfx\"\n"), "{apple}"); - assert_eq!( - toml::from_str::(&apple).unwrap().graphics(), - Graphics::AppleGfx - ); - c.graphics = None; - c.profile = Profile::VmappleArm64; - assert_eq!(c.graphics(), Graphics::AppleGfx); - assert_eq!( - Graphics::default_for(Profile::Q35X86_64), - Graphics::ReimsVgpu - ); - } - - /// reims-vgpu's own device is an x86-64 VM's: an arm64 VM given it is refused, saying what - /// it runs instead. - #[test] - fn reims_vgpu_is_for_x86_64_vms() { - let mut c = x86_64_config(); c.graphics = Some(Graphics::ReimsVgpu); - assert!(c.check().is_ok()); - c.profile = Profile::VmappleArm64; - c.q35 = None; - c.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1, - }); - let e = format!("{:#}", c.check().unwrap_err()); - assert!(e.contains("--graphics apple-gfx"), "{e}"); - c.graphics = None; - assert!(c.check().is_ok()); - assert_eq!(c.display_count(), 1); - c.display.count = 2; - assert_eq!(c.display_count(), 2); + let ours = toml::to_string_pretty(&c).unwrap(); + let apple = ours.replace("graphics = \"reims-vgpu\"", "graphics = \"apple-gfx\""); + assert_ne!(apple, ours); + let loaded = toml::from_str::(&apple).unwrap(); + assert_eq!(loaded.graphics, Some(Graphics::ReimsVgpu)); + assert_eq!(toml::to_string_pretty(&loaded).unwrap(), ours); for g in Graphics::ALL { assert_eq!(Graphics::parse(g.id()).unwrap(), g); } - assert!(Graphics::parse("vga").is_err()); - } - - /// reims-vgpu takes the display settings its device honors, given for it, and refuses the - /// rest, saying what to do instead. - #[test] - fn reims_vgpu_refuses_display_settings_it_does_not_honor() { - assert!(check_reims_vgpu_display(None, None, None, None).is_ok()); - assert!( - check_reims_vgpu_display(Some(1), Some(" 1920x1080"), Some(false), Some(0)).is_ok() - ); - // Its window opens at the size given. - assert!(check_reims_vgpu_display(None, Some("2560x1600"), None, None).is_ok()); - assert!(check_reims_vgpu_display(None, Some("2560"), None, None).is_err()); - for (refused, says) in [ - ( - check_reims_vgpu_display(Some(2), None, None, None), - "one display", - ), - ( - check_reims_vgpu_display(None, Some("host"), None, None), - "for host", - ), - ( - check_reims_vgpu_display(None, None, Some(true), None), - "2880", - ), - ( - check_reims_vgpu_display(None, None, None, Some(120)), - "not 120 Hz", - ), - ] { - let e = format!("{:#}", refused.unwrap_err()); - assert!( - e.contains(says) && e.contains("--graphics apple-gfx"), - "{e}" - ); + for gone in ["apple-gfx", "vga"] { + assert!(Graphics::parse(gone).is_err(), "{gone}"); } } @@ -1485,20 +1142,20 @@ mod tests { } } - /// A VM whose settings don't name video acceleration has it on, and saves as it did before - /// the switch existed; one with it off saves it off. + /// What an older reims-ctl saved for apple-gfx alone (video acceleration, the displays' + /// count, HiDPI and refresh rate) is read past, and left out of the next save. #[test] - fn video_acceleration_is_on_unless_the_settings_say_off() { - let mut c = x86_64_config(); + fn apple_gfx_s_settings_are_read_past() { + let c = x86_64_config(); let text = toml::to_string_pretty(&c).unwrap(); - assert!(!text.contains("video_acceleration"), "{text}"); - let loaded = toml::from_str::(&text).unwrap(); - assert!(loaded.video_acceleration); + let old = text.replace( + "[display]\n", + "video_acceleration = false\n\n[display]\ncount = 2\nhidpi = true\nrefresh = 120\n", + ); + assert_ne!(old, text); + let loaded = toml::from_str::(&old).unwrap(); + assert_eq!(loaded, c); assert_eq!(toml::to_string_pretty(&loaded).unwrap(), text); - c.video_acceleration = false; - let off = toml::to_string_pretty(&c).unwrap(); - assert!(off.contains("video_acceleration = false\n"), "{off}"); - assert_eq!(toml::from_str::(&off).unwrap(), c); } /// A VM an earlier create saved with an SSH port of 0 has no forward, as `set --ssh-port 0` @@ -1518,30 +1175,22 @@ mod tests { assert_eq!(toml::from_str::(&none).unwrap(), c); } + /// A VM is an x86-64 one, with its [q35] settings; VMware SVGA is one of its devices. #[test] - fn vmware_svga_is_an_x86_64_vms_one_display() { + fn a_vm_has_its_q35_settings() { let mut c = x86_64_config(); - c.display.count = 2; c.graphics = Some(Graphics::parse("vmware-svga").unwrap()); assert!(c.check().is_ok()); - assert_eq!(c.display_count(), 1); - c.profile = Profile::VmappleArm64; c.q35 = None; - c.vmapple = Some(Vmapple { - aux: "aux.img".into(), - ecid: 1, - }); - assert!(c.check().is_err()); - c.graphics = Some(Graphics::AppleGfx); - assert!(c.check().is_ok()); - assert_eq!(c.display_count(), 2); + let e = format!("{:#}", c.check().unwrap_err()); + assert!(e.contains("no [q35] settings"), "{e}"); } #[test] fn incompatibilities_are_an_x86_64_vms_silence() { let mut c = x86_64_config(); assert!(c.incompatibilities().is_empty()); - // Wide displays are the OpenCore image's ReimsVgpu.kext's (runtime::warnings). + // A wide window is none. c.display.resolution = "2560x1600".into(); assert!(c.incompatibilities().is_empty()); c.audio.enabled = false; @@ -1551,7 +1200,5 @@ mod tests { w[0].contains("reims-ctl set t --audio-backend none"), "{w:?}" ); - c.profile = Profile::VmappleArm64; - assert!(c.incompatibilities().is_empty()); } } diff --git a/crates/reims-ctl/src/vz.rs b/crates/reims-ctl/src/vz.rs deleted file mode 100644 index 567c4752d..000000000 --- a/crates/reims-ctl/src/vz.rs +++ /dev/null @@ -1,401 +0,0 @@ -//! Installing macOS from an IPSW into a new arm64 VM, through Virtualization.framework, the only -//! thing that restores one. The result is what macosvm makes and QEMU's vmapple boots: a raw -//! `disk.img`, the auxiliary storage `aux.img`, and a machine identifier, whose ECID -//! `-M vmapple,uuid=` takes (the identifier's and the hardware model's data are kept beside them, -//! in `machine-identifier.bin` and `hardware-model.bin`). -//! -//! The install runs in a child process (`reims-ctl __vz-install`): Virtualization.framework uses -//! a virtual machine on its queue, the main one here, which the child's main thread serves by -//! running the main run loop, whatever the parent's threads are doing (the interface runs -//! installs on a thread of its own). The child prints `progress ` lines and, at the -//! end, `ecid `. It needs the `com.apple.security.virtualization` entitlement, which -//! scripts/install-ctl.sh signs reims-ctl with. - -use anyhow::{Context, Result, bail}; -use std::io::BufRead; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; - -/// Whether this binary carries the virtualization entitlement. -pub fn entitled() -> bool { - if !cfg!(target_os = "macos") { - return false; - } - let Ok(exe) = std::env::current_exe() else { - return false; - }; - Command::new("codesign") - .args(["-d", "--entitlements", "-", "--xml"]) - .arg(&exe) - .stderr(Stdio::null()) - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).contains("com.apple.security.virtualization")) - .unwrap_or(false) -} - -/// Installs `ipsw` (a path, or `latest`) into `dir`, making a disk of `disk_mib`; returns the -/// machine identifier's ECID. -pub fn install( - ipsw: &str, - dir: &Path, - disk_mib: u64, - cpus: u32, - memory_mib: u64, - progress: &mut dyn FnMut(&str), -) -> Result { - if !cfg!(target_os = "macos") { - bail!("an IPSW installs only on macOS"); - } - if !entitled() { - bail!( - "installing from an IPSW needs reims-ctl signed with the com.apple.security.virtualization \ - entitlement: rerun scripts/install-ctl.sh (a plain cargo install leaves it out)" - ); - } - let exe = std::env::current_exe()?; - let ipsw = if ipsw == "latest" { - progress("asking Apple for the newest macOS this Mac supports"); - let out = Command::new(&exe).arg("__vz-latest").output()?; - let url = String::from_utf8_lossy(&out.stdout).trim().to_string(); - if !out.status.success() || !url.starts_with("http") { - bail!( - "could not find the latest IPSW: {}", - String::from_utf8_lossy(&out.stderr).trim() - ); - } - download(&url, progress)? - } else { - PathBuf::from(ipsw) - }; - if !ipsw.is_file() { - bail!("{} does not exist", ipsw.display()); - } - progress("loading the IPSW"); - let mut child = Command::new(&exe) - .arg("__vz-install") - .arg("--ipsw") - .arg(&ipsw) - .arg("--dir") - .arg(dir) - .args([ - "--disk-mib", - &disk_mib.to_string(), - "--cpus", - &cpus.to_string(), - "--memory-mib", - &memory_mib.to_string(), - ]) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn()?; - let stderr = child.stderr.take().unwrap(); - let err_thread = std::thread::spawn(move || { - let mut s = String::new(); - use std::io::Read; - let _ = std::io::BufReader::new(stderr).read_to_string(&mut s); - s - }); - let mut ecid = None; - let mut last = -1i64; - for line in std::io::BufReader::new(child.stdout.take().unwrap()).lines() { - let line = line?; - if let Some(f) = line.strip_prefix("progress ") { - let pct = (f.parse::().unwrap_or(0.0) * 100.0) as i64; - if pct != last { - last = pct; - progress(&format!("installing macOS: {pct}%")); - } - } else if let Some(e) = line.strip_prefix("ecid ") { - ecid = e.trim().parse().ok(); - } else if let Some(m) = line.strip_prefix("note ") { - progress(m); - } - } - let status = child.wait()?; - let err = err_thread.join().unwrap_or_default(); - match (status.success(), ecid) { - (true, Some(e)) => Ok(e), - _ => bail!("the install failed: {}", err.trim()), - } -} - -/// Downloads `url` into the data directory's `ipsw/`, resuming a partial download; returns the -/// file. -fn download(url: &str, progress: &mut dyn FnMut(&str)) -> Result { - let name = url - .rsplit('/') - .next() - .filter(|n| n.ends_with(".ipsw")) - .unwrap_or("latest.ipsw"); - let dir = crate::paths::data_dir().join("ipsw"); - std::fs::create_dir_all(&dir)?; - let file = dir.join(name); - if file.is_file() { - progress(&format!( - "using the IPSW downloaded before, {}", - crate::paths::tilde(&file) - )); - return Ok(file); - } - let part = dir.join(format!("{name}.part")); - let total: u64 = Command::new("curl") - .args(["-sIL", url]) - .output() - .ok() - .and_then(|o| { - String::from_utf8_lossy(&o.stdout) - .lines() - .filter_map(|l| { - l.to_ascii_lowercase() - .strip_prefix("content-length:") - .map(|v| v.trim().to_string()) - }) - .next_back() - .and_then(|v| v.parse().ok()) - }) - .unwrap_or(0); - let mut child = Command::new("curl") - .args(["-fsSL", "--retry", "3", "-C", "-", "-o"]) - .arg(&part) - .arg(url) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .spawn() - .context("run curl")?; - loop { - if let Some(st) = child.try_wait()? { - if !st.success() { - let mut e = String::new(); - use std::io::Read; - let _ = child.stderr.take().map(|mut s| s.read_to_string(&mut e)); - bail!("the download failed: {}", e.trim()); - } - break; - } - let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0); - if total > 0 { - progress(&format!( - "downloading {name}: {:.0}% of {:.1} GB", - have as f64 * 100.0 / total as f64, - total as f64 / 1e9 - )); - } else { - progress(&format!("downloading {name}: {:.1} GB", have as f64 / 1e9)); - } - std::thread::sleep(std::time::Duration::from_secs(1)); - } - std::fs::rename(&part, &file)?; - Ok(file) -} - -#[cfg(target_os = "macos")] -mod imp { - use anyhow::{Context, Result, bail}; - use block2::RcBlock; - use objc2::AllocAnyThread; - use objc2::rc::Retained; - use objc2_foundation::{NSArray, NSDate, NSError, NSRunLoop, NSString, NSURL}; - use objc2_virtualization::*; - use std::path::Path; - use std::sync::{Arc, Mutex}; - - fn url(p: &Path) -> Retained { - NSURL::fileURLWithPath(&NSString::from_str(&p.to_string_lossy())) - } - - fn describe(e: *mut NSError) -> String { - if e.is_null() { - return "unknown error".into(); - } - // SAFETY: a non-null NSError the framework passed. - unsafe { (*e).localizedDescription().to_string() } - } - - fn spin_until(slot: &Arc>>) -> T { - loop { - if let Some(v) = slot.lock().unwrap().take() { - return v; - } - NSRunLoop::mainRunLoop().runUntilDate(&NSDate::dateWithTimeIntervalSinceNow(0.1)); - } - } - - /// Loads a restore image (from a file, or Apple's newest), as a raw retained pointer. - fn restore_image(file: Option<&Path>) -> Result> { - let slot: Arc>>> = Arc::new(Mutex::new(None)); - let s = slot.clone(); - let block = RcBlock::new(move |img: *mut VZMacOSRestoreImage, err: *mut NSError| { - let r = if img.is_null() { - Err(describe(err)) - } else { - // SAFETY: a live image the framework passed; retained here, released by the - // Retained made from it below. - Ok(unsafe { Retained::into_raw(Retained::retain(img).unwrap()) } as usize) - }; - *s.lock().unwrap() = Some(r); - }); - // SAFETY: the block lives until the call returns, and the framework copies it. - unsafe { - match file { - Some(f) => VZMacOSRestoreImage::loadFileURL_completionHandler(&url(f), &block), - None => VZMacOSRestoreImage::fetchLatestSupportedWithCompletionHandler(&block), - } - } - let ptr = spin_until(&slot).map_err(anyhow::Error::msg)?; - // SAFETY: retained in the block above. - Ok(unsafe { Retained::from_raw(ptr as *mut VZMacOSRestoreImage) }.unwrap()) - } - - pub fn latest() -> Result { - let img = restore_image(None)?; - // SAFETY: a loaded image. - let u = unsafe { img.URL() }; - Ok(u.absoluteString() - .map(|s| s.to_string()) - .unwrap_or_default()) - } - - pub fn install( - ipsw: &Path, - dir: &Path, - disk_mib: u64, - cpus: u32, - memory_mib: u64, - ) -> Result { - let img = restore_image(Some(ipsw)).context("load the IPSW")?; - // SAFETY: each call below is on the main thread, with live objects, in the order - // Virtualization.framework's documentation gives. - unsafe { - let req = img.mostFeaturefulSupportedConfiguration().context( - "this Mac cannot run the macOS in this IPSW (too old or too new for it)", - )?; - let hw = req.hardwareModel(); - if !hw.isSupported() { - bail!("this Mac does not support the IPSW's hardware model"); - } - let cpus = (cpus as usize).max(req.minimumSupportedCPUCount()); - let memory = (memory_mib * 1024 * 1024).max(req.minimumSupportedMemorySize()); - println!("note creating the auxiliary storage"); - let aux = VZMacAuxiliaryStorage::initCreatingStorageAtURL_hardwareModel_options_error( - VZMacAuxiliaryStorage::alloc(), - &url(&dir.join("aux.img")), - &hw, - VZMacAuxiliaryStorageInitializationOptions::AllowOverwrite, - ) - .map_err(|e| anyhow::anyhow!("create aux.img: {}", e.localizedDescription()))?; - let ident = VZMacMachineIdentifier::new(); - let ident_data = ident.dataRepresentation().to_vec(); - std::fs::write(dir.join("machine-identifier.bin"), &ident_data)?; - std::fs::write( - dir.join("hardware-model.bin"), - hw.dataRepresentation().to_vec(), - )?; - let ecid = crate::create::ecid_from_identifier(&ident_data)?; - - let disk = dir.join("disk.img"); - std::fs::File::create(&disk)?.set_len(disk_mib * 1024 * 1024)?; - - let platform = VZMacPlatformConfiguration::new(); - platform.setHardwareModel(&hw); - platform.setMachineIdentifier(&ident); - platform.setAuxiliaryStorage(Some(&aux)); - let config = VZVirtualMachineConfiguration::new(); - config.setPlatform(&platform); - config.setBootLoader(Some(&VZMacOSBootLoader::new())); - config.setCPUCount(cpus); - config.setMemorySize(memory); - let attachment = VZDiskImageStorageDeviceAttachment::initWithURL_readOnly_error( - VZDiskImageStorageDeviceAttachment::alloc(), - &url(&disk), - false, - ) - .map_err(|e| anyhow::anyhow!("attach disk.img: {}", e.localizedDescription()))?; - let blk = VZVirtioBlockDeviceConfiguration::initWithAttachment( - VZVirtioBlockDeviceConfiguration::alloc(), - &attachment, - ); - config.setStorageDevices(&NSArray::from_retained_slice(&[Retained::into_super(blk)])); - let display = VZMacGraphicsDisplayConfiguration::initWithWidthInPixels_heightInPixels_pixelsPerInch( - VZMacGraphicsDisplayConfiguration::alloc(), - 1920, - 1200, - 80, - ); - let gfx = VZMacGraphicsDeviceConfiguration::new(); - gfx.setDisplays(&NSArray::from_retained_slice(&[display])); - config.setGraphicsDevices(&NSArray::from_retained_slice(&[Retained::into_super(gfx)])); - config.validateWithError().map_err(|e| { - anyhow::anyhow!("the VM's configuration: {}", e.localizedDescription()) - })?; - - let vm = VZVirtualMachine::initWithConfiguration(VZVirtualMachine::alloc(), &config); - let installer = VZMacOSInstaller::initWithVirtualMachine_restoreImageURL( - VZMacOSInstaller::alloc(), - &vm, - &url(ipsw), - ); - let done: Arc>>> = Arc::new(Mutex::new(None)); - let d = done.clone(); - let block = RcBlock::new(move |err: *mut NSError| { - *d.lock().unwrap() = Some(if err.is_null() { - Ok(()) - } else { - Err(describe(err)) - }); - }); - println!("note installing macOS"); - installer.installWithCompletionHandler(&block); - let progress = installer.progress(); - let mut last = -1.0; - let result = loop { - if let Some(r) = done.lock().unwrap().take() { - break r; - } - let f = progress.fractionCompleted(); - if (f - last).abs() >= 0.001 { - last = f; - println!("progress {f:.4}"); - use std::io::Write; - let _ = std::io::stdout().flush(); - } - NSRunLoop::mainRunLoop().runUntilDate(&NSDate::dateWithTimeIntervalSinceNow(0.25)); - }; - result.map_err(anyhow::Error::msg)?; - Ok(ecid) - } - } -} - -/// `reims-ctl __vz-install`. -pub fn install_main( - ipsw: &Path, - dir: &Path, - disk_mib: u64, - cpus: u32, - memory_mib: u64, -) -> Result { - #[cfg(target_os = "macos")] - { - let ecid = imp::install(ipsw, dir, disk_mib, cpus, memory_mib)?; - println!("ecid {ecid}"); - Ok(0) - } - #[cfg(not(target_os = "macos"))] - { - let _ = (ipsw, dir, disk_mib, cpus, memory_mib); - bail!("an IPSW installs only on macOS") - } -} - -/// `reims-ctl __vz-latest`: the URL of the newest IPSW this Mac supports. -pub fn latest_main() -> Result { - #[cfg(target_os = "macos")] - { - println!("{}", imp::latest()?); - Ok(0) - } - #[cfg(not(target_os = "macos"))] - bail!("IPSWs are macOS's") -} diff --git a/scripts/install-ctl.sh b/scripts/install-ctl.sh index 6bf207da4..ceb43dbb5 100755 --- a/scripts/install-ctl.sh +++ b/scripts/install-ctl.sh @@ -1,42 +1,31 @@ #!/usr/bin/env bash # -# Builds and installs reims-ctl, and the QEMU it runs, with apple-gfx on this -# checkout's reims-vgpu. +# Builds and installs reims-ctl, and the QEMU it runs, with reims-vgpu's own +# GPU device on this checkout's reims-vgpu. # # scripts/install-ctl.sh [--yes] [--update] [--skip-qemu] # -# On macOS, GPU_ARM picks what VMs' graphics run on: -# -# GPU_ARM=metal scripts/install-ctl.sh Metal (the default) -# GPU_ARM=vulkan scripts/install-ctl.sh Vulkan, on Homebrew's MoltenVK -# -# Run it again with the other value to switch; switching back to one built -# before rebuilds only what changed since. Without GPU_ARM it keeps the arm -# installed now (a Vulkan install's QEMU directory ends in -vulkan), so -# reims-ctl update never switches it. Linux has Vulkan alone. -# -# macOS on arm64 and Linux on x86-64 (Ubuntu or Debian, Arch or CachyOS; other -# distributions get the list of what to install). It: +# Linux on x86-64 (Ubuntu or Debian, Arch or CachyOS; other distributions get +# the list of what to install), where the library runs on Vulkan; reims-ctl +# runs no VMs on another host. It: # 1. checks the build's dependencies, and offers to install those missing -# (Homebrew on macOS; apt or pacman on Linux, through sudo), and rustup -# through rustup.rs, beside any other cargo, whose installer asks its own -# questions; +# (apt or pacman, through sudo), and rustup through rustup.rs, beside any +# other cargo, whose installer asks its own questions; # 2. fetches vendor/qemu, QEMU's source, without QEMU's own submodules (its # build fetches what it needs); cargo fetches metal2vulkan itself, at the # commit the library's Cargo.toml names; -# 3. builds the library (cargo xtask dist) on GPU_ARM's platform and QEMU on -# it, in ~/.cache/reims-ctl, and installs QEMU into +# 3. builds the library (cargo xtask dist) on Vulkan and QEMU on it, in +# ~/.cache/reims-ctl, and installs QEMU into # ~/.local/share/reims-ctl/qemu/, linking qemu/current to it. A # build never replaces another: a running VM keeps the binary it started # with; # 4. installs reims-ctl with cargo install (into ~/.cargo/bin, or -# CARGO_INSTALL_ROOT's bin), signed on macOS with the virtualization -# entitlement, which installing macOS from an IPSW needs; -# 5. installs reims-util beside it, which makes a new x86-64 VM's OpenCore -# image and downloads its macOS installer from Apple: on Linux, and on any -# host where one is there already. reims-ctl does (__record-install), at -# the commit it names (crates/reims-ctl/src/reims_util.rs), replacing one -# from another commit and leaving one at that commit as it is. +# CARGO_INSTALL_ROOT's bin); +# 5. installs reims-util beside it, which makes a new VM's OpenCore image and +# downloads its macOS installer from Apple. reims-ctl does +# (__record-install), at the commit it names +# (crates/reims-ctl/src/reims_util.rs), replacing one from another commit +# and leaving one at that commit as it is. # # --yes install what is missing without asking (rustup with -y too) # --update pull this checkout first (fast-forward only), putting back the @@ -48,9 +37,9 @@ # needs; it warns where the QEMU or library this checkout builds # changed since that QEMU's build # -# Environment: GPU_ARM (above); CARGO_TARGET_DIR, the library's build (default -# the checkout's target/); XDG_DATA_HOME and XDG_CACHE_HOME move the install -# and the build from ~/.local/share and ~/.cache, where they are on macOS too. +# Environment: CARGO_TARGET_DIR, the library's build (default the checkout's +# target/); XDG_DATA_HOME and XDG_CACHE_HOME move the install and the build +# from ~/.local/share and ~/.cache. set -euo pipefail ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -91,31 +80,17 @@ ask() { } OS="$(uname -s)" ARCH="$(uname -m)" -case "$OS/$ARCH" in - Darwin/arm64) - PLATFORM=macos-arm64 - # gnutls gives QEMU its ciphers. Without a crypto library QEMU has no AES, - # which vmapple's AES engine needs (a macOS guest uses it as it mounts its - # root volume), and refuses to start a VM. It is enabled by name, so that - # configure stops where it is missing. - QEMU_CONFIGURE=(--target-list=aarch64-softmmu --enable-hvf --enable-gnutls --disable-sdl - --disable-gtk) - QEMU_BINARY=qemu-system-aarch64 - ;; - Linux/x86_64) - PLATFORM=linux-x86_64 - # libusb (usb-host, USB passthrough) and SPICE (-spice, a display a SPICE - # client connects to) are enabled by name: configure leaves out an - # optional feature whose library it does not find, saying nothing. - QEMU_CONFIGURE=(--target-list=x86_64-softmmu --enable-kvm --disable-sdl --enable-gtk --enable-slirp - --enable-libusb --enable-spice) - QEMU_BINARY=qemu-system-x86_64 - ;; - *) die "reims-ctl supports macOS on arm64 and Linux on x86-64; this is $OS on $ARCH" ;; -esac +[[ $OS/$ARCH == Linux/x86_64 ]] || die "reims-ctl runs VMs on Linux x86-64 hosts; this is $OS on $ARCH" +PLATFORM=linux-x86_64 +# libusb (usb-host, USB passthrough) and SPICE (-spice, a display a SPICE +# client connects to) are enabled by name: configure leaves out an optional +# feature whose library it does not find, saying nothing. +QEMU_CONFIGURE=(--target-list=x86_64-softmmu --enable-kvm --disable-sdl --enable-gtk --enable-slirp + --enable-libusb --enable-spice) +QEMU_BINARY=qemu-system-x86_64 -# The XDG directory VAR names, else ~/FALLBACK: unset on macOS, and ignored -# unless absolute (as reims-ctl does). +# The XDG directory VAR names, else ~/FALLBACK: ignored unless absolute (as +# reims-ctl does). xdg() { # VAR FALLBACK local v="${!1:-}" if [[ $v == /* ]]; then printf '%s' "$v"; else printf '%s' "$HOME/$2"; fi @@ -124,20 +99,6 @@ DATA="$(xdg XDG_DATA_HOME .local/share)/reims-ctl" CACHE="$(xdg XDG_CACHE_HOME .cache)/reims-ctl" mkdir -p "$DATA" "$CACHE" -# The GPU arm (header). ARM_SUFFIX names a macOS build on Vulkan, its QEMU -# build directory and its install, apart from the Metal one. -case "$OS/${GPU_ARM:-}" in - Darwin/) - if [[ "$(readlink "$DATA/qemu/current" 2>/dev/null)" == *-vulkan ]]; then GPU_ARM=vulkan; else GPU_ARM=metal; fi - ;; - Linux/) GPU_ARM=vulkan ;; - Darwin/metal | Darwin/vulkan | Linux/vulkan) ;; - Linux/metal) die "GPU_ARM=metal is macOS's: on Linux the library runs on Vulkan alone" ;; - *) die "GPU_ARM is metal or vulkan, not $GPU_ARM" ;; -esac -ARM_SUFFIX="" -[[ $OS == Darwin && $GPU_ARM == vulkan ]] && ARM_SUFFIX=-vulkan - # Every VM runs on QEMU: --skip-qemu keeps the installed one, and needs one. if [[ $SKIP_QEMU == 1 && ! -x "$DATA/qemu/current/bin/$QEMU_BINARY" ]]; then die "--skip-qemu keeps the installed QEMU, and none is installed ($DATA/qemu/current/bin/$QEMU_BINARY is missing): run this without --skip-qemu, which builds it" @@ -208,163 +169,146 @@ fi missing=() -if [[ $OS == Darwin ]]; then - xcode-select -p >/dev/null 2>&1 || die "Xcode's command line tools are missing: run xcode-select --install, then this again" - command -v brew >/dev/null 2>&1 || die "Homebrew is missing (https://brew.sh): install it, then run this again" - formulas=(ninja pkgconf glib pixman libslirp lld gnutls) - # The Vulkan arm's loader and driver, which metal2vulkan opens from - # Homebrew's lib. - [[ $GPU_ARM == vulkan ]] && formulas+=(vulkan-loader molten-vk) - for f in "${formulas[@]}"; do - brew list --formula "$f" >/dev/null 2>&1 || missing+=("$f") - done - if ((${#missing[@]})); then - say "Missing Homebrew packages: ${missing[*]}" - ask "Install them with brew?" || die "install them (brew install ${missing[*]}), then run this again" - brew install "${missing[@]}" - fi +distro_id="" distro_like="" +if [[ -r /etc/os-release ]]; then + # shellcheck disable=SC1091 + distro_id="$(. /etc/os-release && echo "${ID:-}")" + # shellcheck disable=SC1091 + distro_like="$(. /etc/os-release && echo "${ID_LIKE:-}")" +fi +# The library (cargo xtask dist: clang, lld and binutils for the option ROM; +# CMake and the X11, Wayland, xkbcommon and EGL headers for SDL3's video, +# which it builds from source), and QEMU (glib, pixman, libslirp; GTK 3 for +# its own window, which a VM on VMware SVGA shows its display in; pipewire, +# pulse and ALSA for its audio backends; libusb for USB passthrough; the +# SPICE server for -spice; bzip2 unpacks its firmware). A new x86-64 VM's +# OVMF comes from reims-util, with its OpenCore image. +apt_pkgs=(build-essential git curl ca-certificates pkg-config python3 python3-venv ninja-build + flex bison bzip2 cmake clang lld binutils libglib2.0-dev libpixman-1-dev libslirp-dev + zlib1g-dev libfdt-dev libpipewire-0.3-dev libpulse-dev libasound2-dev libusb-1.0-0-dev + libspice-server-dev libvulkan1 + libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev + libxtst-dev libxkbcommon-dev libwayland-dev libwayland-bin libdecor-0-dev + libegl-dev libgl-dev libdrm-dev libgbm-dev libdbus-1-dev libudev-dev libgtk-3-dev) +pacman_pkgs=(base-devel git curl python ninja pkgconf flex bison bzip2 cmake clang lld + glib2 pixman libslirp zlib dtc pipewire libpulse alsa-lib libusb spice vulkan-icd-loader + libx11 libxext libxrandr libxcursor libxi libxfixes libxss libxtst libxkbcommon + wayland libdecor mesa libdrm dbus systemd-libs gtk3) +case " $distro_id $distro_like " in + *" debian "* | *" ubuntu "*) + for p in "${apt_pkgs[@]}"; do + dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'install ok installed' || missing+=("$p") + done + if ((${#missing[@]})); then + say "Missing packages: ${missing[*]}" + ask "Install them with sudo apt-get?" || die "install them (sudo apt-get install ${missing[*]}), then run this again" + sudo apt-get update + sudo apt-get install -y "${missing[@]}" + fi + ;; + *" arch "* | *" cachyos "*) + for p in "${pacman_pkgs[@]}"; do + pacman -Qq "$p" >/dev/null 2>&1 || pacman -Qqg "$p" >/dev/null 2>&1 || missing+=("$p") + done + if ((${#missing[@]})); then + say "Missing packages: ${missing[*]}" + ask "Install them with sudo pacman?" || die "install them (sudo pacman -S --needed ${missing[*]}), then run this again" + sudo pacman -S --needed --noconfirm "${missing[@]}" + fi + ;; + *) + warn "$distro_id is neither Debian/Ubuntu nor Arch/CachyOS: install the equivalents of these Ubuntu packages yourself if the build stops: ${apt_pkgs[*]}" + ;; +esac +if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then + warn "/dev/kvm is not usable by you: enable virtualization in the firmware and add yourself to the kvm group (sudo usermod -aG kvm \$USER; log in again), or VMs will not start" +fi +# The guest's memory reaches the GPU through /dev/udmabuf, on every GPU: without +# it the library's views of that memory take a kernel mapping per 4 KiB page, +# past vm.max_map_count at 4K even at the guest's desktop (reims-ctl's +# runtime::udmabuf_problem, docs/qemu.md "Linux hosts: vm.max_map_count"). +why="the guest's memory reaches the GPU through it, and without it the guest can crash at higher resolutions, at 4K even at its desktop" +udmabuf=0 +if [[ ! -e /dev/udmabuf ]]; then + warn "there's no /dev/udmabuf: $why. Load it with sudo modprobe udmabuf, and put udmabuf in a file in /etc/modules-load.d to keep it" else - distro_id="" distro_like="" - if [[ -r /etc/os-release ]]; then - # shellcheck disable=SC1091 - distro_id="$(. /etc/os-release && echo "${ID:-}")" - # shellcheck disable=SC1091 - distro_like="$(. /etc/os-release && echo "${ID_LIKE:-}")" - fi - # The library (cargo xtask dist: clang, lld and binutils for the option ROM; - # CMake and the X11, Wayland, xkbcommon and EGL headers for SDL3's video, - # which it builds from source), and QEMU (glib, pixman, libslirp; GTK 3 for - # its own window, which a VM on VMware SVGA shows its display in; pipewire, - # pulse and ALSA for its audio backends; libusb for USB passthrough; the - # SPICE server for -spice; bzip2 unpacks its firmware). A new x86-64 VM's - # OVMF comes from reims-util, with its OpenCore image. - apt_pkgs=(build-essential git curl ca-certificates pkg-config python3 python3-venv ninja-build - flex bison bzip2 cmake clang lld binutils libglib2.0-dev libpixman-1-dev libslirp-dev - zlib1g-dev libfdt-dev libpipewire-0.3-dev libpulse-dev libasound2-dev libusb-1.0-0-dev - libspice-server-dev libvulkan1 - libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxi-dev libxfixes-dev libxss-dev - libxtst-dev libxkbcommon-dev libwayland-dev libwayland-bin libdecor-0-dev - libegl-dev libgl-dev libdrm-dev libgbm-dev libdbus-1-dev libudev-dev libgtk-3-dev) - pacman_pkgs=(base-devel git curl python ninja pkgconf flex bison bzip2 cmake clang lld - glib2 pixman libslirp zlib dtc pipewire libpulse alsa-lib libusb spice vulkan-icd-loader - libx11 libxext libxrandr libxcursor libxi libxfixes libxss libxtst libxkbcommon - wayland libdecor mesa libdrm dbus systemd-libs gtk3) - case " $distro_id $distro_like " in - *" debian "* | *" ubuntu "*) - for p in "${apt_pkgs[@]}"; do - dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'install ok installed' || missing+=("$p") - done - if ((${#missing[@]})); then - say "Missing packages: ${missing[*]}" - ask "Install them with sudo apt-get?" || die "install them (sudo apt-get install ${missing[*]}), then run this again" - sudo apt-get update - sudo apt-get install -y "${missing[@]}" - fi - ;; - *" arch "* | *" cachyos "*) - for p in "${pacman_pkgs[@]}"; do - pacman -Qq "$p" >/dev/null 2>&1 || pacman -Qqg "$p" >/dev/null 2>&1 || missing+=("$p") - done - if ((${#missing[@]})); then - say "Missing packages: ${missing[*]}" - ask "Install them with sudo pacman?" || die "install them (sudo pacman -S --needed ${missing[*]}), then run this again" - sudo pacman -S --needed --noconfirm "${missing[@]}" - fi - ;; - *) - warn "$distro_id is neither Debian/Ubuntu nor Arch/CachyOS: install the equivalents of these Ubuntu packages yourself if the build stops: ${apt_pkgs[*]}" - ;; - esac - if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then - warn "/dev/kvm is not usable by you: enable virtualization in the firmware and add yourself to the kvm group (sudo usermod -aG kvm \$USER; log in again), or VMs will not start" - fi - # The guest's memory reaches the GPU through /dev/udmabuf, on every GPU: without - # it the library's views of that memory take a kernel mapping per 4 KiB page, - # past vm.max_map_count at 4K even at the guest's desktop (reims-ctl's - # runtime::udmabuf_problem, docs/qemu.md "Linux hosts: vm.max_map_count"). - why="the guest's memory reaches the GPU through it, and without it the guest can crash at higher resolutions, at 4K even at its desktop" - udmabuf=0 - if [[ ! -e /dev/udmabuf ]]; then - warn "there's no /dev/udmabuf: $why. Load it with sudo modprobe udmabuf, and put udmabuf in a file in /etc/modules-load.d to keep it" + group="$(stat -c %G /dev/udmabuf)" + if [[ -r /dev/udmabuf && -w /dev/udmabuf ]]; then + udmabuf=1 + if [[ $group != root ]] && ! id -nG | tr ' ' '\n' | grep -qx "$group"; then + say "You can open /dev/udmabuf in this session, but you're not in its $group group: over ssh, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG $group \$USER) to start VMs there" + fi + elif [[ $group == root ]]; then + warn "only root can open /dev/udmabuf: $why. Give it to the kvm group with a udev rule, a file in /etc/udev/rules.d holding KERNEL==\"udmabuf\", GROUP=\"kvm\", MODE=\"0660\", add yourself to kvm (sudo usermod -aG kvm \$USER), and restart" else - group="$(stat -c %G /dev/udmabuf)" - if [[ -r /dev/udmabuf && -w /dev/udmabuf ]]; then - udmabuf=1 - if [[ $group != root ]] && ! id -nG | tr ' ' '\n' | grep -qx "$group"; then - say "You can open /dev/udmabuf in this session, but you're not in its $group group: over ssh, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG $group \$USER) to start VMs there" - fi - elif [[ $group == root ]]; then - warn "only root can open /dev/udmabuf: $why. Give it to the kvm group with a udev rule, a file in /etc/udev/rules.d holding KERNEL==\"udmabuf\", GROUP=\"kvm\", MODE=\"0660\", add yourself to kvm (sudo usermod -aG kvm \$USER), and restart" + say "You can't open /dev/udmabuf: $why. You need its $group group" + if ask "Add you to the $group group with sudo usermod?"; then + sudo usermod -aG "$group" "$USER" + say "Added you to $group: log in again for it to take effect" else - say "You can't open /dev/udmabuf: $why. You need its $group group" - if ask "Add you to the $group group with sudo usermod?"; then - sudo usermod -aG "$group" "$USER" - say "Added you to $group: log in again for it to take effect" - else - warn "add yourself to the $group group (sudo usermod -aG $group \$USER) and log in again, or the guest can crash at higher resolutions" - fi + warn "add yourself to the $group group (sudo usermod -aG $group \$USER) and log in again, or the guest can crash at higher resolutions" fi fi - # With udmabuf, vm.max_map_count is only a speed-up, on NVIDIA: a view of an - # x86-64 guest's memory takes a mapping per 4 KiB page there, and past the - # library's budget (the limit less 16,384 and 8,192) its buffers are copied, - # which works and is slower (reims-ctl's runtime::max_map_count). A new VM - # gets half the host's memory, 4 to 16 GiB. - maps="$(cat /proc/sys/vm/max_map_count 2>/dev/null || echo 0)" - vm_mib=$(($(awk '/^MemTotal:/ { print $2 }' /proc/meminfo) / 2 / 1048576 * 1024)) - vm_mib=$((vm_mib < 4096 ? 4096 : vm_mib > 16384 ? 16384 : vm_mib)) - want=$((vm_mib * 256 + 24576)) - if ((udmabuf && maps < want)) && grep -qsx 0x10de /sys/class/drm/*/device/vendor; then - raise=1048576 - while ((raise < want)); do raise=$((raise * 2)); done - uncopied=$((maps > 24576 ? (maps - 24576) / 256 : 0)) - say "vm.max_map_count is $maps: on an NVIDIA GPU, past about $uncopied MiB of a new VM's $((vm_mib / 1024)) GiB the GPU gets copies of its memory, which is slower; sudo sysctl -w vm.max_map_count=$raise, and a file in /etc/sysctl.d to keep it, avoids them" +fi +# With udmabuf, vm.max_map_count is only a speed-up, on NVIDIA: a view of an +# x86-64 guest's memory takes a mapping per 4 KiB page there, and past the +# library's budget (the limit less 16,384 and 8,192) its buffers are copied, +# which works and is slower (reims-ctl's runtime::max_map_count). A new VM +# gets half the host's memory, 4 to 16 GiB. +maps="$(cat /proc/sys/vm/max_map_count 2>/dev/null || echo 0)" +vm_mib=$(($(awk '/^MemTotal:/ { print $2 }' /proc/meminfo) / 2 / 1048576 * 1024)) +vm_mib=$((vm_mib < 4096 ? 4096 : vm_mib > 16384 ? 16384 : vm_mib)) +want=$((vm_mib * 256 + 24576)) +if ((udmabuf && maps < want)) && grep -qsx 0x10de /sys/class/drm/*/device/vendor; then + raise=1048576 + while ((raise < want)); do raise=$((raise * 2)); done + uncopied=$((maps > 24576 ? (maps - 24576) / 256 : 0)) + say "vm.max_map_count is $maps: on an NVIDIA GPU, past about $uncopied MiB of a new VM's $((vm_mib / 1024)) GiB the GPU gets copies of its memory, which is slower; sudo sysctl -w vm.max_map_count=$raise, and a file in /etc/sysctl.d to keep it, avoids them" +fi +# MGLRU's thrashing guard (reims-ctl's runtime::MIN_TTL_FILE): above 0, the +# kernel kills a process where it can't keep the pages used in the last that +# many ms, even with RAM free, and a VM's QEMU can be the one. Measured on +# CachyOS hosts at 100, its kernel's default there. Offered off on a terminal +# only, and never required; the tmpfiles.d line keeps it off. +min_ttl_file=/sys/kernel/mm/lru_gen/min_ttl_ms +min_ttl_line='w /sys/kernel/mm/lru_gen/min_ttl_ms - - - - 0' +min_ttl="$(cat "$min_ttl_file" 2>/dev/null || echo 0)" +if [[ $min_ttl =~ ^[0-9]+$ ]] && ((min_ttl > 0)); then + warn "$min_ttl_file is $min_ttl: where the kernel can't keep the pages used in the last $min_ttl ms in memory, it kills a process, which can be a VM's QEMU, even while RAM is free (measured on hosts at 100, killing builds with most RAM free); 0 turns this off" + if [[ -t 0 ]] && ask "Write 0 to $min_ttl_file now with sudo?"; then + echo 0 | sudo tee "$min_ttl_file" >/dev/null || warn "sudo didn't write it" fi - # MGLRU's thrashing guard (reims-ctl's runtime::MIN_TTL_FILE): above 0, the - # kernel kills a process where it can't keep the pages used in the last that - # many ms, even with RAM free, and a VM's QEMU can be the one. Measured on - # CachyOS hosts at 100, its kernel's default there. Offered off on a terminal - # only, and never required; the tmpfiles.d line keeps it off. - min_ttl_file=/sys/kernel/mm/lru_gen/min_ttl_ms - min_ttl_line='w /sys/kernel/mm/lru_gen/min_ttl_ms - - - - 0' - min_ttl="$(cat "$min_ttl_file" 2>/dev/null || echo 0)" - if [[ $min_ttl =~ ^[0-9]+$ ]] && ((min_ttl > 0)); then - warn "$min_ttl_file is $min_ttl: where the kernel can't keep the pages used in the last $min_ttl ms in memory, it kills a process, which can be a VM's QEMU, even while RAM is free (measured on hosts at 100, killing builds with most RAM free); 0 turns this off" - if [[ -t 0 ]] && ask "Write 0 to $min_ttl_file now with sudo?"; then - echo 0 | sudo tee "$min_ttl_file" >/dev/null || warn "sudo didn't write it" - fi - keep="the line $min_ttl_line in a file in /etc/tmpfiles.d, such as /etc/tmpfiles.d/reims-ctl-min-ttl.conf" - if [[ "$(cat "$min_ttl_file" 2>/dev/null)" == 0 ]]; then - say "It's 0 now; $keep, keeps it at 0 after a restart" - else - say "echo 0 | sudo tee $min_ttl_file turns it off now, and $keep, keeps it at 0 after a restart" - fi + keep="the line $min_ttl_line in a file in /etc/tmpfiles.d, such as /etc/tmpfiles.d/reims-ctl-min-ttl.conf" + if [[ "$(cat "$min_ttl_file" 2>/dev/null)" == 0 ]]; then + say "It's 0 now; $keep, keeps it at 0 after a restart" + else + say "echo 0 | sudo tee $min_ttl_file turns it off now, and $keep, keeps it at 0 after a restart" fi - # USB passthrough (reims-ctl usb): QEMU opens a USB device's file in - # /dev/bus/usb, which only root may write unless a udev rule says otherwise. - # This one gives USB devices other than hubs to the kvm group, over SSH too, - # and to the user at the host's screen (uaccess, which a file sorting before - # systemd's 73-seat-late.rules sets). reims-ctl's usb::UDEV_RULE is the same - # line, which its tests check. - usb_rule_file=/etc/udev/rules.d/70-reims-ctl-usb.rules - usb_rule='SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{bDeviceClass}!="09", GROUP="kvm", MODE="0664", TAG+="uaccess"' - if ! grep -qsxF "$usb_rule" "$usb_rule_file"; then - say "A VM can be given this host's USB devices once QEMU, running as you, may open them" - if ask "Add the udev rule $usb_rule_file, giving USB devices other than hubs to the kvm group and to you at this host's screen, with sudo?"; then - printf '# reims-ctl: USB devices for VMs (reims-ctl usb --help)\n%s\n' "$usb_rule" | - sudo tee "$usb_rule_file" >/dev/null - # Applied to the devices plugged in now, as to those plugged in later. - sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb || - warn "udev did not reload its rules: unplug a USB device and plug it in again, or restart, before giving it to a VM" - else - warn "without the rule, a VM can be given only the USB devices you may open; reims-ctl usb --help shows it" - fi - fi - # Unless /dev/udmabuf's group, kvm, was the one named above. - if [[ ${group:-} != kvm ]] && getent group kvm >/dev/null && ! id -nG | tr ' ' '\n' | grep -qx kvm; then - say "You're not in the kvm group: over SSH, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG kvm \$USER) to give VMs USB devices there" +fi +# USB passthrough (reims-ctl usb): QEMU opens a USB device's file in +# /dev/bus/usb, which only root may write unless a udev rule says otherwise. +# This one gives USB devices other than hubs to the kvm group, over SSH too, +# and to the user at the host's screen (uaccess, which a file sorting before +# systemd's 73-seat-late.rules sets). reims-ctl's usb::UDEV_RULE is the same +# line, which its tests check. +usb_rule_file=/etc/udev/rules.d/70-reims-ctl-usb.rules +usb_rule='SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ATTR{bDeviceClass}!="09", GROUP="kvm", MODE="0664", TAG+="uaccess"' +if ! grep -qsxF "$usb_rule" "$usb_rule_file"; then + say "A VM can be given this host's USB devices once QEMU, running as you, may open them" + if ask "Add the udev rule $usb_rule_file, giving USB devices other than hubs to the kvm group and to you at this host's screen, with sudo?"; then + printf '# reims-ctl: USB devices for VMs (reims-ctl usb --help)\n%s\n' "$usb_rule" | + sudo tee "$usb_rule_file" >/dev/null + # Applied to the devices plugged in now, as to those plugged in later. + sudo udevadm control --reload && sudo udevadm trigger --subsystem-match=usb || + warn "udev did not reload its rules: unplug a USB device and plug it in again, or restart, before giving it to a VM" + else + warn "without the rule, a VM can be given only the USB devices you may open; reims-ctl usb --help shows it" fi fi +# Unless /dev/udmabuf's group, kvm, was the one named above. +if [[ ${group:-} != kvm ]] && getent group kvm >/dev/null && ! id -nG | tr ' ' '\n' | grep -qx kvm; then + say "You're not in the kvm group: over SSH, where a desktop session's access doesn't apply, add yourself to it (sudo usermod -aG kvm \$USER) to give VMs USB devices there" +fi # The build runs the toolchain rust-toolchain.toml pins, through rustup's proxies in Cargo's # home, so they come first on PATH here: a shell that sourced no Cargo env has none on it, and @@ -418,17 +362,12 @@ fi # ------------------------------------------------------------------ the library and QEMU -# The files running processes execute, their links resolved, a line each: on -# Linux every process's /proc/PID/exe; on macOS the txt files lsof lists of -# those whose name starts with qemu (QEMU, qemu-img). A QEMU's executable names -# the build it started from, where its command line, and ps, show only -# qemu/current, through which reims-ctl runs QEMU, and which a new build moves. +# The files running processes execute, their links resolved, a line each: +# every process's /proc/PID/exe. A QEMU's executable names the build it started +# from, where its command line, and ps, show only qemu/current, through which +# reims-ctl runs QEMU, and which a new build moves. qemu_executables() { - if [[ -d /proc/self ]]; then - readlink /proc/[0-9]*/exe 2>/dev/null || true - else - lsof -nP -a -c qemu -d txt -Fn 2>/dev/null | sed -n 's/^n//p' || true - fi + readlink /proc/[0-9]*/exe 2>/dev/null || true } # prune_qemu DIR: removes the QEMU builds in DIR but the three newest and those @@ -445,17 +384,12 @@ prune_qemu() { # kept_qemu DIR: why the QEMU build DIR, which --skip-qemu keeps, is not the # one this checkout builds, a line each. DIR's name ends in the commit it was -# built at, then -vulkan for a macOS build on Vulkan. The build is QEMU's -# source and the library and option ROM it links (cargo xtask dist): all of -# the tree's crates but reims-ctl, which is its own workspace. +# built at. The build is QEMU's source and the library and option ROM it links +# (cargo xtask dist): all of the tree's crates but reims-ctl, which is its own +# workspace. kept_qemu() { - local built="${1##*/}" suffix="" arm=Metal + local built="${1##*/}" built="${built#*-*-}" - [[ $built == *-vulkan ]] && suffix=-vulkan arm=Vulkan - built="${built%-vulkan}" - if [[ $suffix != "$ARM_SUFFIX" ]]; then - echo "the installed QEMU runs on $arm, not GPU_ARM=$GPU_ARM: run this without --skip-qemu to build it on $GPU_ARM" - fi if ! git -C "$ROOT" cat-file -e "$built^{commit}" 2>/dev/null; then echo "the installed QEMU was built at $built, which this checkout does not have: run this without --skip-qemu to build this checkout's" elif ! git -C "$ROOT" diff --quiet "$built" HEAD -- vendor/qemu crates firmware xtask \ @@ -466,14 +400,14 @@ kept_qemu() { COMMIT="$(git -C "$ROOT" rev-parse --short HEAD)" TARGET="${CARGO_TARGET_DIR:-$ROOT/target}" -if [[ $GPU_ARM == metal ]]; then DIST="$TARGET/dist"; else DIST="$TARGET/dist-vulkan"; fi +DIST="$TARGET/dist-vulkan" if [[ $SKIP_QEMU == 0 ]]; then - say "Building the library on $GPU_ARM (cargo xtask dist --platform $GPU_ARM)" - (cd "$ROOT" && CARGO_TARGET_DIR="$TARGET" cargo xtask dist --platform "$GPU_ARM") + say "Building the library (cargo xtask dist --platform vulkan)" + (cd "$ROOT" && CARGO_TARGET_DIR="$TARGET" cargo xtask dist --platform vulkan) [[ -f "$DIST/lib/pkgconfig/reims-vgpu.pc" ]] || die "cargo xtask dist wrote no $DIST/lib/pkgconfig/reims-vgpu.pc" - BUILD="$CACHE/qemu-build-$PLATFORM$ARM_SUFFIX" + BUILD="$CACHE/qemu-build-$PLATFORM" PC="$DIST/lib/pkgconfig" # QEMU's install prefix: never used where it is, since QEMU finds its files # relative to its binary; the build is staged with DESTDIR and moved. @@ -506,10 +440,7 @@ if [[ $SKIP_QEMU == 0 ]]; then DESTDIR="$STAGE" ninja -C "$BUILD" install >/dev/null [[ -x "$STAGE$PREFIX/bin/$QEMU_BINARY" ]] || die "QEMU's install has no bin/$QEMU_BINARY" "$STAGE$PREFIX/bin/$QEMU_BINARY" -device help 2>/dev/null | grep -q '"reims-graphics-pci"' || die "QEMU's install has no reims-graphics-pci: was it configured with reims-vgpu?" - if [[ $OS == Darwin ]] && ! codesign -d --entitlements - "$STAGE$PREFIX/bin/$QEMU_BINARY" 2>/dev/null | grep -q com.apple.security.hypervisor; then - codesign -s - -f --entitlements "$ROOT/vendor/qemu/accel/hvf/entitlements.plist" "$STAGE$PREFIX/bin/$QEMU_BINARY" - fi - ID="$(date +%Y%m%d-%H%M%S)-$COMMIT$ARM_SUFFIX" + ID="$(date +%Y%m%d-%H%M%S)-$COMMIT" mkdir -p "$DATA/qemu" mv "$STAGE$PREFIX" "$DATA/qemu/$ID" rm -rf "$STAGE" @@ -527,20 +458,6 @@ say "Installing reims-ctl (cargo install)" (cd "$ROOT" && CARGO_TARGET_DIR="$CACHE/ctl-target" cargo install --locked --force --quiet --path crates/reims-ctl) BIN="${CARGO_INSTALL_ROOT:-${CARGO_HOME:-$HOME/.cargo}}/bin/reims-ctl" [[ -x "$BIN" ]] || die "cargo install left no $BIN" -if [[ $OS == Darwin ]]; then - ent="$CACHE/reims-ctl.entitlements" - cat >"$ent" <<'EOF' - - - - - com.apple.security.virtualization - - - -EOF - codesign -s - -f --entitlements "$ent" "$BIN" 2>/dev/null -fi "$BIN" __record-install --repo "$ROOT" --qemu "$QEMU_DIR" --commit "$COMMIT" echo