|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | + |
| 3 | +//! File system buffers. |
| 4 | +//! |
| 5 | +//! C headers: [`include/linux/buffer_head.h`](../../../include/linux/buffer_head.h) |
| 6 | +
|
| 7 | +use crate::types::{ARef, AlwaysRefCounted, Opaque}; |
| 8 | +use core::ptr; |
| 9 | + |
| 10 | +/// Wraps the kernel's `struct buffer_head`. |
| 11 | +/// |
| 12 | +/// # Invariants |
| 13 | +/// |
| 14 | +/// Instances of this type are always ref-counted, that is, a call to `get_bh` ensures that the |
| 15 | +/// allocation remains valid at least until the matching call to `put_bh`. |
| 16 | +#[repr(transparent)] |
| 17 | +pub struct Head(Opaque<bindings::buffer_head>); |
| 18 | + |
| 19 | +// SAFETY: The type invariants guarantee that `INode` is always ref-counted. |
| 20 | +unsafe impl AlwaysRefCounted for Head { |
| 21 | + fn inc_ref(&self) { |
| 22 | + // SAFETY: The existence of a shared reference means that the refcount is nonzero. |
| 23 | + unsafe { bindings::get_bh(self.0.get()) }; |
| 24 | + } |
| 25 | + |
| 26 | + unsafe fn dec_ref(obj: ptr::NonNull<Self>) { |
| 27 | + // SAFETY: The safety requirements guarantee that the refcount is nonzero. |
| 28 | + unsafe { bindings::put_bh(obj.cast().as_ptr()) } |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +impl Head { |
| 33 | + /// Returns the block data associated with the given buffer head. |
| 34 | + pub fn data(&self) -> &[u8] { |
| 35 | + let h = self.0.get(); |
| 36 | + // SAFETY: The existence of a shared reference guarantees that the buffer head is |
| 37 | + // available and so we can access its contents. |
| 38 | + unsafe { core::slice::from_raw_parts((*h).b_data.cast(), (*h).b_size) } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +/// A view of a buffer. |
| 43 | +/// |
| 44 | +/// It may contain just a contiguous subset of the buffer. |
| 45 | +pub struct View { |
| 46 | + head: ARef<Head>, |
| 47 | + offset: usize, |
| 48 | + size: usize, |
| 49 | +} |
| 50 | + |
| 51 | +impl View { |
| 52 | + #[allow(dead_code)] |
| 53 | + pub(crate) fn new(head: ARef<Head>, offset: usize, size: usize) -> Self { |
| 54 | + Self { head, size, offset } |
| 55 | + } |
| 56 | + |
| 57 | + /// Returns the view of the buffer head. |
| 58 | + pub fn data(&self) -> &[u8] { |
| 59 | + &self.head.data()[self.offset..][..self.size] |
| 60 | + } |
| 61 | +} |
0 commit comments