blob: 35ae1543e954445ecade292dcbb94827d2c8423d [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};
Jiyong Park3c327d22021-06-08 20:51:54 +090027use data_model::DataInit;
Jooyung Han1b00bd22022-04-15 15:29:25 +090028use libc::O_DIRECT;
Jiyong Park86c9b082021-06-04 19:03:48 +090029use std::fs::{File, OpenOptions};
Jiyong Park3c327d22021-06-08 20:51:54 +090030use std::mem::size_of;
Jooyung Han1b00bd22022-04-15 15:29:25 +090031use std::os::unix::fs::OpenOptionsExt;
Jiyong Park86c9b082021-06-04 19:03:48 +090032use std::os::unix::io::AsRawFd;
33use std::path::{Path, PathBuf};
34use std::thread;
35use std::time::{Duration, Instant};
36
37use crate::loopdevice::sys::*;
38use crate::util::*;
39
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 Park99a35b82021-06-07 10:13:44 +090043#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090044nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD);
45
46fn loop_ctl_get_free(ctrl_file: &File) -> Result<i32> {
47 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
48 // The returned device number is a global resource; not tied to this process. So, we don't
49 // need to keep track of it.
50 Ok(unsafe { _loop_ctl_get_free(ctrl_file.as_raw_fd()) }?)
51}
52
Jooyung Han1b00bd22022-04-15 15:29:25 +090053fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090054 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
Jooyung Han1b00bd22022-04-15 15:29:25 +090055 Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?)
Jiyong Park86c9b082021-06-04 19:03:48 +090056}
57
Jiyong Park99a35b82021-06-07 10:13:44 +090058#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090059fn loop_clr_fd(device_file: &File) -> Result<i32> {
60 // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will
61 // remain opened afterward. The association itself is kept for open FDs.
62 Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?)
63}
64
65/// Creates a loop device and attach the given file at `path` as the backing store.
Jooyung Han1b00bd22022-04-15 15:29:25 +090066pub fn attach<P: AsRef<Path>>(
67 path: P,
68 offset: u64,
69 size_limit: u64,
70 direct_io: bool,
71) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +090072 // Attaching a file to a loop device can make a race condition; a loop device number obtained
73 // from LOOP_CTL_GET_FREE might have been used by another thread or process. In that case the
74 // subsequet LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds.
75 //
76 // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e.
77 // inside Microdroid) we can't experience the race condition because `apkverity` is the only
78 // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple
79 // tests run concurrently.
80 const TIMEOUT: Duration = Duration::from_secs(1);
81 const INTERVAL: Duration = Duration::from_millis(10);
82
83 let begin = Instant::now();
84 loop {
Jooyung Han1b00bd22022-04-15 15:29:25 +090085 match try_attach(&path, offset, size_limit, direct_io) {
Jiyong Park86c9b082021-06-04 19:03:48 +090086 Ok(loop_dev) => return Ok(loop_dev),
87 Err(e) => {
88 if begin.elapsed() > TIMEOUT {
89 return Err(e);
90 }
91 }
92 };
93 thread::sleep(INTERVAL);
94 }
95}
96
Jiyong Park5f0ebea2021-06-07 12:53:35 +090097#[cfg(not(target_os = "android"))]
98const LOOP_DEV_PREFIX: &str = "/dev/loop";
99
100#[cfg(target_os = "android")]
101const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
102
Jooyung Han1b00bd22022-04-15 15:29:25 +0900103fn try_attach<P: AsRef<Path>>(
104 path: P,
105 offset: u64,
106 size_limit: u64,
107 direct_io: bool,
108) -> 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)
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()))?;
Jiyong Park3c327d22021-06-08 20:51:54 +0900124 // safe because the size of the array is the same as the size of the struct
Jooyung Han1b00bd22022-04-15 15:29:25 +0900125 let mut config: loop_config =
126 *DataInit::from_mut_slice(&mut [0; size_of::<loop_config>()]).unwrap();
127 config.fd = backing_file.as_raw_fd() as u32;
128 config.block_size = 4096;
129 config.info.lo_offset = offset;
130 config.info.lo_sizelimit = size_limit;
131 config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY;
132 if direct_io {
133 config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900134 }
135
136 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900137 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900138 wait_for_path(&device_path)?;
139 let device_file = OpenOptions::new()
140 .read(true)
141 .write(true)
142 .open(&device_path)
143 .context(format!("failed to open {:?}", &device_path))?;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900144 loop_configure(&device_file, &config)
145 .context(format!("Failed to configure {:?}", &device_path))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900146
147 Ok(PathBuf::from(device_path))
148}
149
150/// Detaches backing file from the loop device `path`.
Jiyong Park99a35b82021-06-07 10:13:44 +0900151#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900152pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
153 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
154 loop_clr_fd(&device_file)?;
155 Ok(())
156}
Jooyung Han1b00bd22022-04-15 15:29:25 +0900157
158#[cfg(test)]
159mod tests {
160 use super::*;
161 use std::fs;
162 use std::path::Path;
163
164 fn create_empty_file(path: &Path, size: u64) {
165 let f = File::create(path).unwrap();
166 f.set_len(size).unwrap();
167 }
168
169 fn is_direct_io(dev: &Path) -> bool {
170 let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
171 "1" == fs::read_to_string(&dio).unwrap().trim()
172 }
173
174 #[test]
175 fn attach_loop_device_with_dio() {
176 let a_dir = tempfile::TempDir::new().unwrap();
177 let a_file = a_dir.path().join("test");
178 let a_size = 4096u64;
179 create_empty_file(&a_file, a_size);
180 let dev = attach(a_file, 0, a_size, /*direct_io*/ true).unwrap();
181 scopeguard::defer! {
182 detach(&dev).unwrap();
183 }
184 assert!(is_direct_io(&dev));
185 }
186
187 #[test]
188 fn attach_loop_device_without_dio() {
189 let a_dir = tempfile::TempDir::new().unwrap();
190 let a_file = a_dir.path().join("test");
191 let a_size = 4096u64;
192 create_empty_file(&a_file, a_size);
193 let dev = attach(a_file, 0, a_size, /*direct_io*/ false).unwrap();
194 scopeguard::defer! {
195 detach(&dev).unwrap();
196 }
197 assert!(!is_direct_io(&dev));
198 }
199}