blob: e41b90cabb512bd0a41bc30f23c56aa898387d9c [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
Shikha Panwarb278b1c2022-10-14 12:38:32 +000026use crate::util::*;
Jiyong Park86c9b082021-06-04 19:03:48 +090027use anyhow::{Context, Result};
Jooyung Han1b00bd22022-04-15 15:29:25 +090028use libc::O_DIRECT;
Jiyong Park86c9b082021-06-04 19:03:48 +090029use std::fs::{File, OpenOptions};
Jooyung Han1b00bd22022-04-15 15:29:25 +090030use std::os::unix::fs::OpenOptionsExt;
Jiyong Park86c9b082021-06-04 19:03:48 +090031use std::os::unix::io::AsRawFd;
32use std::path::{Path, PathBuf};
33use std::thread;
34use std::time::{Duration, Instant};
Andrew Walbran47d316e2024-11-28 18:41:09 +000035use zerocopy::FromZeros;
Jiyong Park86c9b082021-06-04 19:03:48 +090036
37use crate::loopdevice::sys::*;
Jiyong Park86c9b082021-06-04 19:03:48 +090038
39// These are old-style ioctls, thus *_bad.
40nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE);
Jooyung Han1b00bd22022-04-15 15:29:25 +090041nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config);
Jiyong Park86c9b082021-06-04 19:03:48 +090042nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD);
43
44fn loop_ctl_get_free(ctrl_file: &File) -> Result<i32> {
45 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
46 // The returned device number is a global resource; not tied to this process. So, we don't
47 // need to keep track of it.
48 Ok(unsafe { _loop_ctl_get_free(ctrl_file.as_raw_fd()) }?)
49}
50
Jooyung Han1b00bd22022-04-15 15:29:25 +090051fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090052 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
Jooyung Han1b00bd22022-04-15 15:29:25 +090053 Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?)
Jiyong Park86c9b082021-06-04 19:03:48 +090054}
55
Shikha Panwarb278b1c2022-10-14 12:38:32 +000056pub fn loop_clr_fd(device_file: &File) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090057 // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will
58 // remain opened afterward. The association itself is kept for open FDs.
59 Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?)
60}
61
Hung Nguyen109cdfa2024-12-06 11:02:44 -080062/// LOOP_CONFIGURE ioctl operation flags.
63#[derive(Default)]
64pub struct LoopConfigOptions {
65 /// Whether to use direct I/O
66 pub direct_io: bool,
67 /// Whether the device is writable
68 pub writable: bool,
69 /// Whether to autodestruct the device on last close
70 pub autoclear: bool,
71}
72
73pub struct LoopDevice {
74 /// The loop device file
75 pub file: File,
76 /// Path to the loop device
77 pub path: PathBuf,
78}
79
Jiyong Park86c9b082021-06-04 19:03:48 +090080/// Creates a loop device and attach the given file at `path` as the backing store.
Jooyung Han1b00bd22022-04-15 15:29:25 +090081pub fn attach<P: AsRef<Path>>(
82 path: P,
83 offset: u64,
84 size_limit: u64,
Hung Nguyen109cdfa2024-12-06 11:02:44 -080085 options: &LoopConfigOptions,
86) -> Result<LoopDevice> {
Jiyong Park86c9b082021-06-04 19:03:48 +090087 // Attaching a file to a loop device can make a race condition; a loop device number obtained
88 // from LOOP_CTL_GET_FREE might have been used by another thread or process. In that case the
Shikha Panwar414ea892022-10-12 13:45:52 +000089 // subsequent LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds.
Jiyong Park86c9b082021-06-04 19:03:48 +090090 //
91 // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e.
92 // inside Microdroid) we can't experience the race condition because `apkverity` is the only
93 // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple
94 // tests run concurrently.
95 const TIMEOUT: Duration = Duration::from_secs(1);
96 const INTERVAL: Duration = Duration::from_millis(10);
97
98 let begin = Instant::now();
99 loop {
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800100 match try_attach(&path, offset, size_limit, options) {
101 Ok(loop_device) => return Ok(loop_device),
Jiyong Park86c9b082021-06-04 19:03:48 +0900102 Err(e) => {
103 if begin.elapsed() > TIMEOUT {
104 return Err(e);
105 }
106 }
107 };
108 thread::sleep(INTERVAL);
109 }
110}
111
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900112#[cfg(not(target_os = "android"))]
113const LOOP_DEV_PREFIX: &str = "/dev/loop";
114
115#[cfg(target_os = "android")]
116const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
117
Jooyung Han1b00bd22022-04-15 15:29:25 +0900118fn try_attach<P: AsRef<Path>>(
119 path: P,
120 offset: u64,
121 size_limit: u64,
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800122 options: &LoopConfigOptions,
123) -> Result<LoopDevice> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900124 // Get a free loop device
125 wait_for_path(LOOP_CONTROL)?;
126 let ctrl_file = OpenOptions::new()
127 .read(true)
128 .write(true)
129 .open(LOOP_CONTROL)
130 .context("Failed to open loop control")?;
131 let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?;
132
Jooyung Han7ce2e532021-06-16 16:52:02 +0900133 // Construct the loop_info64 struct
Jiyong Park86c9b082021-06-04 19:03:48 +0900134 let backing_file = OpenOptions::new()
135 .read(true)
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800136 .write(options.writable)
137 .custom_flags(if options.direct_io { O_DIRECT } else { 0 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900138 .open(&path)
139 .context(format!("failed to open {:?}", path.as_ref()))?;
Frederick Mayle8f795902023-10-23 15:48:34 -0700140 let mut config = loop_config::new_zeroed();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900141 config.fd = backing_file.as_raw_fd() as u32;
142 config.block_size = 4096;
143 config.info.lo_offset = offset;
144 config.info.lo_sizelimit = size_limit;
Shikha Panwar743454c2022-10-18 12:50:30 +0000145
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800146 if !options.writable {
Shikha Panwar743454c2022-10-18 12:50:30 +0000147 config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY;
148 }
149
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800150 if options.direct_io {
Jooyung Han1b00bd22022-04-15 15:29:25 +0900151 config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900152 }
153
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800154 if options.autoclear {
155 config.info.lo_flags.insert(Flag::LO_FLAGS_AUTOCLEAR);
156 }
157
Jiyong Park86c9b082021-06-04 19:03:48 +0900158 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900159 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900160 wait_for_path(&device_path)?;
161 let device_file = OpenOptions::new()
162 .read(true)
163 .write(true)
164 .open(&device_path)
165 .context(format!("failed to open {:?}", &device_path))?;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900166 loop_configure(&device_file, &config)
167 .context(format!("Failed to configure {:?}", &device_path))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900168
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800169 Ok(LoopDevice { file: device_file, path: PathBuf::from(device_path) })
Jiyong Park86c9b082021-06-04 19:03:48 +0900170}
171
172/// Detaches backing file from the loop device `path`.
Jiyong Park86c9b082021-06-04 19:03:48 +0900173pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
174 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
175 loop_clr_fd(&device_file)?;
176 Ok(())
177}
Jooyung Han1b00bd22022-04-15 15:29:25 +0900178
179#[cfg(test)]
180mod tests {
181 use super::*;
182 use std::fs;
183 use std::path::Path;
184
185 fn create_empty_file(path: &Path, size: u64) {
186 let f = File::create(path).unwrap();
187 f.set_len(size).unwrap();
188 }
189
190 fn is_direct_io(dev: &Path) -> bool {
191 let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
Charisee96113f32023-01-26 09:00:42 +0000192 "1" == fs::read_to_string(dio).unwrap().trim()
Jooyung Han1b00bd22022-04-15 15:29:25 +0900193 }
194
Shikha Panwar743454c2022-10-18 12:50:30 +0000195 // kernel exposes /sys/block/loop*/ro which gives the read-only value
196 fn is_direct_io_writable(dev: &Path) -> bool {
197 let ro = Path::new("/sys/block").join(dev.file_name().unwrap()).join("ro");
Charisee96113f32023-01-26 09:00:42 +0000198 "0" == fs::read_to_string(ro).unwrap().trim()
Shikha Panwar743454c2022-10-18 12:50:30 +0000199 }
200
Hung Nguyenae63e6d2025-02-25 15:04:41 -0800201 fn is_autoclear(dev: &Path) -> bool {
202 let autoclear =
203 Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/autoclear");
204 "1" == fs::read_to_string(autoclear).unwrap().trim()
205 }
206
Frederick Mayleafc347b2025-02-25 12:51:14 -0800207 #[test]
Jooyung Han1b00bd22022-04-15 15:29:25 +0900208 fn attach_loop_device_with_dio() {
209 let a_dir = tempfile::TempDir::new().unwrap();
210 let a_file = a_dir.path().join("test");
211 let a_size = 4096u64;
212 create_empty_file(&a_file, a_size);
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800213 let dev =
214 attach(a_file, 0, a_size, &LoopConfigOptions { direct_io: true, ..Default::default() })
215 .unwrap()
216 .path;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900217 scopeguard::defer! {
218 detach(&dev).unwrap();
219 }
220 assert!(is_direct_io(&dev));
221 }
222
Frederick Mayleafc347b2025-02-25 12:51:14 -0800223 #[test]
Jooyung Han1b00bd22022-04-15 15:29:25 +0900224 fn attach_loop_device_without_dio() {
225 let a_dir = tempfile::TempDir::new().unwrap();
226 let a_file = a_dir.path().join("test");
227 let a_size = 4096u64;
228 create_empty_file(&a_file, a_size);
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800229 let dev = attach(a_file, 0, a_size, &LoopConfigOptions::default()).unwrap().path;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900230 scopeguard::defer! {
231 detach(&dev).unwrap();
232 }
233 assert!(!is_direct_io(&dev));
234 }
Shikha Panwar743454c2022-10-18 12:50:30 +0000235
Frederick Mayleafc347b2025-02-25 12:51:14 -0800236 #[test]
Shikha Panwar743454c2022-10-18 12:50:30 +0000237 fn attach_loop_device_with_dio_writable() {
238 let a_dir = tempfile::TempDir::new().unwrap();
239 let a_file = a_dir.path().join("test");
240 let a_size = 4096u64;
241 create_empty_file(&a_file, a_size);
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800242 let dev = attach(
243 a_file,
244 0,
245 a_size,
246 &LoopConfigOptions { direct_io: true, writable: true, ..Default::default() },
247 )
248 .unwrap()
249 .path;
Shikha Panwar743454c2022-10-18 12:50:30 +0000250 scopeguard::defer! {
251 detach(&dev).unwrap();
252 }
253 assert!(is_direct_io(&dev));
254 assert!(is_direct_io_writable(&dev));
255 }
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800256
Frederick Mayleafc347b2025-02-25 12:51:14 -0800257 #[test]
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800258 fn attach_loop_device_autoclear() {
259 let a_dir = tempfile::TempDir::new().unwrap();
260 let a_file = a_dir.path().join("test");
261 let a_size = 4096u64;
262 create_empty_file(&a_file, a_size);
263 let dev =
264 attach(a_file, 0, a_size, &LoopConfigOptions { autoclear: true, ..Default::default() })
265 .unwrap();
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800266
Hung Nguyenae63e6d2025-02-25 15:04:41 -0800267 assert!(is_autoclear(&dev.path));
Hung Nguyen109cdfa2024-12-06 11:02:44 -0800268 }
Jooyung Han1b00bd22022-04-15 15:29:25 +0900269}