Skip to main content

underhill_core/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! This module implements the interactive control process and the entry point
5//! for the underhill environment.
6
7#![cfg(target_os = "linux")]
8#![expect(missing_docs)]
9#![forbid(unsafe_code)]
10
11mod diag;
12mod dispatch;
13mod emuplat;
14mod get_tracing;
15mod inspect_internal;
16mod inspect_proc;
17mod livedump;
18mod loader;
19mod nvme_manager;
20mod options;
21mod reference_time;
22mod servicing;
23mod threadpool_vm_task_backend;
24mod vmbus_relay_unit;
25mod vmgs_logger;
26mod vp;
27mod vpci;
28mod worker;
29mod wrapped_partition;
30
31// `pub` so that the missing_docs warning fires for options without
32// documentation.
33pub use options::Options;
34
35use crate::diag::DiagWorker;
36use crate::dispatch::UhVmRpc;
37use crate::worker::UnderhillEnvCfg;
38use crate::worker::UnderhillRemoteConsoleCfg;
39use crate::worker::UnderhillVmWorker;
40use crate::worker::UnderhillWorkerParameters;
41use anyhow::Context;
42use bootloader_fdt_parser::BootTimes;
43use cvm_tracing::CVM_ALLOWED;
44use framebuffer::FRAMEBUFFER_SIZE;
45use framebuffer::FramebufferAccess;
46use futures::StreamExt;
47use futures_concurrency::stream::Merge;
48use get_tracing::init_tracing;
49use get_tracing::init_tracing_backend;
50use inspect::Inspect;
51use inspect::SensitivityLevel;
52use mesh::CancelContext;
53use mesh::CancelReason;
54use mesh::MeshPayload;
55use mesh::error::RemoteError;
56use mesh::rpc::Rpc;
57use mesh::rpc::RpcSend;
58use mesh_process::Mesh;
59use mesh_process::ProcessConfig;
60use mesh_process::try_run_mesh_host;
61use mesh_tracing::RemoteTracer;
62use mesh_tracing::TracingBackend;
63use mesh_worker::RegisteredWorkers;
64use mesh_worker::WorkerEvent;
65use mesh_worker::WorkerHandle;
66use mesh_worker::WorkerHost;
67use mesh_worker::WorkerHostRunner;
68use mesh_worker::launch_local_worker;
69use mesh_worker::register_workers;
70use pal_async::DefaultDriver;
71use pal_async::DefaultPool;
72use pal_async::task::Spawn;
73#[cfg(feature = "profiler")]
74use profiler_worker::ProfilerWorker;
75#[cfg(feature = "profiler")]
76use profiler_worker::ProfilerWorkerParameters;
77use std::time::Duration;
78use vmsocket::VmAddress;
79use vmsocket::VmListener;
80use vnc_worker_defs::VncParameters;
81
82fn new_underhill_remote_console_cfg(
83    framebuffer_gpa_base: Option<u64>,
84) -> anyhow::Result<(
85    UnderhillRemoteConsoleCfg,
86    Option<FramebufferAccess>,
87    Option<mesh::Receiver<Vec<video_core::DirtyRect>>>,
88)> {
89    if let Some(framebuffer_gpa_base) = framebuffer_gpa_base {
90        // Underhill accesses the framebuffer by using /dev/mshv_vtl_low to read
91        // from a second mapping placed after the end of RAM at a static
92        // location specified by the host.
93        //
94        // Open the file directly rather than use the `hcl` crate to avoid
95        // leaking `hcl` stuff into this crate.
96        //
97        // FUTURE: use an approach that doesn't require double mapping the
98        // framebuffer from the host.
99        let gpa_fd = fs_err::OpenOptions::new()
100            .read(true)
101            .write(true)
102            .open("/dev/mshv_vtl_low")
103            .context("failed to open gpa device")?;
104
105        let vram = sparse_mmap::new_mappable_from_file(gpa_fd.file(), true, false)?;
106        let (fb, fba) = framebuffer::framebuffer(vram, FRAMEBUFFER_SIZE, framebuffer_gpa_base)
107            .context("allocating framebuffer")?;
108        tracing::debug!("framebuffer_gpa_base: {:#x}", framebuffer_gpa_base);
109
110        let (dirt_send, dirt_recv) = mesh::channel();
111
112        Ok((
113            UnderhillRemoteConsoleCfg {
114                synth_keyboard: true,
115                synth_mouse: true,
116                synth_video: true,
117                input: mesh::Receiver::new(),
118                framebuffer: Some(fb),
119                dirt_send: Some(dirt_send),
120            },
121            Some(fba),
122            Some(dirt_recv),
123        ))
124    } else {
125        Ok((
126            UnderhillRemoteConsoleCfg {
127                synth_keyboard: false,
128                synth_mouse: false,
129                synth_video: false,
130                input: mesh::Receiver::new(),
131                framebuffer: None,
132                dirt_send: None,
133            },
134            None,
135            None,
136        ))
137    }
138}
139
140pub fn main() -> anyhow::Result<()> {
141    // Install a panic hook to prefix the current async task name before the
142    // standard panic output.
143    install_task_name_panic_hook();
144
145    if let Some(path) = std::env::var_os("OPENVMM_WRITE_SAVED_STATE_PROTO") {
146        if cfg!(debug_assertions) {
147            mesh::payload::protofile::DescriptorWriter::new(
148                vmcore::save_restore::saved_state_roots(),
149            )
150            .write_to_path(path)
151            .context("failed to write protobuf descriptors")?;
152            return Ok(());
153        } else {
154            // The generated code for this is too large for release builds.
155            anyhow::bail!(".proto output only supported in debug builds");
156        }
157    }
158
159    // FUTURE: create and use the affinitized threadpool here.
160    let (_, tracing_driver) = DefaultPool::spawn_on_thread("tracing");
161
162    // Try to run as a worker host, sending a remote tracer that will forward
163    // tracing events back to the initial process for logging to the host. See
164    // [`get_tracing`] doc comments for more details.
165    //
166    // On success the worker runs to completion and then exits the process (does
167    // not return). Any worker host setup errors are return and bubbled up.
168    try_run_mesh_host("underhill", {
169        let tracing_driver = tracing_driver.clone();
170        async |params: MeshHostParams| {
171            if let Some(remote_tracer) = params.tracer {
172                init_tracing(tracing_driver, remote_tracer).context("failed to init tracing")?;
173            }
174            params.runner.run(RegisteredWorkers).await;
175            Ok(())
176        }
177    })?;
178
179    // Initialize the tracing backend used by this and all subprocesses.
180    let mut tracing = init_tracing_backend(tracing_driver.clone())?;
181    // Initialize tracing from the backend.
182    init_tracing(tracing_driver, tracing.tracer()).context("failed to init tracing")?;
183    DefaultPool::run_with(|driver| do_main(driver, tracing))
184}
185
186fn install_task_name_panic_hook() {
187    use std::io::Write;
188
189    let panic_hook = std::panic::take_hook();
190    std::panic::set_hook(Box::new(move |info| {
191        pal_async::task::with_current_task_metadata(|metadata| {
192            if let Some(metadata) = metadata {
193                let _ = write!(std::io::stderr(), "task '{}', ", metadata.name());
194            }
195        });
196        // This will proceed with writing "thread ... panicked at ..."
197        panic_hook(info);
198    }));
199}
200
201async fn do_main(driver: DefaultDriver, mut tracing: TracingBackend) -> anyhow::Result<()> {
202    let opt = Options::parse(Vec::new(), Vec::new())?;
203
204    let crate_name = build_info::get().crate_name();
205    let crate_revision = build_info::get().scm_revision();
206    let openhcl_version = build_info::get().openhcl_version();
207    tracing::info!(
208        CVM_ALLOWED,
209        ?crate_name,
210        ?crate_revision,
211        ?openhcl_version,
212        "VMM process"
213    );
214    log_boot_times().context("failure logging boot times")?;
215
216    // Write the current pid to a file.
217    if let Some(pid_path) = &opt.pid {
218        std::fs::write(pid_path, std::process::id().to_string())
219            .with_context(|| format!("failed to write pid to {}", pid_path.display()))?;
220    }
221
222    let mesh = Mesh::new("underhill".to_string()).context("failed to create mesh")?;
223
224    let r = run_control(driver, &mesh, opt, &mut tracing).await;
225    if let Err(err) = &r {
226        tracing::error!(
227            CVM_ALLOWED,
228            error = err.as_ref() as &dyn std::error::Error,
229            "VM failure"
230        );
231    }
232
233    // Wait a few seconds for child processes to terminate and tracing to finish.
234    CancelContext::new()
235        .with_timeout(Duration::from_secs(10))
236        .until_cancelled(async {
237            mesh.shutdown().await;
238            tracing.shutdown().await;
239        })
240        .await
241        .ok();
242
243    r
244}
245
246fn log_boot_times() -> anyhow::Result<()> {
247    fn diff(start: Option<u64>, end: Option<u64>) -> Option<tracing::field::DebugValue<Duration>> {
248        use reference_time::ReferenceTime;
249        Some(tracing::field::debug(
250            ReferenceTime::new(end?).since(ReferenceTime::new(start?))?,
251        ))
252    }
253
254    // Read boot times provided by the bootloader.
255    let BootTimes {
256        start,
257        end,
258        sidecar_start,
259        sidecar_end,
260    } = BootTimes::new().context("failed to parse boot times")?;
261    tracing::info!(
262        CVM_ALLOWED,
263        start,
264        end,
265        sidecar_start,
266        sidecar_end,
267        elapsed = diff(start, end),
268        sidecar_elapsed = diff(sidecar_start, sidecar_end),
269        "boot loader times"
270    );
271    Ok(())
272}
273
274struct DiagState {
275    _worker: WorkerHandle,
276    request_recv: mesh::Receiver<diag_server::DiagRequest>,
277}
278
279impl DiagState {
280    async fn new() -> anyhow::Result<Self> {
281        // Start the diagnostics worker immediately.
282        let (request_send, request_recv) = mesh::channel();
283        let worker = launch_local_worker::<DiagWorker>(diag::DiagWorkerParameters { request_send })
284            .await
285            .context("failed to launch diagnostics worker")?;
286        Ok(Self {
287            _worker: worker,
288            request_recv,
289        })
290    }
291}
292
293#[derive(Inspect)]
294struct Workers {
295    #[inspect(safe)]
296    vm: WorkerHandle,
297    #[inspect(skip)]
298    vm_rpc: mesh::Sender<UhVmRpc>,
299    vnc: Option<WorkerHandle>,
300    #[cfg(feature = "gdb")]
301    gdb: Option<WorkerHandle>,
302}
303
304#[derive(MeshPayload)]
305struct MeshHostParams {
306    tracer: Option<RemoteTracer>,
307    runner: WorkerHostRunner,
308}
309
310async fn launch_mesh_host(
311    mesh: &Mesh,
312    name: &str,
313    tracer: Option<RemoteTracer>,
314) -> anyhow::Result<WorkerHost> {
315    let (host, runner) = mesh_worker::worker_host();
316    mesh.launch_host(ProcessConfig::new(name), MeshHostParams { tracer, runner })
317        .await?;
318    Ok(host)
319}
320
321async fn launch_workers(
322    mesh: &Mesh,
323    tracing: &mut TracingBackend,
324    control_send: mesh::Sender<ControlRequest>,
325    opt: Options,
326) -> anyhow::Result<Workers> {
327    let env_cfg = UnderhillEnvCfg {
328        vmbus_max_version: opt.vmbus_max_version,
329        vmbus_enable_mnf: opt.vmbus_enable_mnf,
330        vmbus_force_confidential_external_memory: opt.vmbus_force_confidential_external_memory,
331        vmbus_channel_unstick_delay: (opt.vmbus_channel_unstick_delay_ms != 0)
332            .then(|| Duration::from_millis(opt.vmbus_channel_unstick_delay_ms)),
333        cmdline_append: opt.cmdline_append.clone(),
334        reformat_vmgs: opt.reformat_vmgs,
335        vtl0_starts_paused: opt.vtl0_starts_paused,
336        emulated_serial_wait_for_rts: opt.serial_wait_for_rts,
337        force_load_vtl0_image: opt.force_load_vtl0_image,
338        nvme_vfio: opt.nvme_vfio,
339        halt_on_guest_halt: opt.halt_on_guest_halt,
340        no_sidecar_hotplug: opt.no_sidecar_hotplug,
341        gdbstub: opt.gdbstub,
342        hide_isolation: opt.hide_isolation,
343        nvme_keep_alive: opt.nvme_keep_alive,
344        mana_keep_alive: opt.mana_keep_alive,
345        nvme_always_flr: opt.nvme_always_flr,
346        test_configuration: opt.test_configuration,
347        disable_uefi_frontpage: opt.disable_uefi_frontpage,
348        default_boot_always_attempt: opt.default_boot_always_attempt,
349        guest_state_lifetime: opt.guest_state_lifetime,
350        guest_state_encryption_policy: opt.guest_state_encryption_policy,
351        efi_diagnostics_log_level: opt.efi_diagnostics_log_level,
352        strict_encryption_policy: opt.strict_encryption_policy,
353        attempt_ak_cert_callback: opt.attempt_ak_cert_callback,
354        enable_vpci_relay: opt.enable_vpci_relay,
355        disable_proxy_redirect: opt.disable_proxy_redirect,
356        disable_lower_vtl_timer_virt: opt.disable_lower_vtl_timer_virt,
357        config_timeout_in_seconds: opt.config_timeout_in_seconds,
358        servicing_timeout_dump_collection_in_ms: opt.servicing_timeout_dump_collection_in_ms,
359    };
360
361    let (mut remote_console_cfg, framebuffer_access, dirty_rect_recv) =
362        new_underhill_remote_console_cfg(opt.framebuffer_gpa_base)?;
363
364    let mut vnc_worker = None;
365    if let Some(framebuffer) = framebuffer_access {
366        let listener = VmListener::bind(VmAddress::vsock_any(opt.vnc_port))
367            .context("failed to bind socket")?;
368
369        let input_send = remote_console_cfg.input.sender();
370
371        let vnc_host = launch_mesh_host(mesh, "vnc", Some(tracing.tracer()))
372            .await
373            .context("spawning vnc process failed")?;
374
375        vnc_worker = Some(
376            vnc_host
377                .launch_worker(
378                    vnc_worker_defs::VNC_WORKER_VMSOCKET,
379                    VncParameters {
380                        listener,
381                        framebuffer,
382                        input_send,
383                        dirty_recv: dirty_rect_recv,
384                        max_clients: 16,
385                        evict_oldest: false,
386                    },
387                )
388                .await?,
389        )
390    }
391
392    #[cfg(feature = "gdb")]
393    let mut gdbstub_worker = None;
394    #[cfg_attr(not(feature = "gdb"), expect(unused_mut))]
395    let mut debugger_rpc = None;
396    #[cfg(feature = "gdb")]
397    if opt.gdbstub {
398        let listener = VmListener::bind(VmAddress::vsock_any(opt.gdbstub_port))
399            .context("failed to bind socket")?;
400
401        let gdb_host = launch_mesh_host(mesh, "gdb", Some(tracing.tracer()))
402            .await
403            .context("failed to spawn gdb host process")?;
404
405        // Get the VP count of this machine. It's too early to read it directly
406        // from IGVM parameters, but the kernel already has the IGVM parsed VP
407        // count via the boot loader anyways.
408        let vp_count =
409            pal::unix::affinity::max_present_cpu().context("failed to get max present cpu")? + 1;
410
411        let (send, recv) = mesh::channel();
412        debugger_rpc = Some(recv);
413        gdbstub_worker = Some(
414            gdb_host
415                .launch_worker(
416                    debug_worker_defs::DEBUGGER_VSOCK_WORKER,
417                    debug_worker_defs::DebuggerParameters {
418                        listener,
419                        req_chan: send,
420                        vp_count,
421                        target_arch: if cfg!(guest_arch = "x86_64") {
422                            debug_worker_defs::TargetArch::X86_64
423                        } else {
424                            debug_worker_defs::TargetArch::Aarch64
425                        },
426                    },
427                )
428                .await?,
429        );
430    }
431    let (vm_rpc, vm_rpc_rx) = mesh::channel();
432
433    // Spawn the worker in a separate process in case the diagnostics server (in
434    // this process) is used to run gdbserver against it, or in case it needs to
435    // be restarted.
436    let host = launch_mesh_host(mesh, "vm", Some(tracing.tracer()))
437        .await
438        .context("failed to launch worker process")?;
439
440    let vm_worker = host
441        .start_worker(
442            worker::UNDERHILL_WORKER,
443            UnderhillWorkerParameters {
444                env_cfg,
445                remote_console_cfg,
446                debugger_rpc,
447                vm_rpc: vm_rpc_rx,
448                control_send,
449            },
450        )
451        .context("failed to launch worker")?;
452
453    Ok(Workers {
454        vm: vm_worker,
455        vm_rpc,
456        vnc: vnc_worker,
457        #[cfg(feature = "gdb")]
458        gdb: gdbstub_worker,
459    })
460}
461
462/// State for inspect only.
463#[derive(Inspect)]
464enum ControlState {
465    WaitingForStart,
466    Starting,
467    Started,
468    Restarting,
469}
470
471#[derive(MeshPayload)]
472pub enum ControlRequest {
473    FlushLogs(Rpc<CancelContext, Result<(), CancelReason>>),
474    MakeWorker(Rpc<String, Result<WorkerHost, RemoteError>>),
475}
476
477async fn run_control(
478    driver: DefaultDriver,
479    mesh: &Mesh,
480    opt: Options,
481    mut tracing: &mut TracingBackend,
482) -> anyhow::Result<()> {
483    let (control_send, mut control_recv) = mesh::channel();
484    let mut control_send = Some(control_send);
485
486    if opt.signal_vtl0_started {
487        signal_vtl0_started(&driver)
488            .await
489            .context("failed to signal vtl0 started")?;
490    }
491
492    let mut diag = DiagState::new().await?;
493
494    let (diag_reinspect_send, mut diag_reinspect_recv) = mesh::channel();
495    #[cfg(feature = "profiler")]
496    let mut profiler_host = None;
497    let mut state;
498    let mut workers = if opt.wait_for_start {
499        state = ControlState::WaitingForStart;
500        None
501    } else {
502        state = ControlState::Starting;
503        let workers = launch_workers(mesh, tracing, control_send.take().unwrap(), opt)
504            .await
505            .context("failed to launch workers")?;
506        Some(workers)
507    };
508
509    enum Event {
510        Diag(diag_server::DiagRequest),
511        Worker(WorkerEvent),
512        Control(ControlRequest),
513    }
514
515    let mut restart_rpc = None;
516    #[cfg(feature = "mem-profile-tracing")]
517    let mut profiler = mem_profile_tracing::HeapProfiler::new();
518    loop {
519        let event = {
520            let mut stream = (
521                (&mut diag.request_recv).map(Event::Diag),
522                (&mut diag_reinspect_recv)
523                    .map(|req| Event::Diag(diag_server::DiagRequest::Inspect(req))),
524                (&mut control_recv).map(Event::Control),
525                futures::stream::select_all(workers.as_mut().map(|w| &mut w.vm)).map(Event::Worker),
526            )
527                .merge();
528
529            let Some(event) = stream.next().await else {
530                break;
531            };
532            event
533        };
534
535        match event {
536            Event::Diag(request) => {
537                match request {
538                    diag_server::DiagRequest::Start(rpc) => {
539                        rpc.handle_failable(async |params| {
540                            if workers.is_some() {
541                                Err(anyhow::anyhow!("workers have already been started"))?;
542                            }
543                            let new_opt = Options::parse(params.args, params.env)
544                                .context("failed to parse new options")?;
545
546                            workers = Some(
547                                launch_workers(
548                                    mesh,
549                                    tracing,
550                                    control_send.take().unwrap(),
551                                    new_opt,
552                                )
553                                .await?,
554                            );
555                            state = ControlState::Starting;
556                            anyhow::Ok(())
557                        })
558                        .await
559                    }
560                    diag_server::DiagRequest::Inspect(deferred) => deferred.respond(|resp| {
561                        resp.sensitivity_field("mesh", SensitivityLevel::Safe, mesh)
562                            .sensitivity_field_mut("trace", SensitivityLevel::Safe, &mut tracing)
563                            .sensitivity_field(
564                                "build_info",
565                                SensitivityLevel::Safe,
566                                build_info::get(),
567                            )
568                            .sensitivity_child(
569                                "proc",
570                                SensitivityLevel::Safe,
571                                inspect_proc::inspect_proc,
572                            )
573                            .sensitivity_field("control_state", SensitivityLevel::Safe, &state)
574                            // This node can not be renamed due to stability guarantees.
575                            // See the comment at the top of inspect_internal for more details.
576                            .sensitivity_child("uhdiag", SensitivityLevel::Safe, |req| {
577                                inspect_internal::inspect_internal_diagnostics(
578                                    req,
579                                    &diag_reinspect_send,
580                                    &driver,
581                                )
582                            });
583
584                        resp.merge(&workers);
585                    }),
586                    diag_server::DiagRequest::Crash(pid) => {
587                        mesh.crash(pid);
588                    }
589                    diag_server::DiagRequest::Restart(rpc) => {
590                        let Some(workers) = &mut workers else {
591                            rpc.complete(Err(RemoteError::new(anyhow::anyhow!(
592                                "worker has not been started yet"
593                            ))));
594                            continue;
595                        };
596
597                        let r = async {
598                            if restart_rpc.is_some() {
599                                anyhow::bail!("previous restart still in progress");
600                            }
601
602                            let host = launch_mesh_host(mesh, "vm", Some(tracing.tracer()))
603                                .await
604                                .context("failed to launch worker process")?;
605
606                            workers.vm.restart(&host);
607                            Ok(())
608                        }
609                        .await;
610
611                        if r.is_err() {
612                            rpc.complete(r.map_err(RemoteError::new));
613                        } else {
614                            state = ControlState::Restarting;
615                            restart_rpc = Some(rpc);
616                        }
617                    }
618                    diag_server::DiagRequest::Pause(rpc) => {
619                        let Some(workers) = &mut workers else {
620                            rpc.complete(Err(RemoteError::new(anyhow::anyhow!(
621                                "worker has not been started yet"
622                            ))));
623                            continue;
624                        };
625
626                        // create the req future output the spawn, so that
627                        // we don't need to clone + move vm_rpc.
628                        let req = workers.vm_rpc.call(UhVmRpc::Pause, ());
629
630                        // FUTURE: consider supporting cancellation
631                        driver
632                            .spawn("diag-pause", async move {
633                                let was_paused = req.await.expect("failed to pause VM");
634                                rpc.handle_failable_sync(|_| {
635                                    if !was_paused {
636                                        Err(anyhow::anyhow!("VM is already paused"))
637                                    } else {
638                                        Ok(())
639                                    }
640                                });
641                            })
642                            .detach();
643                    }
644                    diag_server::DiagRequest::PacketCapture(rpc) => {
645                        let Some(workers) = &mut workers else {
646                            rpc.complete(Err(RemoteError::new(anyhow::anyhow!(
647                                "worker has not been started yet"
648                            ))));
649                            continue;
650                        };
651
652                        workers.vm_rpc.send(UhVmRpc::PacketCapture(rpc));
653                    }
654                    #[cfg(feature = "mem-profile-tracing")]
655                    diag_server::DiagRequest::MemoryProfileTrace(rpc) => {
656                        rpc.handle_failable(async |pid| {
657                            if pid == std::process::id() as i32 {
658                                anyhow::Ok(profiler.capture_and_restart())
659                            } else {
660                                let Some(workers) = &mut workers else {
661                                    anyhow::bail!("workers have not been started yet");
662                                };
663
664                                let result = workers
665                                    .vm_rpc
666                                    .call(UhVmRpc::MemoryProfileTrace, pid)
667                                    .await
668                                    .context("failed to get memory profile from worker process")?;
669                                Ok(result?)
670                            }
671                        })
672                        .await
673                    }
674                    diag_server::DiagRequest::Resume(rpc) => {
675                        let Some(workers) = &mut workers else {
676                            rpc.complete(Err(RemoteError::new(anyhow::anyhow!(
677                                "worker has not been started yet"
678                            ))));
679                            continue;
680                        };
681
682                        let was_resumed = workers
683                            .vm_rpc
684                            .call(UhVmRpc::Resume, ())
685                            .await
686                            .context("failed to resumed VM")?;
687
688                        let was_halted = workers
689                            .vm_rpc
690                            .call(UhVmRpc::ClearHalt, ())
691                            .await
692                            .context("failed to clear halt from VPs")?;
693
694                        rpc.handle_sync(|_| {
695                            if was_resumed || was_halted {
696                                Ok(())
697                            } else {
698                                Err(RemoteError::new(anyhow::anyhow!("VM is currently running")))
699                            }
700                        });
701                    }
702                    diag_server::DiagRequest::Save(rpc) => {
703                        let Some(workers) = &mut workers else {
704                            rpc.complete(Err(RemoteError::new(anyhow::anyhow!(
705                                "worker has not been started yet"
706                            ))));
707                            continue;
708                        };
709
710                        workers.vm_rpc.send(UhVmRpc::Save(rpc));
711                    }
712                    #[cfg(feature = "profiler")]
713                    diag_server::DiagRequest::Profile(rpc) => {
714                        let (rpc_params, rpc_sender) = rpc.split();
715                        // Create profiler host if there is none created before
716                        if profiler_host.is_none() {
717                            match launch_mesh_host(mesh, "profiler", Some(tracing.tracer()))
718                                .await
719                                .context("failed to launch profiler host")
720                            {
721                                Ok(host) => {
722                                    profiler_host = Some(host);
723                                }
724                                Err(e) => {
725                                    rpc_sender.complete(Err(RemoteError::new(e)));
726                                    continue;
727                                }
728                            }
729                        }
730
731                        let profiling_duration = rpc_params.duration;
732                        let host = profiler_host.as_ref().unwrap();
733                        let mut profiler_worker;
734                        match host
735                            .launch_worker(
736                                profiler_worker::PROFILER_WORKER,
737                                ProfilerWorkerParameters {
738                                    profiler_request: rpc_params,
739                                },
740                            )
741                            .await
742                        {
743                            Ok(worker) => {
744                                profiler_worker = worker;
745                            }
746                            Err(e) => {
747                                rpc_sender.complete(Err(RemoteError::new(e)));
748                                continue;
749                            }
750                        }
751
752                        driver
753                            .spawn("profiler_worker", async move {
754                                let result = CancelContext::new()
755                                    .with_timeout(Duration::from_secs(profiling_duration + 30))
756                                    .until_cancelled(profiler_worker.join())
757                                    .await
758                                    .context("profiler worker cancelled")
759                                    .and_then(|result| result.context("profiler worker failed"))
760                                    .map_err(RemoteError::new);
761
762                                rpc_sender.complete(result);
763                            })
764                            .detach();
765                    }
766                }
767            }
768            Event::Worker(event) => match event {
769                WorkerEvent::Started => {
770                    if let Some(response) = restart_rpc.take() {
771                        tracing::info!(CVM_ALLOWED, "restart complete");
772                        response.complete(Ok(()));
773                    } else {
774                        tracing::info!(CVM_ALLOWED, "vm worker started");
775                    }
776                    state = ControlState::Started;
777                }
778                WorkerEvent::Stopped => {
779                    anyhow::bail!("worker unexpectedly stopped");
780                }
781                WorkerEvent::Failed(err) => {
782                    return Err(anyhow::Error::from(err)).context("vm worker failed");
783                }
784                WorkerEvent::RestartFailed(err) => {
785                    tracing::error!(
786                        CVM_ALLOWED,
787                        error = &err as &dyn std::error::Error,
788                        "restart failed"
789                    );
790                    restart_rpc.take().unwrap().complete(Err(err));
791                    state = ControlState::Started;
792                }
793            },
794            Event::Control(req) => match req {
795                ControlRequest::FlushLogs(rpc) => {
796                    rpc.handle(async |mut ctx| {
797                        tracing::info!(CVM_ALLOWED, "flushing logs");
798                        ctx.until_cancelled(tracing.flush()).await?;
799                        Ok(())
800                    })
801                    .await
802                }
803                ControlRequest::MakeWorker(rpc) => {
804                    rpc.handle_failable(async |name| {
805                        launch_mesh_host(mesh, &name, Some(tracing.tracer())).await
806                    })
807                    .await
808                }
809            },
810        }
811    }
812
813    Ok(())
814}
815
816async fn signal_vtl0_started(driver: &DefaultDriver) -> anyhow::Result<()> {
817    tracing::info!(CVM_ALLOWED, "signaling vtl0 started early");
818    let (client, task) = guest_emulation_transport::spawn_get_worker(driver.clone())
819        .await
820        .context("failed to spawn GET")?;
821    client.complete_start_vtl0(None).await;
822    // Disconnect the GET so that it can be reused.
823    drop(client);
824    task.await.unwrap();
825    tracing::info!(CVM_ALLOWED, "signaled vtl0 start");
826    Ok(())
827}
828
829// The "base" workers for Underhill. Other workers are defined in the
830// `underhill_resources` crate.
831//
832// FUTURE: split these workers into separate crates and move them to
833// `underhill_resources`, too.
834register_workers! {
835    UnderhillVmWorker,
836    DiagWorker,
837    #[cfg(feature = "profiler")]
838    ProfilerWorker,
839}