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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//! Interface for Xen Grant Tables
//!
//! "The grant table mechanism [..] allows memory pages to be transferred or shared between virtual machines"

use {
    crate::{
        memory::MachineFrameNumber,
        platform::{self, consts::PAGE_SIZE},
    },
    core::{
        convert::TryInto,
        mem::size_of,
        sync::atomic::{fence, Ordering},
    },
    lazy_static::lazy_static,
    spin::Mutex,
    xen_sys::{
        domid_t, grant_entry_t, grant_ref_t, GTF_accept_transfer, GTF_permit_access, GTF_readonly,
    },
};

pub use error::{Error, GrantStatusError};

mod error;
pub mod operations;

/// Number of grant frames
const NUM_GRANT_FRAMES: usize = 4;

const NUM_RESERVED_ENTRIES: usize = 8;

const NUM_GRANT_ENTRIES: usize = (NUM_GRANT_FRAMES * PAGE_SIZE) / size_of::<grant_entry_t>();

lazy_static! {
    static ref GRANT_TABLE: Mutex<GrantTable> = Mutex::new(GrantTable::new());
}

// Required due to the raw mutable pointer to the grant table not being Send, this is safe as the virtual address it refers to is constant for the lifetime of the GrantTable
unsafe impl Send for GrantTable {}

#[derive(Debug)]
struct GrantTable {
    list: [grant_ref_t; NUM_GRANT_ENTRIES],
    table: *mut grant_entry_t,
}

impl GrantTable {
    fn new() -> Self {
        let list = [0; NUM_GRANT_ENTRIES];

        let table = platform::grant_table::init::<NUM_GRANT_FRAMES>()
            .expect("Failed platform grant table initialization");

        let mut celf = Self { list, table };

        for i in NUM_RESERVED_ENTRIES..NUM_GRANT_ENTRIES {
            celf.put_free_entry(i as u32);
        }

        log::trace!("grant table mapped at {:p}", table);

        celf
    }

    fn put_free_entry(&mut self, reference: grant_ref_t) {
        self.list[reference as usize] = self.list[0];
        self.list[0] = reference;
    }

    fn get_free_entry(&mut self) -> grant_ref_t {
        let reference = self.list[0];
        self.list[0] = self.list[reference as usize];

        assert!(
            reference as usize >= NUM_RESERVED_ENTRIES && (reference as usize) < NUM_GRANT_ENTRIES
        );

        reference
    }

    fn grant_access(
        &mut self,
        domain: domid_t,
        frame: MachineFrameNumber,
        readonly: bool,
    ) -> grant_ref_t {
        let reference = self.get_free_entry();

        let idx: isize = reference
            .try_into()
            .expect("Failed to convert u32 to usize");

        unsafe {
            let mut entry = self.table.offset(idx);
            (*entry).frame = frame.0.try_into().expect("Failed to convert usize to u32");
            (*entry).domid = domain;

            fence(Ordering::SeqCst);

            (*entry).flags = (GTF_permit_access | if readonly { GTF_readonly } else { 0 })
                .try_into()
                .expect("Failed to convert u32 to u16");
        }

        reference
    }

    fn grant_transfer(&mut self, domain: domid_t, frame: MachineFrameNumber) -> grant_ref_t {
        let reference = self.get_free_entry();

        let idx: isize = reference
            .try_into()
            .expect("Failed to convert u32 to usize");

        unsafe {
            let mut entry = *(self.table.offset(idx));
            entry.frame = frame.0.try_into().expect("Failed to convert usize to u32");
            entry.domid = domain;

            fence(Ordering::SeqCst);

            entry.flags = GTF_accept_transfer
                .try_into()
                .expect("Failed to convert u32 to u16");
        }

        reference
    }

    fn grant_end(&mut self, reference: grant_ref_t) {
        unsafe { *(self.table.offset(reference as isize)) }.flags = 0;

        self.put_free_entry(reference);
    }
}

/// Initializes grant table
pub fn init() {
    lazy_static::initialize(&GRANT_TABLE)
}

/// Grants `domain` access to the supplied frame
pub fn grant_access(domain: domid_t, frame: MachineFrameNumber, readonly: bool) -> grant_ref_t {
    GRANT_TABLE.lock().grant_access(domain, frame, readonly)
}

/// Transfers the supplied frame to `domain`
pub fn grant_transfer(domain: domid_t, frame: MachineFrameNumber) -> grant_ref_t {
    GRANT_TABLE.lock().grant_transfer(domain, frame)
}

/// Ends access to the supplied grant reference
pub fn grant_end(reference: grant_ref_t) {
    GRANT_TABLE.lock().grant_end(reference)
}