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); |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 40 | nix::ioctl_write_int_bad!(_loop_set_fd, LOOP_SET_FD); |
| 41 | nix::ioctl_write_ptr_bad!(_loop_set_status64, LOOP_SET_STATUS64, loop_info64); |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 42 | #[cfg(test)] |
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 | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 52 | fn loop_set_fd(device_file: &File, fd: i32) -> 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 | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 54 | Ok(unsafe { _loop_set_fd(device_file.as_raw_fd(), fd) }?) |
| 55 | } |
| 56 | |
| 57 | fn loop_set_status64(device_file: &File, info: &loop_info64) -> Result<i32> { |
| 58 | // SAFETY: this ioctl changes the state in kernel, but not the state in this process. |
| 59 | Ok(unsafe { _loop_set_status64(device_file.as_raw_fd(), info) }?) |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 60 | } |
| 61 | |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 62 | #[cfg(test)] |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 63 | fn loop_clr_fd(device_file: &File) -> Result<i32> { |
| 64 | // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will |
| 65 | // remain opened afterward. The association itself is kept for open FDs. |
| 66 | Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?) |
| 67 | } |
| 68 | |
| 69 | /// Creates a loop device and attach the given file at `path` as the backing store. |
| 70 | pub fn attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 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 |
| 73 | // subsequet LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds. |
| 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 { |
| 84 | match try_attach(&path, offset, size_limit) { |
| 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 | |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 102 | fn try_attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 103 | // Get a free loop device |
| 104 | wait_for_path(LOOP_CONTROL)?; |
| 105 | let ctrl_file = OpenOptions::new() |
| 106 | .read(true) |
| 107 | .write(true) |
| 108 | .open(LOOP_CONTROL) |
| 109 | .context("Failed to open loop control")?; |
| 110 | let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?; |
| 111 | |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 112 | // Construct the loop_info64 struct |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 113 | let backing_file = OpenOptions::new() |
| 114 | .read(true) |
| 115 | .open(&path) |
| 116 | .context(format!("failed to open {:?}", path.as_ref()))?; |
Jiyong Park | 3c327d2 | 2021-06-08 20:51:54 +0900 | [diff] [blame] | 117 | // safe because the size of the array is the same as the size of the struct |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 118 | let mut info: loop_info64 = |
| 119 | *DataInit::from_mut_slice(&mut [0; size_of::<loop_info64>()]).unwrap(); |
| 120 | info.lo_offset = offset; |
| 121 | info.lo_sizelimit = size_limit; |
| 122 | info.lo_flags |= Flag::LO_FLAGS_DIRECT_IO | Flag::LO_FLAGS_READ_ONLY; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 123 | |
| 124 | // Special case: don't use direct IO when the backing file is already a loop device, which |
| 125 | // happens only during test. DirectIO-on-loop-over-loop makes the outer loop device |
| 126 | // unaccessible. |
| 127 | #[cfg(test)] |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 128 | if path.as_ref().to_str().unwrap().starts_with(LOOP_DEV_PREFIX) { |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 129 | info.lo_flags.remove(Flag::LO_FLAGS_DIRECT_IO); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 130 | } |
| 131 | |
| 132 | // Configure the loop device to attach the backing file |
Jiyong Park | 5f0ebea | 2021-06-07 12:53:35 +0900 | [diff] [blame] | 133 | let device_path = format!("{}{}", LOOP_DEV_PREFIX, num); |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 134 | wait_for_path(&device_path)?; |
| 135 | let device_file = OpenOptions::new() |
| 136 | .read(true) |
| 137 | .write(true) |
| 138 | .open(&device_path) |
| 139 | .context(format!("failed to open {:?}", &device_path))?; |
Jooyung Han | 7ce2e53 | 2021-06-16 16:52:02 +0900 | [diff] [blame^] | 140 | loop_set_fd(&device_file, backing_file.as_raw_fd() as i32)?; |
| 141 | loop_set_status64(&device_file, &info)?; |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 142 | |
| 143 | Ok(PathBuf::from(device_path)) |
| 144 | } |
| 145 | |
| 146 | /// Detaches backing file from the loop device `path`. |
Jiyong Park | 99a35b8 | 2021-06-07 10:13:44 +0900 | [diff] [blame] | 147 | #[cfg(test)] |
Jiyong Park | 86c9b08 | 2021-06-04 19:03:48 +0900 | [diff] [blame] | 148 | pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> { |
| 149 | let device_file = OpenOptions::new().read(true).write(true).open(&path)?; |
| 150 | loop_clr_fd(&device_file)?; |
| 151 | Ok(()) |
| 152 | } |