blob: bdbc0f6cc63062412005c4de16bf0a6e6a3a549a [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,
69) -> 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 {
Jooyung Han1b00bd22022-04-15 15:29:25 +090083 match try_attach(&path, offset, size_limit, direct_io) {
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,
106) -> Result<PathBuf> {
Jiyong Park86c9b082021-06-04 19:03:48 +0900107 // Get a free loop device
108 wait_for_path(LOOP_CONTROL)?;
109 let ctrl_file = OpenOptions::new()
110 .read(true)
111 .write(true)
112 .open(LOOP_CONTROL)
113 .context("Failed to open loop control")?;
114 let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?;
115
Jooyung Han7ce2e532021-06-16 16:52:02 +0900116 // Construct the loop_info64 struct
Jiyong Park86c9b082021-06-04 19:03:48 +0900117 let backing_file = OpenOptions::new()
118 .read(true)
Jooyung Han1b00bd22022-04-15 15:29:25 +0900119 .custom_flags(if direct_io { O_DIRECT } else { 0 })
Jiyong Park86c9b082021-06-04 19:03:48 +0900120 .open(&path)
121 .context(format!("failed to open {:?}", path.as_ref()))?;
Jiyong Park3c327d22021-06-08 20:51:54 +0900122 // safe because the size of the array is the same as the size of the struct
Jooyung Han1b00bd22022-04-15 15:29:25 +0900123 let mut config: loop_config =
124 *DataInit::from_mut_slice(&mut [0; size_of::<loop_config>()]).unwrap();
125 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;
129 config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY;
130 if direct_io {
131 config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900132 }
133
134 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900135 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900136 wait_for_path(&device_path)?;
137 let device_file = OpenOptions::new()
138 .read(true)
139 .write(true)
140 .open(&device_path)
141 .context(format!("failed to open {:?}", &device_path))?;
Jooyung Han1b00bd22022-04-15 15:29:25 +0900142 loop_configure(&device_file, &config)
143 .context(format!("Failed to configure {:?}", &device_path))?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900144
145 Ok(PathBuf::from(device_path))
146}
147
148/// Detaches backing file from the loop device `path`.
Jiyong Park86c9b082021-06-04 19:03:48 +0900149pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> {
150 let device_file = OpenOptions::new().read(true).write(true).open(&path)?;
151 loop_clr_fd(&device_file)?;
152 Ok(())
153}
Jooyung Han1b00bd22022-04-15 15:29:25 +0900154
155#[cfg(test)]
156mod tests {
157 use super::*;
158 use std::fs;
159 use std::path::Path;
160
161 fn create_empty_file(path: &Path, size: u64) {
162 let f = File::create(path).unwrap();
163 f.set_len(size).unwrap();
164 }
165
166 fn is_direct_io(dev: &Path) -> bool {
167 let dio = Path::new("/sys/block").join(dev.file_name().unwrap()).join("loop/dio");
168 "1" == fs::read_to_string(&dio).unwrap().trim()
169 }
170
171 #[test]
172 fn attach_loop_device_with_dio() {
173 let a_dir = tempfile::TempDir::new().unwrap();
174 let a_file = a_dir.path().join("test");
175 let a_size = 4096u64;
176 create_empty_file(&a_file, a_size);
177 let dev = attach(a_file, 0, a_size, /*direct_io*/ true).unwrap();
178 scopeguard::defer! {
179 detach(&dev).unwrap();
180 }
181 assert!(is_direct_io(&dev));
182 }
183
184 #[test]
185 fn attach_loop_device_without_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);
190 let dev = attach(a_file, 0, a_size, /*direct_io*/ false).unwrap();
191 scopeguard::defer! {
192 detach(&dev).unwrap();
193 }
194 assert!(!is_direct_io(&dev));
195 }
196}