Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 1 | /* |
| 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 | |
| 24 | mod sys; |
| 25 | |
Shikha Panwar | b278b1c | 2022-10-14 12:38:32 +0000 | [diff] [blame] | 26 | use crate::util::*; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 27 | use anyhow::{Context, Result}; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 28 | use libc::O_DIRECT; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 29 | use std::fs::{File, OpenOptions}; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 30 | use std::os::unix::fs::OpenOptionsExt; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 31 | use std::os::unix::io::AsRawFd; |
| 32 | use std::path::{Path, PathBuf}; |
| 33 | use std::thread; |
| 34 | use std::time::{Duration, Instant}; |
Andrew Walbran | 47d316e | 2024-11-28 18:41:09 +0000 | [diff] [blame] | 35 | use zerocopy::FromZeros; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 36 | |
| 37 | use crate::loopdevice::sys::*; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 38 | |
| 39 | // These are old-style ioctls, thus *_bad. |
| 40 | nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE); |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 41 | nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 42 | nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD); |
| 43 | |
| 44 | fn 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 51 | fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 52 | // SAFETY: this ioctl changes the state in kernel, but not the state in this process. |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 53 | Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 54 | } |
| 55 | |
Shikha Panwar | b278b1c | 2022-10-14 12:38:32 +0000 | [diff] [blame] | 56 | pub fn loop_clr_fd(device_file: &File) -> Result<i32> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 57 | // 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 62 | /// LOOP_CONFIGURE ioctl operation flags. |
| 63 | #[derive(Default)] |
| 64 | pub 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 | |
| 73 | pub struct LoopDevice { |
| 74 | /// The loop device file |
| 75 | pub file: File, |
| 76 | /// Path to the loop device |
| 77 | pub path: PathBuf, |
| 78 | } |
| 79 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 80 | /// Creates a loop device and attach the given file at `path` as the backing store. |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 81 | pub fn attach<P: AsRef<Path>>( |
| 82 | path: P, |
| 83 | offset: u64, |
| 84 | size_limit: u64, |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 85 | options: &LoopConfigOptions, |
| 86 | ) -> Result<LoopDevice> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 87 | // 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 Panwar | 414ea89 | 2022-10-12 13:45:52 +0000 | [diff] [blame] | 89 | // subsequent LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds. |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 90 | // |
| 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 100 | match try_attach(&path, offset, size_limit, options) { |
| 101 | Ok(loop_device) => return Ok(loop_device), |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 102 | Err(e) => { |
| 103 | if begin.elapsed() > TIMEOUT { |
| 104 | return Err(e); |
| 105 | } |
| 106 | } |
| 107 | }; |
| 108 | thread::sleep(INTERVAL); |
| 109 | } |
| 110 | } |
| 111 | |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 112 | #[cfg(not(target_os = "android"))] |
| 113 | const LOOP_DEV_PREFIX: &str = "/dev/loop"; |
| 114 | |
| 115 | #[cfg(target_os = "android")] |
| 116 | const LOOP_DEV_PREFIX: &str = "/dev/block/loop"; |
| 117 | |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 118 | fn try_attach<P: AsRef<Path>>( |
| 119 | path: P, |
| 120 | offset: u64, |
| 121 | size_limit: u64, |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 122 | options: &LoopConfigOptions, |
| 123 | ) -> Result<LoopDevice> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 124 | // 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 Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame] | 133 | // Construct the loop_info64 struct |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 134 | let backing_file = OpenOptions::new() |
| 135 | .read(true) |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 136 | .write(options.writable) |
| 137 | .custom_flags(if options.direct_io { O_DIRECT } else { 0 }) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 138 | .open(&path) |
| 139 | .context(format!("failed to open {:?}", path.as_ref()))?; |
Frederick Mayle | 8f79590 | 2023-10-23 15:48:34 -0700 | [diff] [blame] | 140 | let mut config = loop_config::new_zeroed(); |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 141 | 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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 145 | |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 146 | if !options.writable { |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 147 | config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY; |
| 148 | } |
| 149 | |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 150 | if options.direct_io { |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 151 | config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 152 | } |
| 153 | |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 154 | if options.autoclear { |
| 155 | config.info.lo_flags.insert(Flag::LO_FLAGS_AUTOCLEAR); |
| 156 | } |
| 157 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 158 | // Configure the loop device to attach the backing file |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 159 | let device_path = format!("{}{}", LOOP_DEV_PREFIX, num); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 160 | 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 166 | loop_configure(&device_file, &config) |
| 167 | .context(format!("Failed to configure {:?}", &device_path))?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 168 | |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 169 | Ok(LoopDevice { file: device_file, path: PathBuf::from(device_path) }) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 170 | } |
| 171 | |
| 172 | /// Detaches backing file from the loop device `path`. |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 173 | pub 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 178 | |
| 179 | #[cfg(test)] |
| 180 | mod 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"); |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 192 | "1" == fs::read_to_string(dio).unwrap().trim() |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 193 | } |
| 194 | |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 195 | // 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"); |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 198 | "0" == fs::read_to_string(ro).unwrap().trim() |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 199 | } |
| 200 | |
Hung Nguyen | ae63e6d | 2025-02-25 15:04:41 -0800 | [diff] [blame] | 201 | 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 Mayle | afc347b | 2025-02-25 12:51:14 -0800 | [diff] [blame] | 207 | #[test] |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 208 | 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 213 | let dev = |
| 214 | attach(a_file, 0, a_size, &LoopConfigOptions { direct_io: true, ..Default::default() }) |
| 215 | .unwrap() |
| 216 | .path; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 217 | scopeguard::defer! { |
| 218 | detach(&dev).unwrap(); |
| 219 | } |
| 220 | assert!(is_direct_io(&dev)); |
| 221 | } |
| 222 | |
Frederick Mayle | afc347b | 2025-02-25 12:51:14 -0800 | [diff] [blame] | 223 | #[test] |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 224 | 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 229 | let dev = attach(a_file, 0, a_size, &LoopConfigOptions::default()).unwrap().path; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 230 | scopeguard::defer! { |
| 231 | detach(&dev).unwrap(); |
| 232 | } |
| 233 | assert!(!is_direct_io(&dev)); |
| 234 | } |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 235 | |
Frederick Mayle | afc347b | 2025-02-25 12:51:14 -0800 | [diff] [blame] | 236 | #[test] |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 237 | 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 242 | 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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 250 | scopeguard::defer! { |
| 251 | detach(&dev).unwrap(); |
| 252 | } |
| 253 | assert!(is_direct_io(&dev)); |
| 254 | assert!(is_direct_io_writable(&dev)); |
| 255 | } |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 256 | |
Frederick Mayle | afc347b | 2025-02-25 12:51:14 -0800 | [diff] [blame] | 257 | #[test] |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 258 | 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 Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 266 | |
Hung Nguyen | ae63e6d | 2025-02-25 15:04:41 -0800 | [diff] [blame] | 267 | assert!(is_autoclear(&dev.path)); |
Hung Nguyen | 109cdfa | 2024-12-06 11:02:44 -0800 | [diff] [blame] | 268 | } |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 269 | } |