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}; |
| 27 | use std::fs::{File, OpenOptions}; |
| 28 | use std::os::unix::io::AsRawFd; |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | use std::thread; |
| 31 | use std::time::{Duration, Instant}; |
| 32 | |
| 33 | use crate::loopdevice::sys::*; |
| 34 | use crate::util::*; |
| 35 | |
| 36 | // These are old-style ioctls, thus *_bad. |
| 37 | nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE); |
| 38 | nix::ioctl_write_ptr_bad!(_loop_configure, LOOP_CONFIGURE, loop_config); |
| 39 | nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD); |
| 40 | |
| 41 | fn loop_ctl_get_free(ctrl_file: &File) -> Result<i32> { |
| 42 | // SAFETY: this ioctl changes the state in kernel, but not the state in this process. |
| 43 | // The returned device number is a global resource; not tied to this process. So, we don't |
| 44 | // need to keep track of it. |
| 45 | Ok(unsafe { _loop_ctl_get_free(ctrl_file.as_raw_fd()) }?) |
| 46 | } |
| 47 | |
| 48 | fn loop_configure(device_file: &File, config: &loop_config) -> Result<i32> { |
| 49 | // SAFETY: this ioctl changes the state in kernel, but not the state in this process. |
| 50 | Ok(unsafe { _loop_configure(device_file.as_raw_fd(), config) }?) |
| 51 | } |
| 52 | |
| 53 | fn loop_clr_fd(device_file: &File) -> Result<i32> { |
| 54 | // SAFETY: this ioctl disassociates the loop device with `device_file`, where the FD will |
| 55 | // remain opened afterward. The association itself is kept for open FDs. |
| 56 | Ok(unsafe { _loop_clr_fd(device_file.as_raw_fd()) }?) |
| 57 | } |
| 58 | |
| 59 | /// Creates a loop device and attach the given file at `path` as the backing store. |
| 60 | pub fn attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 61 | // Attaching a file to a loop device can make a race condition; a loop device number obtained |
| 62 | // from LOOP_CTL_GET_FREE might have been used by another thread or process. In that case the |
| 63 | // subsequet LOOP_CONFIGURE ioctl returns with EBUSY. Try until it succeeds. |
| 64 | // |
| 65 | // Note that the timing parameters below are chosen rather arbitrarily. In practice (i.e. |
| 66 | // inside Microdroid) we can't experience the race condition because `apkverity` is the only |
| 67 | // user of /dev/loop-control at the moment. This loop is mostly for testing where multiple |
| 68 | // tests run concurrently. |
| 69 | const TIMEOUT: Duration = Duration::from_secs(1); |
| 70 | const INTERVAL: Duration = Duration::from_millis(10); |
| 71 | |
| 72 | let begin = Instant::now(); |
| 73 | loop { |
| 74 | match try_attach(&path, offset, size_limit) { |
| 75 | Ok(loop_dev) => return Ok(loop_dev), |
| 76 | Err(e) => { |
| 77 | if begin.elapsed() > TIMEOUT { |
| 78 | return Err(e); |
| 79 | } |
| 80 | } |
| 81 | }; |
| 82 | thread::sleep(INTERVAL); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | fn try_attach<P: AsRef<Path>>(path: P, offset: u64, size_limit: u64) -> Result<PathBuf> { |
| 87 | // Get a free loop device |
| 88 | wait_for_path(LOOP_CONTROL)?; |
| 89 | let ctrl_file = OpenOptions::new() |
| 90 | .read(true) |
| 91 | .write(true) |
| 92 | .open(LOOP_CONTROL) |
| 93 | .context("Failed to open loop control")?; |
| 94 | let num = loop_ctl_get_free(&ctrl_file).context("Failed to get free loop device")?; |
| 95 | |
| 96 | // Construct the loop_config struct |
| 97 | let backing_file = OpenOptions::new() |
| 98 | .read(true) |
| 99 | .open(&path) |
| 100 | .context(format!("failed to open {:?}", path.as_ref()))?; |
| 101 | // SAFETY: zero initialized C structs is safe |
| 102 | let mut config = unsafe { std::mem::MaybeUninit::<loop_config>::zeroed().assume_init() }; |
| 103 | config.fd = backing_file.as_raw_fd() as u32; |
| 104 | config.block_size = 4096; |
| 105 | config.info.lo_offset = offset; |
| 106 | config.info.lo_sizelimit = size_limit; |
| 107 | config.info.lo_flags |= Flag::LO_FLAGS_DIRECT_IO | Flag::LO_FLAGS_READ_ONLY; |
| 108 | |
| 109 | // Special case: don't use direct IO when the backing file is already a loop device, which |
| 110 | // happens only during test. DirectIO-on-loop-over-loop makes the outer loop device |
| 111 | // unaccessible. |
| 112 | #[cfg(test)] |
| 113 | if path.as_ref().to_str().unwrap().starts_with("/dev/loop") { |
| 114 | config.info.lo_flags.remove(Flag::LO_FLAGS_DIRECT_IO); |
| 115 | } |
| 116 | |
| 117 | // Configure the loop device to attach the backing file |
| 118 | let device_path = format!("/dev/loop{}", num); |
| 119 | wait_for_path(&device_path)?; |
| 120 | let device_file = OpenOptions::new() |
| 121 | .read(true) |
| 122 | .write(true) |
| 123 | .open(&device_path) |
| 124 | .context(format!("failed to open {:?}", &device_path))?; |
| 125 | loop_configure(&device_file, &mut config) |
| 126 | .context(format!("Failed to configure {:?}", &device_path))?; |
| 127 | |
| 128 | Ok(PathBuf::from(device_path)) |
| 129 | } |
| 130 | |
| 131 | /// Detaches backing file from the loop device `path`. |
| 132 | pub fn detach<P: AsRef<Path>>(path: P) -> Result<()> { |
| 133 | let device_file = OpenOptions::new().read(true).write(true).open(&path)?; |
| 134 | loop_clr_fd(&device_file)?; |
| 135 | Ok(()) |
| 136 | } |