blob: 9dc722b107a4f3ca0caf4cb2601238fc54ff8679 [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};
Frederick Mayle8f795902023-10-23 15:48:34 -070035use zerocopy::FromZeroes;
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
62/// Creates a loop device and attach the given file at `path` as the backing store.
Jooyung Han1b00bd22022-04-15 15:29:25 +090063pub fn attach<P: AsRef<Path>>(
64 path: P,
65 offset: u64,
66 size_limit: u64,
67 direct_io: bool,
Shikha Panwar743454c2022-10-18 12:50:30 +000068 writable: bool,
Jooyung Han1b00bd22022-04-15 15:29:25 +090069) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +090070 // Attaching a file to a loop device can make a race condition; a loop device number obtained
71 // 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 +000072 // subsequent LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds.
Jiyong Park86c9b082021-06-04 19:03:48 +090073 //
74 // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e.
75 // inside Microdroid) we can't experience the race condition because `apkverity` is the only
76 // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple
77 // tests run concurrently.
78 const TIMEOUT: Duration = Duration::from_secs(1);
79 const INTERVAL: Duration = Duration::from_millis(10);
80
81 let begin = Instant::now();
82 loop {
Shikha Panwar743454c2022-10-18 12:50:30 +000083 match try_attach(&path, offset, size_limit, direct_io, writable) {
Jiyong Park86c9b082021-06-04 19:03:48 +090084 Ok(loop_dev) => return Ok(loop_dev),
85 Err(e) => {
86 if begin.elapsed() > TIMEOUT {
87 return Err(e);
88 }
89 }
90 };
91 thread::sleep(INTERVAL);
92 }
93}
94
Jiyong Park5f0ebea2021-06-07 12:53:35 +090095#[cfg(not(target_os = "android"))]
96const LOOP_DEV_PREFIX: &str = "/dev/loop";
97
98#[cfg(target_os = "android")]
99const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
100
Jooyung Han1b00bd22022-04-15 15:29:25 +0900101fn try_attach<P: AsRef<Path>>(
102 path: P,
103 offset: u64,
104 size_limit: u64,
105 direct_io: bool,
Shikha Panwar743454c2022-10-18 12:50:30 +0000106 writable: bool,
Jooyung Han1b00bd22022-04-15 15:29:25 +0900107) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900108 // Get a free loop device
109 wait_for_path(LOOP_CONTROL)?;
110 let ctrl_file = OpenOptions::new()
111 .read(true)
112 .write(true)
113 .open(LOOP_CONTROL)
114 .context("Failed to open loop control")?;
115 let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?;
116
Jooyung Han7ce2e532021-06-16 16:52:02 +0900117 // Construct the loop_info64 struct
Jiyong Park86c9b082021-06-04 19:03:48 +0900118 let backing_file = OpenOptions::new()
119 .read(true)
Shikha Panwar743454c2022-10-18 12:50:30 +0000120 .write(writable)
Jooyung Han1b00bd22022-04-15 15:29:25 +0900121 .custom_flags(if direct_io { O_DIRECT } else { 0 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900122 .open(&path)
123 .context(format!("failed to open {:?}", path.as_ref()))?;
Frederick Mayle8f795902023-10-23 15:48:34 -0700124 let mut config = loop_config::new_zeroed();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900125 config.fd = backing_file.as_raw_fd() as u32;
126 config.block_size = 4096;
127 config.info.lo_offset = offset;
128 config.info.lo_sizelimit = size_limit;
Shikha Panwar743454c2022-10-18 12:50:30 +0000129
130 if !writable {
131 config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY;
132 }
133
Jooyung Han1b00bd22022-04-15 15:29:25 +0900134 if direct_io {
135 config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900136 }
137
138 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900139 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900140 wait_for_path(&device_path)?;
141 let device_file = OpenOptions::new()
142 .read(true)
143 .write(true)
144 .open(&device_path)
145 .context(format!("failed to open {:?}", &device_path))?;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900146 loop_configure(&device_file, &config)
147 .context(format!("Failed to configure {:?}", &device_path))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900148
149 Ok(PathBuf::from(device_path))
150}
151
152/// Detaches backing file from the loop device `path`.
Jiyong Park86c9b082021-06-04 19:03:48 +0900153pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
154 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
155 loop_clr_fd(&device_file)?;
156 Ok(())
157}
Jooyung Han1b00bd22022-04-15 15:29:25 +0900158
159#[cfg(test)]
160mod tests {
161 use super::*;
162 use std::fs;
163 use std::path::Path;
164
165 fn create_empty_file(path: &Path, size: u64) {
166 let f = File::create(path).unwrap();
167 f.set_len(size).unwrap();
168 }
169
170 fn is_direct_io(dev: &Path) -> bool {
171 let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
Charisee96113f32023-01-26 09:00:42 +0000172 "1" == fs::read_to_string(dio).unwrap().trim()
Jooyung Han1b00bd22022-04-15 15:29:25 +0900173 }
174
Shikha Panwar743454c2022-10-18 12:50:30 +0000175 // kernel exposes /sys/block/loop*/ro which gives the read-only value
176 fn is_direct_io_writable(dev: &Path) -> bool {
177 let ro = Path::new("/sys/block").join(dev.file_name().unwrap()).join("ro");
Charisee96113f32023-01-26 09:00:42 +0000178 "0" == fs::read_to_string(ro).unwrap().trim()
Shikha Panwar743454c2022-10-18 12:50:30 +0000179 }
180
Jooyung Han1b00bd22022-04-15 15:29:25 +0900181 #[test]
182 fn attach_loop_device_with_dio() {
183 let a_dir = tempfile::TempDir::new().unwrap();
184 let a_file = a_dir.path().join("test");
185 let a_size = 4096u64;
186 create_empty_file(&a_file, a_size);
Shikha Panwar743454c2022-10-18 12:50:30 +0000187 let dev = attach(a_file, 0, a_size, /*direct_io*/ true, /*writable*/ false).unwrap();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900188 scopeguard::defer! {
189 detach(&dev).unwrap();
190 }
191 assert!(is_direct_io(&dev));
192 }
193
194 #[test]
195 fn attach_loop_device_without_dio() {
196 let a_dir = tempfile::TempDir::new().unwrap();
197 let a_file = a_dir.path().join("test");
198 let a_size = 4096u64;
199 create_empty_file(&a_file, a_size);
Shikha Panwar743454c2022-10-18 12:50:30 +0000200 let dev = attach(a_file, 0, a_size, /*direct_io*/ false, /*writable*/ false).unwrap();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900201 scopeguard::defer! {
202 detach(&dev).unwrap();
203 }
204 assert!(!is_direct_io(&dev));
205 }
Shikha Panwar743454c2022-10-18 12:50:30 +0000206
207 #[test]
208 fn attach_loop_device_with_dio_writable() {
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);
213 let dev = attach(a_file, 0, a_size, /*direct_io*/ true, /*writable*/ true).unwrap();
214 scopeguard::defer! {
215 detach(&dev).unwrap();
216 }
217 assert!(is_direct_io(&dev));
218 assert!(is_direct_io_writable(&dev));
219 }
Jooyung Han1b00bd22022-04-15 15:29:25 +0900220}