tdx_guest_device/
ioctl.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! The module implements the Linux TDX Guest APIs based on ioctl.
5
6#![cfg(feature = "std")]
7// UNSAFETY: unsafe needed to make ioctl calls.
8#![expect(unsafe_code)]
9
10use crate::protocol;
11use std::fs::File;
12use std::os::fd::AsRawFd;
13use thiserror::Error;
14use zerocopy::FromZeros;
15
16#[expect(missing_docs)] // self-explanatory fields
17#[derive(Debug, Error)]
18pub enum Error {
19    #[error("failed to open /dev/tdx_guest")]
20    OpenDevTdxGuest(#[source] std::io::Error),
21    #[error("TDX_CMD_GET_REPORT0 ioctl failed")]
22    TdxGetReportIoctl(#[source] nix::Error),
23}
24
25nix::ioctl_readwrite!(
26    /// `TDX_CMD_GET_REPORT0` ioctl defined by Linux.
27    tdx_get_report0,
28    protocol::TDX_CMD_GET_REPORT0_IOC_TYPE,
29    0x1,
30    protocol::TdxReportReq
31);
32
33/// Abstraction of the /dev/tdx_guest device.
34pub struct TdxGuestDevice {
35    file: File,
36}
37
38impl TdxGuestDevice {
39    /// Open an /dev/tdx_guest device
40    pub fn open() -> Result<Self, Error> {
41        let tdx_guest = std::fs::OpenOptions::new()
42            .read(true)
43            .write(true)
44            .open("/dev/tdx_guest")
45            .map_err(Error::OpenDevTdxGuest)?;
46
47        Ok(Self { file: tdx_guest })
48    }
49
50    /// Invoke the `TDX_CMD_GET_REPORT0` ioctl via the device.
51    pub fn get_report(
52        &self,
53        report_data: [u8; 64],
54        _vmpl: u32,
55    ) -> Result<protocol::TdReport, Error> {
56        let mut tdx_report_request = protocol::TdxReportReq {
57            report_data,
58            td_report: protocol::TdReport::new_zeroed(),
59        };
60
61        // SAFETY: Make TDX_CMD_GET_REPORT0 ioctl call to the device with correct types.
62        unsafe {
63            tdx_get_report0(self.file.as_raw_fd(), &mut tdx_report_request)
64                .map_err(Error::TdxGetReportIoctl)?;
65        }
66
67        Ok(tdx_report_request.td_report)
68    }
69}