blob: d1b0b9975efffee3fdae8ae6a45a20b6d0ddfd3d [file] [log] [blame]
Alan Stokesa2869d22021-09-22 09:06:41 +01001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alan Stokes6b2d0a82021-09-29 11:30:39 +010017//! Manages running instances of the CompOS VM. At most one instance should be running at
18//! a time, started on demand.
Alan Stokesa2869d22021-09-22 09:06:41 +010019
Alan Stokes6b2d0a82021-09-29 11:30:39 +010020use crate::instance_starter::{CompOsInstance, InstanceStarter};
21use android_system_virtualizationservice::aidl::android::system::virtualizationservice;
Alan Stokes8d351602023-03-23 16:44:58 +000022use anyhow::{anyhow, bail, Context, Result};
Alan Stokes0e82b502022-08-08 14:44:48 +010023use binder::Strong;
David Brazdil7d1e5ec2023-02-06 17:56:29 +000024use compos_common::compos_client::{VmCpuTopology, VmParameters};
David Brazdil025c7cc2023-02-06 16:14:23 +000025use compos_common::{CURRENT_INSTANCE_DIR, TEST_INSTANCE_DIR};
Alan Stokes8d351602023-03-23 16:44:58 +000026use log::info;
27use rustutils::system_properties;
28use std::str::FromStr;
Alan Stokesa2869d22021-09-22 09:06:41 +010029use std::sync::{Arc, Mutex, Weak};
Alan Stokes6b2d0a82021-09-29 11:30:39 +010030use virtualizationservice::IVirtualizationService::IVirtualizationService;
Alan Stokesa2869d22021-09-22 09:06:41 +010031
Alan Stokes69c610f2021-09-27 14:03:31 +010032pub struct InstanceManager {
33 service: Strong<dyn IVirtualizationService>,
34 state: Mutex<State>,
35}
Alan Stokesa2869d22021-09-22 09:06:41 +010036
37impl InstanceManager {
Alan Stokes69c610f2021-09-27 14:03:31 +010038 pub fn new(service: Strong<dyn IVirtualizationService>) -> Self {
39 Self { service, state: Default::default() }
40 }
41
Alan Stokes93863602022-08-03 17:23:25 +010042 pub fn start_current_instance(&self) -> Result<CompOsInstance> {
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080043 let mut vm_parameters = new_vm_parameters()?;
Seungjae Yooa61a8672023-04-10 14:19:14 +090044 vm_parameters.name = String::from("Composd");
Victor Hsieha61ec2e2022-09-21 16:25:27 -070045 vm_parameters.prefer_staged = true;
Alan Stokes6542fdd2022-02-17 15:21:46 +000046 self.start_instance(CURRENT_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010047 }
48
Inseob Kim4657d0e2024-11-28 13:34:10 +090049 pub fn start_test_instance(&self, prefer_staged: bool, os: &str) -> Result<CompOsInstance> {
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080050 let mut vm_parameters = new_vm_parameters()?;
Seungjae Yooa61a8672023-04-10 14:19:14 +090051 vm_parameters.name = String::from("ComposdTest");
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080052 vm_parameters.debug_mode = true;
Victor Hsieha61ec2e2022-09-21 16:25:27 -070053 vm_parameters.prefer_staged = prefer_staged;
Inseob Kim4657d0e2024-11-28 13:34:10 +090054 vm_parameters.os = os.to_owned();
Alan Stokesd21764c2021-10-25 15:33:40 +010055 self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
Alan Stokes388b88a2021-10-13 16:03:17 +010056 }
57
Alan Stokesd21764c2021-10-25 15:33:40 +010058 fn start_instance(
59 &self,
60 instance_name: &str,
61 vm_parameters: VmParameters,
Alan Stokes93863602022-08-03 17:23:25 +010062 ) -> Result<CompOsInstance> {
Alan Stokes69c610f2021-09-27 14:03:31 +010063 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010064 state.mark_starting()?;
65 // Don't hold the lock while we start the instance to avoid blocking other callers.
66 drop(state);
67
Alan Stokesd21764c2021-10-25 15:33:40 +010068 let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
Alan Stokes93863602022-08-03 17:23:25 +010069 let instance = instance_starter.start_new_instance(&*self.service);
Alan Stokesa2869d22021-09-22 09:06:41 +010070
Alan Stokes69c610f2021-09-27 14:03:31 +010071 let mut state = self.state.lock().unwrap();
Alan Stokesa2869d22021-09-22 09:06:41 +010072 if let Ok(ref instance) = instance {
Alan Stokes93863602022-08-03 17:23:25 +010073 state.mark_started(instance.get_instance_tracker())?;
Alan Stokesa2869d22021-09-22 09:06:41 +010074 } else {
75 state.mark_stopped();
76 }
77 instance
78 }
Alan Stokes69c610f2021-09-27 14:03:31 +010079}
80
Victor Hsiehda8ca3b2022-01-26 12:36:54 -080081fn new_vm_parameters() -> Result<VmParameters> {
David Brazdil025c7cc2023-02-06 16:14:23 +000082 // By default, dex2oat starts as many threads as there are CPUs. This can be overridden with
83 // a system property. Start the VM with all CPUs and assume the guest will start a suitable
84 // number of dex2oat threads.
David Brazdil7d1e5ec2023-02-06 17:56:29 +000085 let cpu_topology = VmCpuTopology::MatchHost;
Alan Stokes8d351602023-03-23 16:44:58 +000086 let memory_mib = Some(compos_memory_mib()?);
Inseob Kim4657d0e2024-11-28 13:34:10 +090087 let os = "microdroid".to_owned();
88 Ok(VmParameters { cpu_topology, memory_mib, os, ..Default::default() })
Alan Stokes8d351602023-03-23 16:44:58 +000089}
90
91fn compos_memory_mib() -> Result<i32> {
92 // Enough memory to complete odrefresh in the VM, for older versions of ART that don't set the
93 // property explicitly.
Inseob Kim61599a22024-01-30 19:08:54 +090094 const DEFAULT_MEMORY_MIB: u32 = 600;
Alan Stokes8d351602023-03-23 16:44:58 +000095
96 let art_requested_mib =
97 read_property("composd.vm.art.memory_mib.config")?.unwrap_or(DEFAULT_MEMORY_MIB);
98
99 let vm_adjustment_mib = read_property("composd.vm.vendor.memory_mib.config")?.unwrap_or(0);
100
101 info!(
102 "Compilation VM memory: ART requests {art_requested_mib} MiB, \
103 VM adjust is {vm_adjustment_mib}"
104 );
105 art_requested_mib
106 .checked_add_signed(vm_adjustment_mib)
107 .and_then(|x| x.try_into().ok())
108 .context("Invalid vm memory adjustment")
109}
110
111fn read_property<T: FromStr>(name: &str) -> Result<Option<T>> {
112 let str = system_properties::read(name).context("Failed to read {name}")?;
113 str.map(|s| s.parse().map_err(|_| anyhow!("Invalid {name}: {s}"))).transpose()
Victor Hsiehda8ca3b2022-01-26 12:36:54 -0800114}
115
Alan Stokesa2869d22021-09-22 09:06:41 +0100116// Ensures we only run one instance at a time.
117// Valid states:
Alan Stokes93863602022-08-03 17:23:25 +0100118// Starting: is_starting is true, instance_tracker is None.
119// Started: is_starting is false, instance_tracker is Some(x) and there is a strong ref to x.
120// Stopped: is_starting is false and instance_tracker is None or a weak ref to a dropped instance.
Alan Stokes69c610f2021-09-27 14:03:31 +0100121// The panic calls here should never happen, unless the code above in InstanceManager is buggy.
122// In particular nothing the client does should be able to trigger them.
Alan Stokesa2869d22021-09-22 09:06:41 +0100123#[derive(Default)]
124struct State {
Alan Stokes93863602022-08-03 17:23:25 +0100125 instance_tracker: Option<Weak<()>>,
Alan Stokesa2869d22021-09-22 09:06:41 +0100126 is_starting: bool,
127}
128
129impl State {
130 // Move to Starting iff we are Stopped.
131 fn mark_starting(&mut self) -> Result<()> {
132 if self.is_starting {
133 bail!("An instance is already starting");
134 }
Alan Stokes93863602022-08-03 17:23:25 +0100135 if let Some(weak) = &self.instance_tracker {
Alan Stokesa2869d22021-09-22 09:06:41 +0100136 if weak.strong_count() != 0 {
137 bail!("An instance is already running");
138 }
139 }
Alan Stokes93863602022-08-03 17:23:25 +0100140 self.instance_tracker = None;
Alan Stokesa2869d22021-09-22 09:06:41 +0100141 self.is_starting = true;
142 Ok(())
143 }
144
145 // Move from Starting to Stopped.
146 fn mark_stopped(&mut self) {
Alan Stokes93863602022-08-03 17:23:25 +0100147 if !self.is_starting || self.instance_tracker.is_some() {
Alan Stokesa2869d22021-09-22 09:06:41 +0100148 panic!("Tried to mark stopped when not starting");
149 }
150 self.is_starting = false;
151 }
152
153 // Move from Starting to Started.
Alan Stokes93863602022-08-03 17:23:25 +0100154 fn mark_started(&mut self, instance_tracker: &Arc<()>) -> Result<()> {
Alan Stokesa2869d22021-09-22 09:06:41 +0100155 if !self.is_starting {
156 panic!("Tried to mark started when not starting")
157 }
Alan Stokes93863602022-08-03 17:23:25 +0100158 if self.instance_tracker.is_some() {
Alan Stokesa2869d22021-09-22 09:06:41 +0100159 panic!("Attempted to mark started when already started");
160 }
161 self.is_starting = false;
Alan Stokes93863602022-08-03 17:23:25 +0100162 self.instance_tracker = Some(Arc::downgrade(instance_tracker));
Alan Stokesa2869d22021-09-22 09:06:41 +0100163 Ok(())
164 }
Alan Stokesa2869d22021-09-22 09:06:41 +0100165}