1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
45use crate::buffer::{BufferFuture, BufferRef, MutableBufferRef};
6use anyhow::{bail, Error};
7use async_trait::async_trait;
8use block_protocol::WriteOptions;
9use futures::channel::oneshot::{channel, Sender};
10use std::future::Future;
11use std::mem::ManuallyDrop;
12use std::ops::{Deref, Range};
13use std::sync::{Arc, OnceLock};
1415pub mod buffer;
16pub mod buffer_allocator;
1718#[cfg(target_os = "fuchsia")]
19pub mod block_device;
2021#[cfg(target_family = "unix")]
22pub mod file_backed_device;
2324pub mod fake_device;
2526#[async_trait]
27/// Device is an abstract representation of an underlying block device.
28pub trait Device: Send + Sync {
29/// Allocates a transfer buffer of at least |size| bytes for doing I/O with the device.
30 /// The actual size of the buffer will be rounded up to a block-aligned size.
31fn allocate_buffer(&self, size: usize) -> BufferFuture<'_>;
3233/// Returns the block size of the device. Buffers are aligned to block-aligned chunks.
34fn block_size(&self) -> u32;
3536/// Returns the number of blocks of the device.
37// TODO(jfsulliv): Should this be async and go query the underlying device?
38fn block_count(&self) -> u64;
3940/// Returns the size in bytes of the device.
41fn size(&self) -> u64 {
42self.block_size() as u64 * self.block_count()
43 }
4445/// Fills |buffer| with blocks read from |offset|.
46async fn read(&self, offset: u64, buffer: MutableBufferRef<'_>) -> Result<(), Error>;
4748/// Writes the contents of |buffer| to the device at |offset|.
49async fn write(&self, offset: u64, buffer: BufferRef<'_>) -> Result<(), Error> {
50self.write_with_opts(offset, buffer, WriteOptions::empty()).await
51}
5253/// Writes the contents of |buffer| to the device at |offset|.
54async fn write_with_opts(
55&self,
56 offset: u64,
57 buffer: BufferRef<'_>,
58 opts: WriteOptions,
59 ) -> Result<(), Error>;
6061/// Trims the given device |range|.
62async fn trim(&self, range: Range<u64>) -> Result<(), Error>;
6364/// Closes the block device. It is an error to continue using the device after this, but close
65 /// itself is idempotent.
66async fn close(&self) -> Result<(), Error>;
6768/// Flush the device.
69async fn flush(&self) -> Result<(), Error>;
7071/// Reopens the device, making it usable again. (Only implemented for testing devices.)
72fn reopen(&self, _read_only: bool) {
73unreachable!();
74 }
75/// Returns whether the device is read-only.
76fn is_read_only(&self) -> bool;
7778/// Returns whether the device supports trim.
79fn supports_trim(&self) -> bool;
8081/// Returns a snapshot of the device.
82fn snapshot(&self) -> Result<DeviceHolder, Error> {
83bail!("Not supported");
84 }
8586/// Discards random blocks since the last flush.
87fn discard_random_since_last_flush(&self) -> Result<(), Error> {
88bail!("Not supported");
89 }
9091/// Poisons a device to panic on drop. Used to find hanging references.
92fn poison(&self) -> Result<(), Error> {
93bail!("Not supported");
94 }
95}
9697// Arc<dyn Device> can easily be cloned and supports concurrent access, but sometimes exclusive
98// access is required, in which case APIs should accept DeviceHolder. It doesn't guarantee there
99// aren't some users that hold an Arc<dyn Device> somewhere, but it does mean that something that
100// accepts a DeviceHolder won't be sharing the device with something else that accepts a
101// DeviceHolder. For example, FxFilesystem accepts a DeviceHolder which means that you cannot
102// create two FxFilesystem instances that are both sharing the same device.
103pub struct DeviceHolder {
104 device: ManuallyDrop<Arc<dyn Device>>,
105 on_drop: OnceLock<Sender<DeviceHolder>>,
106}
107108impl DeviceHolder {
109pub fn new(device: impl Device + 'static) -> Self {
110 DeviceHolder { device: ManuallyDrop::new(Arc::new(device)), on_drop: OnceLock::new() }
111 }
112113// Ensures there are no dangling references to the device. Useful for tests to ensure orderly
114 // shutdown.
115pub fn ensure_unique(&self) {
116assert_eq!(Arc::strong_count(&self.device), 1);
117 }
118119pub fn take_when_dropped(&self) -> impl Future<Output = DeviceHolder> {
120let (sender, receiver) = channel::<DeviceHolder>();
121self.on_drop
122 .set(sender)
123 .unwrap_or_else(|_| panic!("take_when_dropped should only be called once"));
124async { receiver.await.unwrap() }
125 }
126}
127128impl Drop for DeviceHolder {
129fn drop(&mut self) {
130if let Some(sender) = self.on_drop.take() {
131// SAFETY: `device` is not used again.
132let device = ManuallyDrop::new(unsafe { ManuallyDrop::take(&mut self.device) });
133// We don't care if this fails to send.
134let _ = sender.send(DeviceHolder { device, on_drop: OnceLock::new() });
135 } else {
136// SAFETY: `device` is not used again.
137unsafe { ManuallyDrop::drop(&mut self.device) }
138 }
139 }
140}
141142impl Deref for DeviceHolder {
143type Target = Arc<dyn Device>;
144145fn deref(&self) -> &Self::Target {
146&self.device
147 }
148}
149150#[cfg(test)]
151mod tests {
152use super::DeviceHolder;
153use crate::fake_device::FakeDevice;
154155#[fuchsia::test]
156async fn test_take_when_dropped() {
157let holder = DeviceHolder::new(FakeDevice::new(1, 512));
158let fut = holder.take_when_dropped();
159 std::mem::drop(holder);
160 fut.await.ensure_unique();
161 }
162}