blob: 68516d7226fc714f9fea91349e67ebe2e094df18 [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
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// `loopdevice` module provides `attach` and `detach` functions that are for attaching and
18// detaching a regular file to and from a loop device. Note that
19// `loopdev`(https://crates.io/crates/loopdev) is a public alternative to this. In-house
20// implementation was chosen to make Android-specific changes (like the use of the new
21// LOOP_CONFIGURE instead of the legacy LOOP_SET_FD + LOOP_SET_STATUS64 combo which is considerably
22// slower than the former).
23
24mod sys;
25
26use anyhow::{Context, Result};
27use std::fs::{File, OpenOptions};
28use std::os::unix::io::AsRawFd;
29use std::path::{Path, PathBuf};
30use std::thread;
31use std::time::{Duration, Instant};
32
33use crate::loopdevice::sys::*;
34use crate::util::*;
35
36// These are old-style ioctls, thus *_bad.
37nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE);
38nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config);
Jiyong Park99a35b82021-06-07 10:13:44 +090039#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090040nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD);
41
42fn loop_ctl_get_free(ctrl_file: &File) -> Result<i32> {
43 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
44 // The returned device number is a global resource; not tied to this process. So, we don't
45 // need to keep track of it.
46 Ok(unsafe { _loop_ctl_get_free(ctrl_file.as_raw_fd()) }?)
47}
48
49fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> {
50 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
51 Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?)
52}
53
Jiyong Park99a35b82021-06-07 10:13:44 +090054#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090055fn loop_clr_fd(device_file: &File) -> Result<i32> {
56 // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will
57 // remain opened afterward. The association itself is kept for open FDs.
58 Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?)
59}
60
61/// Creates a loop device and attach the given file at `path` as the backing store.
62pub fn attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> {
63 // Attaching a file to a loop device can make a race condition; a loop device number obtained
64 // from LOOP_CTL_GET_FREE might have been used by another thread or process. In that case the
65 // subsequet LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds.
66 //
67 // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e.
68 // inside Microdroid) we can't experience the race condition because `apkverity` is the only
69 // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple
70 // tests run concurrently.
71 const TIMEOUT: Duration = Duration::from_secs(1);
72 const INTERVAL: Duration = Duration::from_millis(10);
73
74 let begin = Instant::now();
75 loop {
76 match try_attach(&path, offset, size_limit) {
77 Ok(loop_dev) => return Ok(loop_dev),
78 Err(e) => {
79 if begin.elapsed() > TIMEOUT {
80 return Err(e);
81 }
82 }
83 };
84 thread::sleep(INTERVAL);
85 }
86}
87
Jiyong Park5f0ebea2021-06-07 12:53:35 +090088#[cfg(not(target_os = "android"))]
89const LOOP_DEV_PREFIX: &str = "/dev/loop";
90
91#[cfg(target_os = "android")]
92const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
93
Jiyong Park86c9b082021-06-04 19:03:48 +090094fn try_attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> {
95 // Get a free loop device
96 wait_for_path(LOOP_CONTROL)?;
97 let ctrl_file = OpenOptions::new()
98 .read(true)
99 .write(true)
100 .open(LOOP_CONTROL)
101 .context("Failed to open loop control")?;
102 let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?;
103
104 // Construct the loop_config struct
105 let backing_file = OpenOptions::new()
106 .read(true)
107 .open(&path)
108 .context(format!("failed to open {:?}", path.as_ref()))?;
109 // SAFETY: zero initialized C structs is safe
110 let mut config = unsafe { std::mem::MaybeUninit::<loop_config>::zeroed().assume_init() };
111 config.fd = backing_file.as_raw_fd() as u32;
112 config.block_size = 4096;
113 config.info.lo_offset = offset;
114 config.info.lo_sizelimit = size_limit;
115 config.info.lo_flags |= Flag::LO_FLAGS_DIRECT_IO | Flag::LO_FLAGS_READ_ONLY;
116
117 // Special case: don't use direct IO when the backing file is already a loop device, which
118 // happens only during test. DirectIO-on-loop-over-loop makes the outer loop device
119 // unaccessible.
120 #[cfg(test)]
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900121 if path.as_ref().to_str().unwrap().starts_with(LOOP_DEV_PREFIX) {
Jiyong Park86c9b082021-06-04 19:03:48 +0900122 config.info.lo_flags.remove(Flag::LO_FLAGS_DIRECT_IO);
123 }
124
125 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900126 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900127 wait_for_path(&device_path)?;
128 let device_file = OpenOptions::new()
129 .read(true)
130 .write(true)
131 .open(&device_path)
132 .context(format!("failed to open {:?}", &device_path))?;
Jiyong Park99a35b82021-06-07 10:13:44 +0900133 loop_configure(&device_file, &config)
Jiyong Park86c9b082021-06-04 19:03:48 +0900134 .context(format!("Failed to configure {:?}", &device_path))?;
135
136 Ok(PathBuf::from(device_path))
137}
138
139/// Detaches backing file from the loop device `path`.
Jiyong Park99a35b82021-06-07 10:13:44 +0900140#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900141pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
142 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
143 loop_clr_fd(&device_file)?;
144 Ok(())
145}