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 | |
| 26 | use anyhow::{Context, Result}; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 27 | use data_model::DataInit; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 28 | use std::fs::{File, OpenOptions}; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 29 | use std::mem::size_of; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 30 | use std::os::unix::io::AsRawFd; |
| 31 | use std::path::{Path, PathBuf}; |
| 32 | use std::thread; |
| 33 | use std::time::{Duration, Instant}; |
| 34 | |
| 35 | use crate::loopdevice::sys::*; |
| 36 | use crate::util::*; |
| 37 | |
| 38 | // These are old-style ioctls, thus *_bad. |
| 39 | nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE); |
| 40 | nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config); |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 41 | #[cfg(test)] |
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 | |
| 51 | fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> { |
| 52 | // SAFETY: this ioctl changes the state in kernel, but not the state in this process. |
| 53 | Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?) |
| 54 | } |
| 55 | |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 56 | #[cfg(test)] |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 57 | fn loop_clr_fd(device_file: &File) -> Result<i32> { |
| 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. |
| 64 | pub fn attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 65 | // Attaching a file to a loop device can make a race condition; a loop device number obtained |
| 66 | // from LOOP_CTL_GET_FREE might have been used by another thread or process. In that case the |
| 67 | // subsequet LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds. |
| 68 | // |
| 69 | // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e. |
| 70 | // inside Microdroid) we can't experience the race condition because `apkverity` is the only |
| 71 | // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple |
| 72 | // tests run concurrently. |
| 73 | const TIMEOUT: Duration = Duration::from_secs(1); |
| 74 | const INTERVAL: Duration = Duration::from_millis(10); |
| 75 | |
| 76 | let begin = Instant::now(); |
| 77 | loop { |
| 78 | match try_attach(&path, offset, size_limit) { |
| 79 | Ok(loop_dev) => return Ok(loop_dev), |
| 80 | Err(e) => { |
| 81 | if begin.elapsed() > TIMEOUT { |
| 82 | return Err(e); |
| 83 | } |
| 84 | } |
| 85 | }; |
| 86 | thread::sleep(INTERVAL); |
| 87 | } |
| 88 | } |
| 89 | |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 90 | #[cfg(not(target_os = "android"))] |
| 91 | const LOOP_DEV_PREFIX: &str = "/dev/loop"; |
| 92 | |
| 93 | #[cfg(target_os = "android")] |
| 94 | const LOOP_DEV_PREFIX: &str = "/dev/block/loop"; |
| 95 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 96 | fn try_attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 97 | // Get a free loop device |
| 98 | wait_for_path(LOOP_CONTROL)?; |
| 99 | let ctrl_file = OpenOptions::new() |
| 100 | .read(true) |
| 101 | .write(true) |
| 102 | .open(LOOP_CONTROL) |
| 103 | .context("Failed to open loop control")?; |
| 104 | let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?; |
| 105 | |
| 106 | // Construct the loop_config struct |
| 107 | let backing_file = OpenOptions::new() |
| 108 | .read(true) |
| 109 | .open(&path) |
| 110 | .context(format!("failed to open {:?}", path.as_ref()))?; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 111 | // safe because the size of the array is the same as the size of the struct |
| 112 | let mut config: loop_config = |
| 113 | *DataInit::from_mut_slice(&mut [0; size_of::<loop_config>()]).unwrap(); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 114 | config.fd = backing_file.as_raw_fd() as u32; |
| 115 | config.block_size = 4096; |
| 116 | config.info.lo_offset = offset; |
| 117 | config.info.lo_sizelimit = size_limit; |
| 118 | config.info.lo_flags |= Flag::LO_FLAGS_DIRECT_IO | Flag::LO_FLAGS_READ_ONLY; |
| 119 | |
| 120 | // Special case: don't use direct IO when the backing file is already a loop device, which |
| 121 | // happens only during test. DirectIO-on-loop-over-loop makes the outer loop device |
| 122 | // unaccessible. |
| 123 | #[cfg(test)] |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 124 | if path.as_ref().to_str().unwrap().starts_with(LOOP_DEV_PREFIX) { |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 125 | config.info.lo_flags.remove(Flag::LO_FLAGS_DIRECT_IO); |
| 126 | } |
| 127 | |
| 128 | // Configure the loop device to attach the backing file |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 129 | let device_path = format!("{}{}", LOOP_DEV_PREFIX, num); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 130 | wait_for_path(&device_path)?; |
| 131 | let device_file = OpenOptions::new() |
| 132 | .read(true) |
| 133 | .write(true) |
| 134 | .open(&device_path) |
| 135 | .context(format!("failed to open {:?}", &device_path))?; |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 136 | loop_configure(&device_file, &config) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 137 | .context(format!("Failed to configure {:?}", &device_path))?; |
| 138 | |
| 139 | Ok(PathBuf::from(device_path)) |
| 140 | } |
| 141 | |
| 142 | /// Detaches backing file from the loop device `path`. |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 143 | #[cfg(test)] |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 144 | pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> { |
| 145 | let device_file = OpenOptions::new().read(true).write(true).open(&path)?; |
| 146 | loop_clr_fd(&device_file)?; |
| 147 | Ok(()) |
| 148 | } |