Skip to content

Commit

Permalink
Wait for ueventd to create loop device on Android
Browse files Browse the repository at this point in the history
  • Loading branch information
tiann committed Feb 14, 2023
1 parent 64a8ddb commit 609f549
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ direct_io = []
errno = "0.2.8"
libc = "0.2.105"

[target.'cfg(target_os = "android")'.dependencies]
inotify = "0.10"

[build-dependencies]
bindgen = { version = "0.60.1", default-features = false, features = ["runtime"] }

Expand Down
53 changes: 52 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ impl LoopControl {
LOOP_CTL_GET_FREE as IoctlRequest,
)
})?;
LoopDevice::open(&format!("{}{}", LOOP_PREFIX, dev_num))
let dev = format!("{}{}", LOOP_PREFIX, dev_num);
#[cfg(target_os = "android")]
let _ = wait_until_file_created(&dev);
LoopDevice::open(&dev)
}

/// Add and opens a new loop device.
Expand Down Expand Up @@ -512,3 +515,51 @@ fn ioctl_to_error(ret: i32) -> io::Result<i32> {
Ok(ret)
}
}

// Android doesn't use devtmpfs. Instead device nodes under /dev are
// created by userspace daemon ueventd. There could be a noticeable delay
// between LOOP_CTL_GET_FREE issued and loop device created, so we need to
// wait until it is created and then continue.
#[cfg(target_os = "android")]
fn wait_until_file_created<P: AsRef<Path>>(dev: P) -> io::Result<()> {
let path = dev.as_ref();
if path.exists() {
return Ok(());
}

use inotify::{Inotify, WatchMask};
let mut inotify = Inotify::init()?;
// We need to watch the parent directory because the file may not exist yet
// And we can be sure that the parent must exist
let parent_dir = path.parent().ok_or(io::Error::new(
io::ErrorKind::Other,
format!("Cannot get parent directory of {}", path.display()),
))?;
inotify.add_watch(parent_dir, WatchMask::CREATE)?;

// the file may have been created when we are adding the watch
if path.exists() {
return Ok(());
}
// 1024 is enough for most cases
let mut buffer = [0; 1024];
let start = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(2);
loop {
if start.elapsed() > timeout {
break;
}
if let Ok(events) = inotify.read_events(&mut buffer) {
for event in events {
if event.name == path.file_name() {
return Ok(());
}
}
}
}

Err(io::Error::new(
io::ErrorKind::Other,
format!("Timeout waiting for file {} being created!", path.display()),
))
}

0 comments on commit 609f549

Please sign in to comment.