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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// SPDX-License-Identifier: BSD-3-Clause
// Copyright(c) 2023-2024 Intel Corporation.

//! The TDVMCALL helps invoke services from the host VMM. From the perspective of the host VMM, the TDVMCALL is a trap-like, VM exit into
//! the host VMM, reported via the SEAMRET instruction flow.
//! By design, after the SEAMRET, the host VMM services the request specified in the parameters
//! passed by the TD during the TDG.VP.VMCALL (that are passed via SEAMRET to the VMM), then
//! resumes the TD via a SEAMCALL [TDH.VP.ENTER] invocation.
extern crate alloc;

use alloc::fmt;
use core::fmt::Write;

use bitflags::bitflags;
use x86_64::{
    registers::rflags::{self, RFlags},
    structures::port::PortRead,
};

use crate::asm::asm_td_vmcall;

/// TDVMCALL Instruction Leaf Numbers Definition.
#[repr(u64)]
pub enum TdVmcallNum {
    Cpuid = 0x0000a,
    Hlt = 0x0000c,
    Io = 0x0001e,
    Rdmsr = 0x0001f,
    Wrmsr = 0x00020,
    RequestMmio = 0x00030,
    Wbinvd = 0x00036,
    GetTdVmcallInfo = 0x10000,
    Mapgpa = 0x10001,
    GetQuote = 0x10002,
    SetupEventNotifyInterrupt = 0x10004,
    Service = 0x10005,
}

const SERIAL_IO_PORT: u16 = 0x3F8;
const SERIAL_LINE_STS: u16 = 0x3FD;
const IO_READ: u64 = 0;
const IO_WRITE: u64 = 1;

#[derive(Debug, PartialEq)]
pub enum TdVmcallError {
    /// TDCALL[TDG.VP.VMCALL] sub-function invocation must be retried.
    TdxRetry,
    /// Invalid operand to TDG.VP.VMCALL sub-function.
    TdxOperandInvalid,
    /// GPA already mapped.
    TdxGpaInuse,
    /// Operand (address) aligned error.
    TdxAlignError,
    Other,
}

impl From<u64> for TdVmcallError {
    fn from(val: u64) -> Self {
        match val {
            0x1 => Self::TdxRetry,
            0x8000_0000_0000_0000 => Self::TdxOperandInvalid,
            0x8000_0000_0000_0001 => Self::TdxGpaInuse,
            0x8000_0000_0000_0002 => Self::TdxAlignError,
            _ => Self::Other,
        }
    }
}

#[repr(C)]
#[derive(Default)]
pub(crate) struct TdVmcallArgs {
    r10: u64,
    r11: u64,
    r12: u64,
    r13: u64,
    r14: u64,
    r15: u64,
}

#[repr(C)]
#[derive(Debug, Default)]
pub struct CpuIdInfo {
    pub eax: usize,
    pub ebx: usize,
    pub ecx: usize,
    pub edx: usize,
}

pub enum Direction {
    In,
    Out,
}

pub enum Operand {
    Dx,
    Immediate,
}

pub enum IoSize {
    Size1 = 1,
    Size2 = 2,
    Size4 = 4,
    Size8 = 8,
}

pub fn cpuid(eax: u32, ecx: u32) -> Result<CpuIdInfo, TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Cpuid as u64,
        r12: eax as u64,
        r13: ecx as u64,
        ..Default::default()
    };
    td_vmcall(&mut args)?;
    Ok(CpuIdInfo {
        eax: args.r12 as usize,
        ebx: args.r13 as usize,
        ecx: args.r14 as usize,
        edx: args.r15 as usize,
    })
}

pub fn hlt() {
    let interrupt_blocked = !rflags::read().contains(RFlags::INTERRUPT_FLAG);
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Hlt as u64,
        r12: interrupt_blocked as u64,
        ..Default::default()
    };
    let _ = td_vmcall(&mut args);
}

/// # Safety
/// Make sure the index is valid.
pub unsafe fn rdmsr(index: u32) -> Result<u64, TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Rdmsr as u64,
        r12: index as u64,
        ..Default::default()
    };
    td_vmcall(&mut args)?;
    Ok(args.r11)
}

/// # Safety
/// Make sure the index and the corresponding value are valid.
pub unsafe fn wrmsr(index: u32, value: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Wrmsr as u64,
        r12: index as u64,
        r13: value,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// Used to help perform WBINVD or WBNOINVD operation.
/// - cache_operation: 0: WBINVD, 1: WBNOINVD
pub fn perform_cache_operation(cache_operation: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Wbinvd as u64,
        r12: cache_operation,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// # Safety
/// Make sure the mmio address is valid.
pub unsafe fn read_mmio(size: IoSize, mmio_gpa: u64) -> Result<u64, TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::RequestMmio as u64,
        r12: size as u64,
        r13: 0,
        r14: mmio_gpa,
        ..Default::default()
    };
    td_vmcall(&mut args)?;
    Ok(args.r11)
}

/// # Safety
/// Make sure the mmio address is valid.
pub unsafe fn write_mmio(size: IoSize, mmio_gpa: u64, data: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::RequestMmio as u64,
        r12: size as u64,
        r13: 1,
        r14: mmio_gpa,
        r15: data,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// MapGPA TDG.VP.VMCALL is used to help request the host VMM to map a GPA range as private
/// or shared-memory mappings. This API may also be used to convert page mappings from
/// private to shared. The GPA range passed in this operation can indicate if the mapping is
/// requested for a shared or private memory via the GPA.Shared bit in the start address.
pub fn map_gpa(gpa: u64, size: u64) -> Result<(), (u64, TdVmcallError)> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Mapgpa as u64,
        r12: gpa,
        r13: size,
        ..Default::default()
    };
    td_vmcall(&mut args).map_err(|e| (args.r11, e))
}

/// GetQuote TDG.VP.VMCALL is a doorbell-like interface used to help send a message to the
/// host VMM to queue operations that tend to be long-running operations. GetQuote is
/// designed to invoke a request to generate a TD-Quote signing by a service hosting TD-Quoting
/// Enclave operating in the host environment for a TD Report passed as a parameter by the TD.
/// TDREPORT_STRUCT is a memory operand intended to be sent via the GetQuote
/// TDG.VP.VMCALL to indicate the asynchronous service requested.
pub fn get_quote(shared_gpa: u64, size: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::GetQuote as u64,
        r12: shared_gpa,
        r13: size,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// The guest TD may request that the host VMM specify which interrupt vector to use as an
/// event-notify vector. This is designed as an untrusted operation; thus, the TD OS should be
/// designed not to use the event notification for trusted operations. Example of an operation
/// that can use the event notify is the host VMM signaling a device removal to the TD, in
/// response to which a TD may unload a device driver.
/// The host VMM should use SEAMCALL [TDWRVPS] leaf to inject an interrupt at the requestedinterrupt vector into the TD VCPU that executed TDG.VP.VMCALL
/// <SetupEventNotifyInterrupt> via the posted-interrupt descriptor.
pub fn setup_event_notify_interrupt(interrupt_vector: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::SetupEventNotifyInterrupt as u64,
        r12: interrupt_vector,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// GetTdVmCallInfo TDG.VP.VMCALL is used to help request the host VMM enumerate which
/// TDG.VP.VMCALLs are supported.
pub fn get_tdvmcall_info(interrupt_vector: u64) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::GetTdVmcallInfo as u64,
        // This register is reserved to extend TDG.VP.VMCALL enumeration in future versions.
        r12: 0,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

/// In Service TD scenario, there is a need to define interfaces for the command/response that
/// may have long latency, such as communicating with local device via Secure Protocol and Data
/// Model (SPDM), communicating with remote platform via Transport Layer Security (TLS)
/// Protocol, or communicating with a Quoting Enclave (QE) on attestation or mutual
/// authentication.
///
/// There is also needed that the VMM may notify a service TD to do some actions, such as
/// Migration TD (MigTD).
///
/// We define Command/Response Buffer (CRB) DMA interface.
///
/// Inputs:
/// - shared_gpa_input: Shared 4KB aligned GPA as input – the memory contains a Command.
/// It could be more than one 4K pages.
/// - shared_gpa_output: Shared 4KB aligned GPA as output – the memory contains a Response.
/// It could be more than one 4K pages.
/// - interrupt_vector: Event notification interrupt vector - (valid values 32~255) selected by TD.
/// 0: blocking action. VMM need get response then return.
/// 1~31: Reserved. Should not be used.
/// 32~255: Non-block action. VMM can return immediately and signal the interrupt vector when the response is ready.
/// VMM should inject interrupt vector into the TD VCPU that executed TDG.VP.VMCALL<Service>.
/// - time_out: Timeout– Maximum wait time for the command and response. 0 means infinite wait.
pub fn get_td_service(
    shared_gpa_input: u64,
    shared_gpa_output: u64,
    interrupt_vector: u64,
    time_out: u64,
) -> Result<(), TdVmcallError> {
    let mut args = TdVmcallArgs {
        r11: TdVmcallNum::Service as u64,
        r12: shared_gpa_input,
        r13: shared_gpa_output,
        r14: interrupt_vector,
        r15: time_out,
        ..Default::default()
    };
    td_vmcall(&mut args)
}

macro_rules! io_read {
    ($port:expr, $ty:ty) => {{
        let mut args = TdVmcallArgs {
            r11: TdVmcallNum::Io as u64,
            r12: core::mem::size_of::<$ty>() as u64,
            r13: IO_READ,
            r14: $port as u64,
            ..Default::default()
        };
        td_vmcall(&mut args)?;
        Ok(args.r11 as u32)
    }};
}

pub fn io_read(size: IoSize, port: u16) -> Result<u32, TdVmcallError> {
    match size {
        IoSize::Size1 => io_read!(port, u8),
        IoSize::Size2 => io_read!(port, u16),
        IoSize::Size4 => io_read!(port, u32),
        _ => unreachable!(),
    }
}

macro_rules! io_write {
    ($port:expr, $byte:expr, $size:expr) => {{
        let mut args = TdVmcallArgs {
            r11: TdVmcallNum::Io as u64,
            r12: core::mem::size_of_val(&$byte) as u64,
            r13: IO_WRITE,
            r14: $port as u64,
            r15: $byte as u64,
            ..Default::default()
        };
        td_vmcall(&mut args)
    }};
}

pub fn io_write(size: IoSize, port: u16, byte: u32) -> Result<(), TdVmcallError> {
    match size {
        IoSize::Size1 => io_write!(port, byte as u8, u8),
        IoSize::Size2 => io_write!(port, byte as u16, u16),
        IoSize::Size4 => io_write!(port, byte, u32),
        _ => unreachable!(),
    }
}

fn td_vmcall(args: &mut TdVmcallArgs) -> Result<(), TdVmcallError> {
    let result = unsafe { asm_td_vmcall(args) };
    match result {
        0 => Ok(()),
        _ => Err(result.into()),
    }
}

bitflags! {
    /// LineSts: Line Status
    struct LineSts: u8 {
        const INPUT_FULL = 1;
        const OUTPUT_EMPTY = 1 << 5;
    }
}

fn read_line_sts() -> LineSts {
    LineSts::from_bits_truncate(unsafe { PortRead::read_from_port(SERIAL_LINE_STS) })
}

struct Serial;

impl Serial {
    fn serial_write_byte(byte: u8) {
        match byte {
            // Backspace/Delete
            8 | 0x7F => {
                while !read_line_sts().contains(LineSts::OUTPUT_EMPTY) {}
                io_write!(SERIAL_IO_PORT, 8, u8).unwrap();
                while !read_line_sts().contains(LineSts::OUTPUT_EMPTY) {}
                io_write!(SERIAL_IO_PORT, b' ', u8).unwrap();
                while !read_line_sts().contains(LineSts::OUTPUT_EMPTY) {}
                io_write!(SERIAL_IO_PORT, 8, u8).unwrap();
            }
            _ => {
                while !read_line_sts().contains(LineSts::OUTPUT_EMPTY) {}
                io_write!(SERIAL_IO_PORT, byte, u8).unwrap();
            }
        }
    }
}

impl Write for Serial {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        for &c in s.as_bytes() {
            Serial::serial_write_byte(c);
        }
        Ok(())
    }
}

pub fn print(args: fmt::Arguments) {
    Serial
        .write_fmt(args)
        .expect("Failed to write to serial port");
}

#[macro_export]
macro_rules! serial_print {
    ($fmt: literal $(, $($arg: tt)+)?) => {
        $crate::tdvmcall::print(format_args!($fmt $(, $($arg)+)?));
    }
}

#[macro_export]
macro_rules! serial_println {
    ($fmt: literal $(, $($arg: tt)+)?) => {
        $crate::tdvmcall::print(format_args!(concat!($fmt, "\n") $(, $($arg)+)?))
    }
}