device_virtio_pmem/
ext2.rs

1// Copyright 2024 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Provides a function to launches a process of creating ext2 filesystem on memory region
6//! asynchronously for pmem-ext2 device.
7//!
8//! The ext2 file system is created in the memory area for pmem by the following three processes:
9//! (a). The main process
10//! (b). ext2 process launched by the `launch()` below.
11//! (c). The virtio-pmem process
12//!
13//! By executing mkfs in the multiple processes, mkfs won't block other initialization steps. Also,
14//! we can use different seccomp policy for (b) and (c).
15//!
16//! The overall workflow is like the followings:
17//! 1. At (a): `launch()` is called from (a)
18//! 2. At (a): (b) is forked from (a) in `launch()`
19//! 3. At (b): The given directory is traversed and metadata is constructed.
20//! 4. At (b): File descriptors are sent to (a) with `VmMemoryRequest::MmapAndRegisterMemory`.
21//! 5. At (a): mmap() for the file descriptors are called. The reply is sent to (b).
22//! 6. At (b): memory slot number is sent to (c).
23//! 7. At (c): device activation finished.
24
25use std::path::Path;
26use std::path::PathBuf;
27
28use anyhow::Context;
29use anyhow::Result;
30use base::error;
31use base::AsRawDescriptor;
32use base::Pid;
33use base::SharedMemory;
34use base::Tube;
35use devices::virtio::VirtioDevice;
36use devices::VirtioDeviceArgs;
37use devices::VirtioDeviceModule;
38use jail::create_base_minijail;
39use jail::create_sandbox_minijail;
40use jail::fork_process;
41use jail::JailConfig;
42use jail::RunAsUser;
43use jail::SandboxConfig;
44use minijail::Minijail;
45use resources::Alloc;
46use resources::AllocOptions;
47use serde::Deserialize;
48use serde::Serialize;
49use vm_control::api::VmMemoryClient;
50use vm_control::AnyControlTube;
51use vm_control::VmMemoryFileMapping;
52use vm_memory::GuestAddress;
53
54use crate::MemSlotConfig;
55use crate::Pmem;
56use crate::PmemConfig;
57
58/// Starts a process to create an ext2 filesystem on a given shared memory region.
59fn launch(
60    mapping_address: GuestAddress,
61    vm_memory_client: VmMemoryClient,
62    device_tube: Tube, // Connects to a virtio device to send a memory slot number.
63    path: &Path,
64    ugid: &(Option<u32>, Option<u32>),
65    ugid_map: (&str, &str),
66    mut builder: ext2::Builder,
67    jail_config: Option<&JailConfig>,
68) -> Result<Pid> {
69    let max_open_files = base::linux::max_open_files()
70        .context("failed to get max number of open files")?
71        .rlim_max;
72
73    let jail = if let Some(jail_config) = jail_config {
74        let mut config = SandboxConfig::new(jail_config, "virtual_ext2");
75        config.limit_caps = false;
76        config.ugid_map = Some(ugid_map);
77        // We want bind mounts from the parent namespaces to propagate into the mkfs's
78        // namespace.
79        config.remount_mode = Some(libc::MS_SLAVE);
80        config.run_as = match *ugid {
81            (None, None) => RunAsUser::Unspecified,
82            (uid_opt, gid_opt) => RunAsUser::Specified(uid_opt.unwrap_or(0), gid_opt.unwrap_or(0)),
83        };
84        create_sandbox_minijail(path, max_open_files, &config)?
85    } else {
86        create_base_minijail(path, max_open_files)?
87    };
88
89    // Use "/" in the new mount namespace as the root for mkfs.
90    builder.root_dir = Some(std::path::PathBuf::from("/"));
91
92    let shm = SharedMemory::new("pmem_ext2_shm", builder.size as u64)
93        .context("failed to create shared memory")?;
94    let mut keep_rds = vec![
95        shm.as_raw_descriptor(),
96        vm_memory_client.as_raw_descriptor(),
97        device_tube.as_raw_descriptor(),
98    ];
99    base::syslog::push_descriptors(&mut keep_rds);
100
101    let child_process = fork_process(jail, keep_rds, Some(String::from("mkfs process")), || {
102        if let Err(e) = mkfs_callback(vm_memory_client, mapping_address, device_tube, builder, shm)
103        {
104            error!("failed to create file system: {:#}", e);
105            // SAFETY: exit() is trivially safe.
106            unsafe { libc::exit(1) };
107        }
108    })
109    .context("failed to fork a process for mkfs")?;
110    Ok(child_process.pid)
111}
112
113/// A callback to create a ext2 file system on `shm`.
114/// This is supposed to be run in a jailed child process so operations are sandboxed and limited.
115fn mkfs_callback(
116    mem_client: VmMemoryClient,
117    mapping_address: GuestAddress,
118    device_tube: Tube, // Connects to a virtio device to send a memory slot number.
119    builder: ext2::Builder,
120    shm: SharedMemory,
121) -> Result<()> {
122    let file_mappings = builder
123        .build_on_shm(&shm)
124        .context("failed to build memory region")?
125        .build_mmap_info()
126        .context("failed to build ext2")?
127        .mapping_info;
128
129    let file_mapping_info: Vec<_> = file_mappings
130        .into_iter()
131        .map(|info| VmMemoryFileMapping {
132            file: info.file,
133            length: info.length,
134            mem_offset: info.mem_offset,
135            file_offset: info.file_offset as u64,
136        })
137        .collect();
138
139    let slot = mem_client
140        .mmap_and_register_memory(mapping_address, shm, file_mapping_info)
141        .context("failed to request mmaping and registering memory")?;
142    device_tube
143        .send(&slot)
144        .context("failed to send VmMemoryRequest::RegisterMemory")?;
145    Ok(())
146}
147
148#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
149#[serde(deny_unknown_fields)]
150pub struct PmemExt2Option {
151    pub path: PathBuf,
152    pub blocks_per_group: u32,
153    pub inodes_per_group: u32,
154    pub size: u32,
155    pub ugid: (Option<u32>, Option<u32>),
156    pub uid_map: String,
157    pub gid_map: String,
158}
159
160impl Default for PmemExt2Option {
161    fn default() -> Self {
162        let blocks_per_group = 4096;
163        let inodes_per_group = 1024;
164        let size = ext2::BLOCK_SIZE as u32 * blocks_per_group; // only one block group
165        Self {
166            path: Default::default(),
167            blocks_per_group,
168            inodes_per_group,
169            size,
170            ugid: (None, None),
171            // SAFETY: geteuid never fails.
172            uid_map: format!("0 {} 1", unsafe { libc::geteuid() }),
173            // SAFETY: getegid never fails.
174            gid_map: format!("0 {} 1", unsafe { libc::getegid() }),
175        }
176    }
177}
178
179#[derive(Clone, Debug, Serialize, Deserialize)]
180pub struct VirtioPmemExt2Module {
181    pub pmem_ext2_option: PmemExt2Option,
182    pub index: usize,
183}
184
185impl VirtioDeviceModule for VirtioPmemExt2Module {
186    fn sort_name(&self) -> &'static str {
187        "pmem_ext2"
188    }
189
190    fn create(&self, cx: &mut VirtioDeviceArgs<'_>) -> Result<Box<dyn VirtioDevice>> {
191        let (pmem_ext2_host_tube, pmem_ext2_device_tube) =
192            Tube::pair().context("failed to create tube")?;
193        let vm_memory_client = VmMemoryClient::new(pmem_ext2_device_tube);
194        (cx.add_control_tube)(AnyControlTube::VmMemoryTube {
195            tube: pmem_ext2_host_tube,
196            expose_with_viommu: false,
197            remote_peer: cx.jail_config.is_some(),
198        });
199        let (pmem_host_tube, pmem_device_tube) = Tube::pair().context("failed to create tube")?;
200        (cx.add_control_tube)(AnyControlTube::VmMsync(pmem_host_tube));
201
202        let mapping_size = self.pmem_ext2_option.size as u64;
203        let builder = ext2::Builder {
204            inodes_per_group: self.pmem_ext2_option.inodes_per_group,
205            blocks_per_group: self.pmem_ext2_option.blocks_per_group,
206            size: mapping_size as u32,
207            ..Default::default()
208        };
209
210        let mapping_address = GuestAddress(
211            cx.resources
212                .allocate_mmio(
213                    mapping_size,
214                    Alloc::PmemDevice(self.index),
215                    format!("pmem_ext2_image_{}", self.index),
216                    AllocOptions::new()
217                        .top_down(true)
218                        .prefetchable(true)
219                        // 2MB alignment for DAX
220                        // cf. https://docs.pmem.io/persistent-memory/getting-started-guide/creating-development-environments/linux-environments/advanced-topics/i-o-alignment-considerations#verifying-io-alignment
221                        .align(2 * 1024 * 1024),
222                )
223                .context("failed to allocate memory for pmem device")?,
224        );
225
226        let (mkfs_tube, mkfs_device_tube) = Tube::pair().context("failed to create tube")?;
227
228        let ext2_proc_pid = launch(
229            mapping_address,
230            vm_memory_client,
231            mkfs_tube,
232            &self.pmem_ext2_option.path,
233            &self.pmem_ext2_option.ugid,
234            (
235                &self.pmem_ext2_option.uid_map,
236                &self.pmem_ext2_option.gid_map,
237            ),
238            builder,
239            cx.jail_config,
240        )
241        .context("failed to spawn mkfs process")?;
242
243        cx.worker_process_pids.insert(ext2_proc_pid);
244
245        Ok(Box::new(
246            Pmem::new(
247                devices::virtio::base_features(cx.protection_type),
248                PmemConfig {
249                    disk_image: None,
250                    mapping_address,
251                    mem_slot: MemSlotConfig::LazyInit {
252                        tube: mkfs_device_tube,
253                    },
254                    mapping_size,
255                    pmem_device_tube,
256                    swap_interval: None,
257                    mapping_writable: false,
258                },
259            )
260            .context("failed to create pmem device")?,
261        ))
262    }
263
264    fn create_jail(&self, jail_config: Option<&JailConfig>) -> Result<Option<Minijail>> {
265        let max_open_files = base::linux::max_open_files()
266            .context("failed to get max number of open files")?
267            .rlim_max;
268        let jail = if let Some(jail_config) = jail_config {
269            let mut config = SandboxConfig::new(jail_config, "pmem_device");
270            config.limit_caps = false;
271            create_sandbox_minijail(&self.pmem_ext2_option.path, max_open_files, &config)?
272        } else {
273            create_base_minijail(&self.pmem_ext2_option.path, max_open_files)?
274        };
275        Ok(Some(jail))
276    }
277}