Skip to main content

kernel/mm/vmm/
vma.rs

1// SPDX-License-Identifier: GPL-3.0-only
2//! Type that represents virtual memory areas which are used to mark certain memory read, write, user or execute
3//!
4//! Authors: MarioS271
5
6use crate::lib::addr::VirtAddr;
7use crate::lib::macros::bitflags::bitflags;
8use core::borrow::Borrow;
9use core::cmp::Ordering;
10
11/// A type representing virtual memory areas
12/// > **Important**: `end_addr` is exclusive
13pub struct Vma {
14    pub start_addr: VirtAddr,
15    pub end_addr: VirtAddr,
16    pub flags: VmaFlags
17}
18
19impl Vma {
20    /// Checks whether the VMA contains/manages a specific address
21    pub fn contains(&self, addr: VirtAddr) -> bool {
22        if addr >= self.start_addr && addr < self.end_addr {
23            return true;
24        }
25        false
26    }
27
28    /// Returns the size of memory that is managed by this VMA
29    pub fn size(&self) -> u64 {
30        self.end_addr.as_u64() - self.start_addr.as_u64()
31    }
32
33    /// Check whether two VMAs overlap
34    pub fn overlaps(&self, other: &Vma) -> bool {
35        if (self.end_addr <= other.start_addr) || (other.end_addr <= self.start_addr) {
36            return false;
37        }
38        true
39    }
40}
41
42impl Borrow<VirtAddr> for Vma {
43    /// Returns a reference to [`Vma::start_addr`] to make it possible for [`BTreeSet`] to
44    /// compare it with a [`VirtAddr`] directly
45    fn borrow(&self) -> &VirtAddr {
46        &self.start_addr
47    }
48}
49impl PartialEq<Self> for Vma {
50    /// Only checks equality for [`Vma::start_addr`] and no other property
51    fn eq(&self, other: &Self) -> bool {
52        self.start_addr.eq(&other.start_addr)
53    }
54}
55impl Eq for Vma {}
56impl Ord for Vma {
57    /// Compares only [`Vma::start_addr`] and no other property
58    fn cmp(&self, other: &Self) -> Ordering {
59        self.start_addr.cmp(&other.start_addr)
60    }
61}
62impl PartialOrd for Vma {
63    /// Delegates to [`Vma::cmp`]
64    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
65        Some(self.cmp(other))
66    }
67}
68
69bitflags!(
70    /// Flags to describe the properties of a VMA
71    VmaFlags, u8
72);
73impl VmaFlags {
74    pub const READ: Self = Self(1 << 0);
75    pub const WRITE: Self = Self(1 << 1);
76    pub const EXEC: Self = Self(1 << 2);
77    pub const USER: Self = Self(1 << 3);
78}