1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
use core::{fmt, mem, slice};

/// Classes of physical memory regions.
#[derive(Debug)]
pub enum RegionType {
    /// Free for any use.
    Available,
    /// Reserved by firmware.
    Reserved,
    /// Contains ACPI tables, may be reclaimed if those are no longer needed.
    ACPIReclaim,
    /// Used by firmware for non-volatile storage. Don't use.
    ACPINonVolatile,
    /// Unusable.
    Invalid
}

impl From<u32> for RegionType {
    fn from(val: u32) -> RegionType  {
        use self::RegionType::*;
        match val {
            1 => Available,
            2 => Reserved,
            3 => ACPIReclaim,
            4 => ACPINonVolatile,
            _ => Invalid
        }
    }
}

/// Describes a region of physical memory.
#[repr(C, packed)]
pub struct RegionDescriptor {
    /// Base address of region
    base: u64,
    /// Length of region in bytes
    length: u64,
    /// Regiontype
    ty: u32
}

impl fmt::Display for RegionDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let ty: RegionType = self.ty.into();
        write!(f, "{:#016X}-{:#016X}: {:?}", self.base, self.base.wrapping_add(self.length), ty)
    }
}

const BIOS_MEMMAP_LEN: *const u32 = 0x5000 as *const _;
const BIOS_MEMMAP: *const RegionDescriptor = 0x5004 as *const _;

/// Handle to retrieving the physical memory map.
pub struct MemoryMap;

impl MemoryMap {
    /// Return a slice of `RegionDescriptor`s for firmware-reported physical
    /// memory layout.
    pub fn regions() -> &'static [RegionDescriptor] {
        unsafe {
            let item_size = mem::size_of::<RegionDescriptor>();
            let n_items = (*BIOS_MEMMAP_LEN as usize) / item_size;
            assert_eq!(n_items * item_size, *BIOS_MEMMAP_LEN as usize);
            slice::from_raw_parts(BIOS_MEMMAP, n_items)
        }
    }
}