blob: 5533e17879e616b454aaf8765f71f6392d6c56e0 [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};
Jiyong Park3c327d22021-06-08 20:51:54 +090028use data_model::DataInit;
Jooyung Han1b00bd22022-04-15 15:29:25 +090029use libc::O_DIRECT;
Jiyong Park86c9b082021-06-04 19:03:48 +090030use std::fs::{File, OpenOptions};
Jiyong Park3c327d22021-06-08 20:51:54 +090031use std::mem::size_of;
Jooyung Han1b00bd22022-04-15 15:29:25 +090032use std::os::unix::fs::OpenOptionsExt;
Jiyong Park86c9b082021-06-04 19:03:48 +090033use std::os::unix::io::AsRawFd;
34use std::path::{Path, PathBuf};
35use std::thread;
36use std::time::{Duration, Instant};
37
38use crate::loopdevice::sys::*;
Jiyong Park86c9b082021-06-04 19:03:48 +090039
40// These are old-style ioctls, thus *_bad.
41nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE);
Jooyung Han1b00bd22022-04-15 15:29:25 +090042nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config);
Jiyong Park86c9b082021-06-04 19:03:48 +090043nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD);
44
45fn loop_ctl_get_free(ctrl_file: &File) -> Result<i32> {
46 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
47 // The returned device number is a global resource; not tied to this process. So, we don't
48 // need to keep track of it.
49 Ok(unsafe { _loop_ctl_get_free(ctrl_file.as_raw_fd()) }?)
50}
51
Jooyung Han1b00bd22022-04-15 15:29:25 +090052fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090053 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
Jooyung Han1b00bd22022-04-15 15:29:25 +090054 Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?)
Jiyong Park86c9b082021-06-04 19:03:48 +090055}
56
Shikha Panwarb278b1c2022-10-14 12:38:32 +000057pub fn loop_clr_fd(device_file: &File) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090058 // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will
59 // remain opened afterward. The association itself is kept for open FDs.
60 Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?)
61}
62
63/// Creates a loop device and attach the given file at `path` as the backing store.
Jooyung Han1b00bd22022-04-15 15:29:25 +090064pub fn attach<P: AsRef<Path>>(
65 path: P,
66 offset: u64,
67 size_limit: u64,
68 direct_io: bool,
Shikha Panwar743454c2022-10-18 12:50:30 +000069 writable: bool,
Jooyung Han1b00bd22022-04-15 15:29:25 +090070) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +090071 // Attaching a file to a loop device can make a race condition; a loop device number obtained
72 // 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 +000073 // subsequent LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds.
Jiyong Park86c9b082021-06-04 19:03:48 +090074 //
75 // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e.
76 // inside Microdroid) we can't experience the race condition because `apkverity` is the only
77 // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple
78 // tests run concurrently.
79 const TIMEOUT: Duration = Duration::from_secs(1);
80 const INTERVAL: Duration = Duration::from_millis(10);
81
82 let begin = Instant::now();
83 loop {
Shikha Panwar743454c2022-10-18 12:50:30 +000084 match try_attach(&path, offset, size_limit, direct_io, writable) {
Jiyong Park86c9b082021-06-04 19:03:48 +090085 Ok(loop_dev) => return Ok(loop_dev),
86 Err(e) => {
87 if begin.elapsed() > TIMEOUT {
88 return Err(e);
89 }
90 }
91 };
92 thread::sleep(INTERVAL);
93 }
94}
95
Jiyong Park5f0ebea2021-06-07 12:53:35 +090096#[cfg(not(target_os = "android"))]
97const LOOP_DEV_PREFIX: &str = "/dev/loop";
98
99#[cfg(target_os = "android")]
100const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
101
Jooyung Han1b00bd22022-04-15 15:29:25 +0900102fn try_attach<P: AsRef<Path>>(
103 path: P,
104 offset: u64,
105 size_limit: u64,
106 direct_io: bool,
Shikha Panwar743454c2022-10-18 12:50:30 +0000107 writable: bool,
Jooyung Han1b00bd22022-04-15 15:29:25 +0900108) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900109 // Get a free loop device
110 wait_for_path(LOOP_CONTROL)?;
111 let ctrl_file = OpenOptions::new()
112 .read(true)
113 .write(true)
114 .open(LOOP_CONTROL)
115 .context("Failed to open loop control")?;
116 let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?;
117
Jooyung Han7ce2e532021-06-16 16:52:02 +0900118 // Construct the loop_info64 struct
Jiyong Park86c9b082021-06-04 19:03:48 +0900119 let backing_file = OpenOptions::new()
120 .read(true)
Shikha Panwar743454c2022-10-18 12:50:30 +0000121 .write(writable)
Jooyung Han1b00bd22022-04-15 15:29:25 +0900122 .custom_flags(if direct_io { O_DIRECT } else { 0 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900123 .open(&path)
124 .context(format!("failed to open {:?}", path.as_ref()))?;
Jiyong Park3c327d22021-06-08 20:51:54 +0900125 // safe because the size of the array is the same as the size of the struct
Jooyung Han1b00bd22022-04-15 15:29:25 +0900126 let mut config: loop_config =
127 *DataInit::from_mut_slice(&mut [0; size_of::<loop_config>()]).unwrap();
128 config.fd = backing_file.as_raw_fd() as u32;
129 config.block_size = 4096;
130 config.info.lo_offset = offset;
131 config.info.lo_sizelimit = size_limit;
Shikha Panwar743454c2022-10-18 12:50:30 +0000132
133 if !writable {
134 config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY;
135 }
136
Jooyung Han1b00bd22022-04-15 15:29:25 +0900137 if direct_io {
138 config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900139 }
140
141 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900142 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900143 wait_for_path(&device_path)?;
144 let device_file = OpenOptions::new()
145 .read(true)
146 .write(true)
147 .open(&device_path)
148 .context(format!("failed to open {:?}", &device_path))?;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900149 loop_configure(&device_file, &config)
150 .context(format!("Failed to configure {:?}", &device_path))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900151
152 Ok(PathBuf::from(device_path))
153}
154
155/// Detaches backing file from the loop device `path`.
Jiyong Park86c9b082021-06-04 19:03:48 +0900156pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
157 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
158 loop_clr_fd(&device_file)?;
159 Ok(())
160}
Jooyung Han1b00bd22022-04-15 15:29:25 +0900161
162#[cfg(test)]
163mod tests {
164 use super::*;
165 use std::fs;
166 use std::path::Path;
167
168 fn create_empty_file(path: &Path, size: u64) {
169 let f = File::create(path).unwrap();
170 f.set_len(size).unwrap();
171 }
172
173 fn is_direct_io(dev: &Path) -> bool {
174 let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
175 "1" == fs::read_to_string(&dio).unwrap().trim()
176 }
177
Shikha Panwar743454c2022-10-18 12:50:30 +0000178 // kernel exposes /sys/block/loop*/ro which gives the read-only value
179 fn is_direct_io_writable(dev: &Path) -> bool {
180 let ro = Path::new("/sys/block").join(dev.file_name().unwrap()).join("ro");
181 "0" == fs::read_to_string(&ro).unwrap().trim()
182 }
183
Jooyung Han1b00bd22022-04-15 15:29:25 +0900184 #[test]
185 fn attach_loop_device_with_dio() {
186 let a_dir = tempfile::TempDir::new().unwrap();
187 let a_file = a_dir.path().join("test");
188 let a_size = 4096u64;
189 create_empty_file(&a_file, a_size);
Shikha Panwar743454c2022-10-18 12:50:30 +0000190 let dev = attach(a_file, 0, a_size, /*direct_io*/ true, /*writable*/ false).unwrap();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900191 scopeguard::defer! {
192 detach(&dev).unwrap();
193 }
194 assert!(is_direct_io(&dev));
195 }
196
197 #[test]
198 fn attach_loop_device_without_dio() {
199 let a_dir = tempfile::TempDir::new().unwrap();
200 let a_file = a_dir.path().join("test");
201 let a_size = 4096u64;
202 create_empty_file(&a_file, a_size);
Shikha Panwar743454c2022-10-18 12:50:30 +0000203 let dev = attach(a_file, 0, a_size, /*direct_io*/ false, /*writable*/ false).unwrap();
Jooyung Han1b00bd22022-04-15 15:29:25 +0900204 scopeguard::defer! {
205 detach(&dev).unwrap();
206 }
207 assert!(!is_direct_io(&dev));
208 }
Shikha Panwar743454c2022-10-18 12:50:30 +0000209
210 #[test]
211 fn attach_loop_device_with_dio_writable() {
212 let a_dir = tempfile::TempDir::new().unwrap();
213 let a_file = a_dir.path().join("test");
214 let a_size = 4096u64;
215 create_empty_file(&a_file, a_size);
216 let dev = attach(a_file, 0, a_size, /*direct_io*/ true, /*writable*/ true).unwrap();
217 scopeguard::defer! {
218 detach(&dev).unwrap();
219 }
220 assert!(is_direct_io(&dev));
221 assert!(is_direct_io_writable(&dev));
222 }
Jooyung Han1b00bd22022-04-15 15:29:25 +0900223}