• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 //! Manages running instances of the CompOS VM. At most one instance should be running at
18 //! a time, started on demand.
19 
20 use crate::instance_starter::{CompOsInstance, InstanceStarter};
21 use android_system_virtualizationservice::aidl::android::system::virtualizationservice;
22 use anyhow::{anyhow, bail, Context, Result};
23 use binder::Strong;
24 use compos_common::compos_client::{VmCpuTopology, VmParameters};
25 use compos_common::{CURRENT_INSTANCE_DIR, TEST_INSTANCE_DIR};
26 use log::info;
27 use rustutils::system_properties;
28 use std::str::FromStr;
29 use std::sync::{Arc, Mutex, Weak};
30 use virtualizationservice::IVirtualizationService::IVirtualizationService;
31 
32 pub struct InstanceManager {
33     service: Strong<dyn IVirtualizationService>,
34     state: Mutex<State>,
35 }
36 
37 impl InstanceManager {
new(service: Strong<dyn IVirtualizationService>) -> Self38     pub fn new(service: Strong<dyn IVirtualizationService>) -> Self {
39         Self { service, state: Default::default() }
40     }
41 
start_current_instance(&self, os: &str) -> Result<CompOsInstance>42     pub fn start_current_instance(&self, os: &str) -> Result<CompOsInstance> {
43         let mut vm_parameters = new_vm_parameters()?;
44         vm_parameters.name = String::from("Composd");
45         vm_parameters.prefer_staged = true;
46         vm_parameters.os = os.to_owned();
47         self.start_instance(CURRENT_INSTANCE_DIR, vm_parameters)
48     }
49 
start_test_instance(&self, prefer_staged: bool, os: &str) -> Result<CompOsInstance>50     pub fn start_test_instance(&self, prefer_staged: bool, os: &str) -> Result<CompOsInstance> {
51         let mut vm_parameters = new_vm_parameters()?;
52         vm_parameters.name = String::from("ComposdTest");
53         vm_parameters.debug_mode = true;
54         vm_parameters.prefer_staged = prefer_staged;
55         vm_parameters.os = os.to_owned();
56         self.start_instance(TEST_INSTANCE_DIR, vm_parameters)
57     }
58 
start_instance( &self, instance_name: &str, vm_parameters: VmParameters, ) -> Result<CompOsInstance>59     fn start_instance(
60         &self,
61         instance_name: &str,
62         vm_parameters: VmParameters,
63     ) -> Result<CompOsInstance> {
64         let mut state = self.state.lock().unwrap();
65         state.mark_starting()?;
66         // Don't hold the lock while we start the instance to avoid blocking other callers.
67         drop(state);
68 
69         let instance_starter = InstanceStarter::new(instance_name, vm_parameters);
70         let instance = instance_starter.start_new_instance(&*self.service);
71 
72         let mut state = self.state.lock().unwrap();
73         if let Ok(ref instance) = instance {
74             state.mark_started(instance.get_instance_tracker())?;
75         } else {
76             state.mark_stopped();
77         }
78         instance
79     }
80 }
81 
new_vm_parameters() -> Result<VmParameters>82 fn new_vm_parameters() -> Result<VmParameters> {
83     // By default, dex2oat starts as many threads as there are CPUs. This can be overridden with
84     // a system property. Start the VM with all CPUs and assume the guest will start a suitable
85     // number of dex2oat threads.
86     let cpu_topology = VmCpuTopology::MatchHost;
87     let memory_mib = Some(compos_memory_mib()?);
88     let os = "microdroid".to_owned();
89     Ok(VmParameters { cpu_topology, memory_mib, os, ..Default::default() })
90 }
91 
compos_memory_mib() -> Result<i32>92 fn compos_memory_mib() -> Result<i32> {
93     // Enough memory to complete odrefresh in the VM, for older versions of ART that don't set the
94     // property explicitly.
95     const DEFAULT_MEMORY_MIB: u32 = 600;
96 
97     let art_requested_mib =
98         read_property("composd.vm.art.memory_mib.config")?.unwrap_or(DEFAULT_MEMORY_MIB);
99 
100     let vm_adjustment_mib = read_property("composd.vm.vendor.memory_mib.config")?.unwrap_or(0);
101 
102     info!(
103         "Compilation VM memory: ART requests {art_requested_mib} MiB, \
104         VM adjust is {vm_adjustment_mib}"
105     );
106     art_requested_mib
107         .checked_add_signed(vm_adjustment_mib)
108         .and_then(|x| x.try_into().ok())
109         .context("Invalid vm memory adjustment")
110 }
111 
read_property<T: FromStr>(name: &str) -> Result<Option<T>>112 fn read_property<T: FromStr>(name: &str) -> Result<Option<T>> {
113     let str = system_properties::read(name).context("Failed to read {name}")?;
114     str.map(|s| s.parse().map_err(|_| anyhow!("Invalid {name}: {s}"))).transpose()
115 }
116 
117 // Ensures we only run one instance at a time.
118 // Valid states:
119 // Starting: is_starting is true, instance_tracker is None.
120 // Started: is_starting is false, instance_tracker is Some(x) and there is a strong ref to x.
121 // Stopped: is_starting is false and instance_tracker is None or a weak ref to a dropped instance.
122 // The panic calls here should never happen, unless the code above in InstanceManager is buggy.
123 // In particular nothing the client does should be able to trigger them.
124 #[derive(Default)]
125 struct State {
126     instance_tracker: Option<Weak<()>>,
127     is_starting: bool,
128 }
129 
130 impl State {
131     // Move to Starting iff we are Stopped.
mark_starting(&mut self) -> Result<()>132     fn mark_starting(&mut self) -> Result<()> {
133         if self.is_starting {
134             bail!("An instance is already starting");
135         }
136         if let Some(weak) = &self.instance_tracker {
137             if weak.strong_count() != 0 {
138                 bail!("An instance is already running");
139             }
140         }
141         self.instance_tracker = None;
142         self.is_starting = true;
143         Ok(())
144     }
145 
146     // Move from Starting to Stopped.
mark_stopped(&mut self)147     fn mark_stopped(&mut self) {
148         if !self.is_starting || self.instance_tracker.is_some() {
149             panic!("Tried to mark stopped when not starting");
150         }
151         self.is_starting = false;
152     }
153 
154     // Move from Starting to Started.
mark_started(&mut self, instance_tracker: &Arc<()>) -> Result<()>155     fn mark_started(&mut self, instance_tracker: &Arc<()>) -> Result<()> {
156         if !self.is_starting {
157             panic!("Tried to mark started when not starting")
158         }
159         if self.instance_tracker.is_some() {
160             panic!("Attempted to mark started when already started");
161         }
162         self.is_starting = false;
163         self.instance_tracker = Some(Arc::downgrade(instance_tracker));
164         Ok(())
165     }
166 }
167