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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
//! XenStore interface
//!
//! "The XenStore is a storage system shared between Xen guests. It is a
//! simple hierarchical storage system, maintained by Domain 0 and accessed
//! via a shared memory page and an event channel." - The Definitive Guide
//! to the Xen Hypervisor, Chapter 8

use {
    crate::{
        events::event_channel_op,
        memory::{MachineFrameNumber, VirtualAddress},
        START_INFO,
    },
    alloc::{borrow::ToOwned, string::String, vec, vec::Vec},
    core::{
        convert::{TryFrom, TryInto},
        str,
        sync::atomic::{fence, Ordering},
    },
    lazy_static::lazy_static,
    log::{debug, error},
    spin::Mutex,
    xen_sys::{
        evtchn_port_t, evtchn_send, xenstore_domain_interface, xsd_sockmsg,
        xsd_sockmsg_type_XS_DIRECTORY, xsd_sockmsg_type_XS_READ, xsd_sockmsg_type_XS_WRITE,
        EVTCHNOP_send, XENSTORE_RING_SIZE,
    },
};

lazy_static! {
    /// Global XenStore interface
    static ref XENSTORE: Mutex<XenStore> = {
        let event_channel_port = unsafe { *START_INFO }.store_evtchn;

        // convert store_mfn to a virtual address
        let interface_ptr = VirtualAddress::from(MachineFrameNumber(
            unsafe { *START_INFO }
                .store_mfn
                .try_into()
                .expect("Failed to convert u64 to usize"),
        ))
        .0 as *mut xenstore_domain_interface;

        // convert the mutable pointer to a mutable reference with a static lifetime, using lazy_static ensures only a single mutable reference exists
        let interface =
            unsafe { interface_ptr.as_mut() }.expect("XenStore interface pointer was null");

        Mutex::new(XenStore {
            event_channel_port,
            interface,
            req_id: 0,
        })
    };
}

/// Initialize XenStore
pub fn init() {
    lazy_static::initialize(&XENSTORE);
    debug!("Initialized XenStore");
}

/// Write a key-value pair to the XenStore
pub fn write<K: AsRef<str>, V: AsRef<str>>(key: K, value: V) {
    XENSTORE.lock().write(key.as_ref(), value.as_ref())
}

/// Read a key's value from the XenStore
pub fn read<K: AsRef<str>>(key: K) -> String {
    XENSTORE.lock().read(key.as_ref())
}

/// List contents of directory
pub fn ls<K: AsRef<str>>(key: K) -> Vec<String> {
    XENSTORE.lock().ls(key.as_ref())
}

/// Read the current domain's ID
pub fn domain_id() -> u32 {
    XENSTORE.lock().domain_id()
}

/// XenStore interface
#[derive(Debug)]
struct XenStore {
    event_channel_port: evtchn_port_t,
    interface: &'static mut xenstore_domain_interface,
    req_id: u32,
}

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

impl XenStore {
    /// Write a key-value pair to the XenStore
    fn write(&mut self, key: &str, value: &str) {
        let msg = &mut xsd_sockmsg {
            type_: xsd_sockmsg_type_XS_WRITE,
            req_id: self.req_id,
            tx_id: 0,
            len: (key.len() + value.len())
                .try_into()
                .expect("Failed to convert usize to u32"),
        };

        //TODO: validate that this is safe
        let msg_bytes = unsafe {
            core::mem::transmute::<&mut xsd_sockmsg, &mut [u8; core::mem::size_of::<xsd_sockmsg>()]>(
                msg,
            )
        };

        self.write_request(msg_bytes);
        self.write_request(key.as_bytes());
        self.write_request(value.as_bytes());

        self.notify();

        self.read_response(msg_bytes);
        self.ignore(msg.len.try_into().expect("Failed to convert u32 to usize"));

        self.req_id += 1;

        if msg.req_id != (self.req_id - 1) {
            panic!("XenStore read failed due to unexpected message request ID");
        }
    }

    /// Perform initial steps of a read operation, returning the length of value now ready to be read
    ///
    /// The read operation was split like this to allow for building operations requiring reads without allocating (e.g. domain_id)
    fn read_preamble(&mut self, key: &str) -> usize {
        let msg = &mut xsd_sockmsg {
            type_: xsd_sockmsg_type_XS_READ,
            req_id: self.req_id,
            tx_id: 0,
            len: key
                .len()
                .try_into()
                .expect("Failed to convert usize to u32"),
        };

        //TODO: validate that this is safe
        let msg_bytes = unsafe {
            core::mem::transmute::<&mut xsd_sockmsg, &mut [u8; core::mem::size_of::<xsd_sockmsg>()]>(
                msg,
            )
        };

        self.write_request(msg_bytes);
        self.write_request(key.as_bytes());

        self.notify();

        self.read_response(msg_bytes);

        let msg_len = msg.len.try_into().expect("Failed to convert u32 to usize");
        self.req_id += 1;

        if msg.req_id != (self.req_id - 1) {
            self.ignore(msg_len);
            panic!("XenStore read failed due to unexpected message request ID");
        }

        msg_len
    }

    /// Read a key's value from the XenStore
    ///
    /// Requires that the allocator be initialised before calling
    fn read(&mut self, key: &str) -> String {
        let msg_len = self.read_preamble(key);

        let mut buf = vec![0; msg_len];

        self.read_response(&mut buf);

        // remove nul terminator if it exists
        if let Some(0) = buf.last() {
            buf.truncate(buf.len() - 1);
        }

        // does not reallocate
        String::from_utf8(buf).expect("XenStore value contains invalid UTF-8")
    }

    /// List contents of directory
    fn ls(&mut self, key: &str) -> Vec<String> {
        let msg = &mut xsd_sockmsg {
            type_: xsd_sockmsg_type_XS_DIRECTORY,
            req_id: self.req_id,
            tx_id: 0,
            len: key
                .len()
                .try_into()
                .expect("Failed to convert usize to u32"),
        };

        //TODO: validate that this is safe
        let msg_bytes = unsafe {
            core::mem::transmute::<&mut xsd_sockmsg, &mut [u8; core::mem::size_of::<xsd_sockmsg>()]>(
                msg,
            )
        };

        self.write_request(msg_bytes);
        self.write_request(key.as_bytes());

        self.notify();

        self.read_response(msg_bytes);

        let msg_len = msg.len.try_into().expect("Failed to convert u32 to usize");
        self.req_id += 1;

        if msg.req_id != (self.req_id - 1) {
            self.ignore(msg_len);
            panic!("XenStore read failed due to unexpected message request ID");
        }

        let mut value = vec![0; msg_len];

        self.read_response(&mut value);

        value
            .split(|&c| c == 0)
            .map(|slice| match str::from_utf8(slice) {
                Ok(str) => str,
                Err(e) => {
                    error!(
                        "XenStore directory contained non UTF-8 key ({:?}), error: {}",
                        slice, e
                    );
                    ""
                }
            })
            .filter(|s| !s.is_empty())
            .map(|s| s.to_owned())
            .collect()
    }

    /// Read the current domain's ID
    fn domain_id(&mut self) -> u32 {
        // fill with newlines so that str::trim removes excess bytes
        let mut buf = [b'\n'; 4];

        let len = self.read_preamble("domid\0");
        self.read_response(&mut buf[..len]);

        // convert slice to str
        str::from_utf8(&buf)
            .expect("XenStore domid value contains invalid UTF-8")
            // remove leading and trailing whitespace
            .trim()
            // parse as u32
            .parse()
            .expect("Failed to parse XenStore domid value as u32")
    }

    fn notify(&self) {
        let mut event = evtchn_send {
            port: self.event_channel_port,
        };
        event_channel_op(EVTCHNOP_send, &mut event as *mut _ as u64);
    }

    fn ignore(&mut self, len: usize) {
        let mut buffer = [0u8; XENSTORE_RING_SIZE as usize];
        self.read_response(&mut buffer[..len]);
    }

    fn write_request(&mut self, mut message: &[u8]) {
        assert!(
            message.len()
                < XENSTORE_RING_SIZE
                    .try_into()
                    .expect("Failed to convert u32 to usize")
        );

        let mut i = self.interface.req_prod;
        let mut length = message.len();

        while length > 0 {
            let mut data;

            loop {
                data = i - self.interface.req_cons;
                fence(Ordering::SeqCst);

                if !(usize::try_from(data).expect("Failed to convert u32 to usize")
                    >= self.interface.req.len())
                {
                    break;
                }
            }

            let ring_index =
                mask_xenstore_idx(i.try_into().expect("Failed to convert u32 to usize"));
            self.interface.req[ring_index] = message[0] as i8;
            message = &message[1..];

            length -= 1;
            i += 1;
        }

        fence(Ordering::SeqCst);
        self.interface.req_prod = i;
    }

    fn read_response(&mut self, mut message: &mut [u8]) {
        let mut i = self.interface.rsp_cons;
        let mut length = message.len();

        while length > 0 {
            let mut data;

            loop {
                data = self.interface.rsp_prod - i;
                fence(Ordering::SeqCst);

                if !(data == 0) {
                    break;
                }
            }

            let ring_index =
                mask_xenstore_idx(i.try_into().expect("Failed to convert u32 to usize"));
            message[0] = self.interface.rsp[ring_index] as u8;
            message = &mut message[1..];

            length -= 1;
            i += 1;
        }

        self.interface.rsp_cons = i;
    }
}

fn mask_xenstore_idx(idx: usize) -> usize {
    idx & (usize::try_from(XENSTORE_RING_SIZE).expect("Failed to convert u32 to usize") - 1)
}