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}; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 28 | use data_model::DataInit; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 29 | use libc::O_DIRECT; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 30 | use std::fs::{File, OpenOptions}; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 31 | use std::mem::size_of; |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 32 | use std::os::unix::fs::OpenOptionsExt; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 33 | use std::os::unix::io::AsRawFd; |
| 34 | use std::path::{Path, PathBuf}; |
| 35 | use std::thread; |
| 36 | use std::time::{Duration, Instant}; |
| 37 | |
| 38 | use crate::loopdevice::sys::*; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 39 | |
| 40 | // These are old-style ioctls, thus *_bad. |
| 41 | nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE); |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 42 | nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 43 | nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD); |
| 44 | |
| 45 | fn 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 52 | fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 53 | // 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] | 54 | Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 55 | } |
| 56 | |
Shikha Panwar | b278b1c | 2022-10-14 12:38:32 +0000 | [diff] [blame] | 57 | pub fn loop_clr_fd(device_file: &File) -> Result<i32> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 58 | // 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 64 | pub fn attach<P: AsRef<Path>>( |
| 65 | path: P, |
| 66 | offset: u64, |
| 67 | size_limit: u64, |
| 68 | direct_io: bool, |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 69 | writable: bool, |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 70 | ) -> Result<PathBuf> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 71 | // 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 Panwar | 414ea89 | 2022-10-12 13:45:52 +0000 | [diff] [blame] | 73 | // subsequent LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds. |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 74 | // |
| 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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 84 | match try_attach(&path, offset, size_limit, direct_io, writable) { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 85 | 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 Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 96 | #[cfg(not(target_os = "android"))] |
| 97 | const LOOP_DEV_PREFIX: &str = "/dev/loop"; |
| 98 | |
| 99 | #[cfg(target_os = "android")] |
| 100 | const LOOP_DEV_PREFIX: &str = "/dev/block/loop"; |
| 101 | |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 102 | fn try_attach<P: AsRef<Path>>( |
| 103 | path: P, |
| 104 | offset: u64, |
| 105 | size_limit: u64, |
| 106 | direct_io: bool, |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 107 | writable: bool, |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 108 | ) -> Result<PathBuf> { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 109 | // 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 Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame] | 118 | // Construct the loop_info64 struct |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 119 | let backing_file = OpenOptions::new() |
| 120 | .read(true) |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 121 | .write(writable) |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 122 | .custom_flags(if direct_io { O_DIRECT } else { 0 }) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 123 | .open(&path) |
| 124 | .context(format!("failed to open {:?}", path.as_ref()))?; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 125 | // safe because the size of the array is the same as the size of the struct |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 126 | 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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 132 | |
| 133 | if !writable { |
| 134 | config.info.lo_flags = Flag::LO_FLAGS_READ_ONLY; |
| 135 | } |
| 136 | |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 137 | if direct_io { |
| 138 | config.info.lo_flags.insert(Flag::LO_FLAGS_DIRECT_IO); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | // Configure the loop device to attach the backing file |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 142 | let device_path = format!("{}{}", LOOP_DEV_PREFIX, num); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 143 | 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 149 | loop_configure(&device_file, &config) |
| 150 | .context(format!("Failed to configure {:?}", &device_path))?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 151 | |
| 152 | Ok(PathBuf::from(device_path)) |
| 153 | } |
| 154 | |
| 155 | /// Detaches backing file from the loop device `path`. |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 156 | pub 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 161 | |
| 162 | #[cfg(test)] |
| 163 | mod 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"); |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 175 | "1" == fs::read_to_string(dio).unwrap().trim() |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 176 | } |
| 177 | |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 178 | // 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"); |
Charisee | 96113f3 | 2023-01-26 09:00:42 +0000 | [diff] [blame] | 181 | "0" == fs::read_to_string(ro).unwrap().trim() |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 182 | } |
| 183 | |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 184 | #[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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 190 | let dev = attach(a_file, 0, a_size, /*direct_io*/ true, /*writable*/ false).unwrap(); |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 191 | 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 Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 203 | let dev = attach(a_file, 0, a_size, /*direct_io*/ false, /*writable*/ false).unwrap(); |
Jooyung Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 204 | scopeguard::defer! { |
| 205 | detach(&dev).unwrap(); |
| 206 | } |
| 207 | assert!(!is_direct_io(&dev)); |
| 208 | } |
Shikha Panwar | 743454c | 2022-10-18 12:50:30 +0000 | [diff] [blame] | 209 | |
| 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 Han | 1b00bd2 | 2022-04-15 15:29:25 +0900 | [diff] [blame] | 223 | } |