|
| 1 | +// SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | + |
| 3 | +//! Defines wrapper allocated by PCI Root Bridge protocol. |
| 4 | +
|
| 5 | +use core::mem::{ManuallyDrop, MaybeUninit}; |
| 6 | +use core::num::NonZeroUsize; |
| 7 | +use core::ops::{Deref, DerefMut}; |
| 8 | +use core::ptr::NonNull; |
| 9 | +use log::debug; |
| 10 | +use uefi_raw::Status; |
| 11 | +use uefi_raw::protocol::pci::root_bridge::PciRootBridgeIoProtocol; |
| 12 | + |
| 13 | +/// Smart pointer for wrapping owned buffer allocated by PCI Root Bridge protocol. |
| 14 | +#[derive(Debug)] |
| 15 | +pub struct PciBuffer<'p, T> { |
| 16 | + pub(crate) base: NonNull<T>, |
| 17 | + pub(crate) pages: NonZeroUsize, |
| 18 | + pub(crate) proto: &'p PciRootBridgeIoProtocol, |
| 19 | +} |
| 20 | + |
| 21 | +impl<'p, T> PciBuffer<'p, MaybeUninit<T>> { |
| 22 | + /// Assumes the contents of this buffer have been initialized. |
| 23 | + /// |
| 24 | + /// # Safety |
| 25 | + /// Callers of this function must guarantee that value stored is valid. |
| 26 | + #[must_use] |
| 27 | + pub unsafe fn assume_init(self) -> PciBuffer<'p, T> { |
| 28 | + let old = ManuallyDrop::new(self); |
| 29 | + PciBuffer { |
| 30 | + base: old.base.cast(), |
| 31 | + pages: old.pages, |
| 32 | + proto: old.proto, |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl<'p, T> AsRef<T> for PciBuffer<'p, T> { |
| 38 | + fn as_ref(&self) -> &T { |
| 39 | + unsafe { self.base.as_ref() } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl<'p, T> AsMut<T> for PciBuffer<'p, T> { |
| 44 | + fn as_mut(&mut self) -> &mut T { |
| 45 | + unsafe { self.base.as_mut() } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl<'p, T> Deref for PciBuffer<'p, T> { |
| 50 | + type Target = T; |
| 51 | + |
| 52 | + fn deref(&self) -> &Self::Target { |
| 53 | + self.as_ref() |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +impl<'p, T> DerefMut for PciBuffer<'p, T> { |
| 58 | + fn deref_mut(&mut self) -> &mut Self::Target { |
| 59 | + self.as_mut() |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +impl<'p, T> Drop for PciBuffer<'p, T> { |
| 64 | + fn drop(&mut self) { |
| 65 | + let status = unsafe { |
| 66 | + (self.proto.free_buffer)(self.proto, self.pages.get(), self.base.as_ptr().cast()) |
| 67 | + }; |
| 68 | + match status { |
| 69 | + Status::SUCCESS => { |
| 70 | + debug!( |
| 71 | + "Freed {} pages at 0x{:X}", |
| 72 | + self.pages.get(), |
| 73 | + self.base.as_ptr().addr() |
| 74 | + ); |
| 75 | + } |
| 76 | + Status::INVALID_PARAMETER => { |
| 77 | + panic!("PciBuffer was not created through valid protocol usage!") |
| 78 | + } |
| 79 | + _ => unreachable!(), |
| 80 | + } |
| 81 | + } |
| 82 | +} |
0 commit comments