blob: 376abd4198a48f6150c95ba41f6957c994c7a6fc [file] [log] [blame]
Jiyong Park86c9b082021-06-04 19:03:48 +09001/*
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
24mod sys;
25
26use anyhow::{Context, Result};
Jiyong Park3c327d22021-06-08 20:51:54 +090027use data_model::DataInit;
Jiyong Park86c9b082021-06-04 19:03:48 +090028use std::fs::{File, OpenOptions};
Jiyong Park3c327d22021-06-08 20:51:54 +090029use std::mem::size_of;
Jiyong Park86c9b082021-06-04 19:03:48 +090030use std::os::unix::io::AsRawFd;
31use std::path::{Path, PathBuf};
32use std::thread;
33use std::time::{Duration, Instant};
34
35use crate::loopdevice::sys::*;
36use crate::util::*;
37
38// These are old-style ioctls, thus *_bad.
39nix::ioctl_none_bad!(_loop_ctl_get_free, LOOP_CTL_GET_FREE);
Jooyung Han7ce2e532021-06-16 16:52:02 +090040nix::ioctl_write_int_bad!(_loop_set_fd, LOOP_SET_FD);
41nix::ioctl_write_ptr_bad!(_loop_set_status64, LOOP_SET_STATUS64, loop_info64);
Jiyong Park99a35b82021-06-07 10:13:44 +090042#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090043nix::ioctl_none_bad!(_loop_clr_fd, LOOP_CLR_FD);
44
45fn 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 Han7ce2e532021-06-16 16:52:02 +090052fn loop_set_fd(device_file: &File, fd: i32) -> Result<i32> {
Jiyong Park86c9b082021-06-04 19:03:48 +090053 // SAFETY: this ioctl changes the state in kernel, but not the state in this process.
Jooyung Han7ce2e532021-06-16 16:52:02 +090054 Ok(unsafe { _loop_set_fd(device_file.as_raw_fd(), fd) }?)
55}
56
57fn 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 Park86c9b082021-06-04 19:03:48 +090060}
61
Jiyong Park99a35b82021-06-07 10:13:44 +090062#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +090063fn 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.
70pub 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 Park5f0ebea2021-06-07 12:53:35 +090096#[cfg(not(target_os = "android"))]
97const LOOP_DEV_PREFIX: &str = "/dev/loop";
98
99#[cfg(target_os = "android")]
100const LOOP_DEV_PREFIX: &str = "/dev/block/loop";
101
Jiyong Park86c9b082021-06-04 19:03:48 +0900102fn 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 Han7ce2e532021-06-16 16:52:02 +0900112 // Construct the loop_info64 struct
Jiyong Park86c9b082021-06-04 19:03:48 +0900113 let backing_file = OpenOptions::new()
114 .read(true)
115 .open(&path)
116 .context(format!("failed to open {:?}", path.as_ref()))?;
Jiyong Park3c327d22021-06-08 20:51:54 +0900117 // safe because the size of the array is the same as the size of the struct
Jooyung Han7ce2e532021-06-16 16:52:02 +0900118 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 Park86c9b082021-06-04 19:03:48 +0900123
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 Park5f0ebea2021-06-07 12:53:35 +0900128 if path.as_ref().to_str().unwrap().starts_with(LOOP_DEV_PREFIX) {
Jooyung Han7ce2e532021-06-16 16:52:02 +0900129 info.lo_flags.remove(Flag::LO_FLAGS_DIRECT_IO);
Jiyong Park86c9b082021-06-04 19:03:48 +0900130 }
131
132 // Configure the loop device to attach the backing file
Jiyong Park5f0ebea2021-06-07 12:53:35 +0900133 let device_path = format!("{}{}", LOOP_DEV_PREFIX, num);
Jiyong Park86c9b082021-06-04 19:03:48 +0900134 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 Han7ce2e532021-06-16 16:52:02 +0900140 loop_set_fd(&device_file, backing_file.as_raw_fd() as i32)?;
141 loop_set_status64(&device_file, &info)?;
Jiyong Park86c9b082021-06-04 19:03:48 +0900142
143 Ok(PathBuf::from(device_path))
144}
145
146/// Detaches backing file from the loop device `path`.
Jiyong Park99a35b82021-06-07 10:13:44 +0900147#[cfg(test)]
Jiyong Park86c9b082021-06-04 19:03:48 +0900148pub 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}