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
//! Device node (`/dev/dri/card*`)
use std::cmp::Ordering;
use std::fs::File;
use std::io::Write;
use std::os::raw::c_uint;
use std::{fs, io};

use lazy_static::lazy_static;
use regex::Regex;
use thiserror::Error;
use tracing::instrument;

use crate::prelude::*;
use crate::{ensure_logs_setup, ffi};

const DEVICE_CARDS_DIR: &str = "/dev/dri";
const REMOVE_ALL_FILE: &str = "/sys/devices/evdi/remove_all";

/// Represents a device node (`/dev/dri/card*`).
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct DeviceNode {
    pub(crate) id: i32,
}

impl DeviceNode {
    // NOTE: This contains the main entrypoints.
    // We must ensure we setup logs before we call any ffi.

    /// Returns an evdi device node if one is available.
    ///
    /// If no device is available you will need to run Device::add() with superuser permissions.
    pub fn get() -> Option<Self> {
        if let Ok(mut devices) = Self::list_available() {
            devices.pop()
        } else {
            None
        }
    }

    /// Check if a device node is an evdi device node, is a different device node, or doesn't exist.
    pub fn status(&self) -> DeviceNodeStatus {
        ensure_logs_setup();
        let sys = unsafe { ffi::evdi_check_device(self.id) };
        DeviceNodeStatus::from(sys)
    }

    /// Open an evdi device node.
    ///
    /// Returns None if we fail to open the device, which may be because the device isn't an evdi
    /// device node.
    pub fn open(&self) -> Result<UnconnectedHandle, OpenDeviceError> {
        ensure_logs_setup();

        // Provide helpful info if the call would have failed with Unknown
        match check_kernel_mod() {
            KernelModStatus::NotInstalled => return Err(OpenDeviceError::KernelModuleNotInstalled),
            KernelModStatus::Outdated => return Err(OpenDeviceError::KernelModuleOutdated),
            KernelModStatus::Compatible => (),
        }

        // NOTE: Opening invalid devices can be very slow (~10sec on my laptop), so we check first
        match self.status() {
            DeviceNodeStatus::Unrecognized => Err(OpenDeviceError::NotEvdiDevice),
            DeviceNodeStatus::NotPresent => Err(OpenDeviceError::NonexistentDevice),
            DeviceNodeStatus::Available => {
                let sys = unsafe { ffi::evdi_open(self.id) };
                if !sys.is_null() {
                    info!("Opened device {}", self.id);
                    Ok(UnconnectedHandle::new(self.clone(), sys))
                } else {
                    Err(OpenDeviceError::Unknown)
                }
            }
        }
    }

    /// List all evdi device nodes that have available status in a stable order
    #[instrument]
    pub fn list_available() -> io::Result<Vec<Self>> {
        lazy_static! {
            static ref RE: Regex = Regex::new(r"^card([0-9]+)$").unwrap();
        }

        let mut devices: Vec<DeviceNode> = vec![];

        for entry in fs::read_dir(DEVICE_CARDS_DIR)? {
            let name_os = entry?.file_name();
            let name = name_os.to_string_lossy();
            let id = RE
                .captures(&name)
                .and_then(|caps| caps.get(1))
                .and_then(|id| id.as_str().parse::<i32>().ok());

            if let Some(id) = id {
                devices.push(DeviceNode::new(id))
            }
        }

        let mut available: Vec<DeviceNode> = devices
            .into_iter()
            .filter(|device| device.status() == DeviceNodeStatus::Available)
            .collect();

        available.sort();

        Ok(available)
    }

    /// Tell the kernel module to create a new evdi device node.
    ///
    /// **Requires superuser permissions.**
    #[instrument]
    pub fn add() -> bool {
        ensure_logs_setup();
        let status = unsafe { ffi::evdi_add_device() };
        status > 0
    }

    /// Remove all evdi device nodes.
    ///
    /// **Requires superuser permissions.**
    #[instrument]
    pub fn remove_all() -> io::Result<()> {
        let mut f = File::with_options().write(true).open(REMOVE_ALL_FILE)?;
        f.write_all("1".as_ref())?;
        f.flush()?;
        Ok(())
    }

    /// Create a struct representing /dev/dri/card{id}.
    ///
    /// This does not create the device or check if the device exists.
    pub fn new(id: i32) -> Self {
        DeviceNode { id }
    }
}

impl Ord for DeviceNode {
    fn cmp(&self, other: &Self) -> Ordering {
        self.id.cmp(&other.id)
    }
}

impl PartialOrd for DeviceNode {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// Status of a [`DeviceNode`]
#[derive(Debug, PartialEq)]
#[cfg_attr(
    feature = "serde",
    derive(serde_crate::Serialize, serde_crate::Deserialize),
    serde(crate = "serde_crate")
)]
pub enum DeviceNodeStatus {
    Available,
    Unrecognized,
    NotPresent,
}

#[derive(Debug, Error)]
pub enum OpenDeviceError {
    #[error("The kernel module evdi is not installed")]
    KernelModuleNotInstalled,
    #[error("The kernel module is too outdated to use with this library version")]
    KernelModuleOutdated,
    #[error("The device node does not exist")]
    NonexistentDevice,
    #[error("The device node is not an evdi device node")]
    NotEvdiDevice,
    #[error("The call to the c library failed. Maybe the device node is an incompatible version?")]
    Unknown,
}

impl DeviceNodeStatus {
    /// * `sys` - evdi_device_status
    ///
    /// Panics on unrecognized sys.
    fn from(sys: c_uint) -> Self {
        match sys {
            ffi::EVDI_STATUS_AVAILABLE => DeviceNodeStatus::Available,
            ffi::EVDI_STATUS_UNRECOGNIZED => DeviceNodeStatus::Unrecognized,
            ffi::EVDI_STATUS_NOT_PRESENT => DeviceNodeStatus::NotPresent,
            _ => panic!("Invalid device status {}", sys),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_common::*;

    #[ltest]
    fn default_device_is_not_evdi() {
        let status = DeviceNode::new(0).status();
        assert_eq!(status, DeviceNodeStatus::Unrecognized);
    }

    #[ltest]
    fn nonexistent_device_has_proper_status() {
        let status = DeviceNode::new(4200).status();
        assert_eq!(status, DeviceNodeStatus::NotPresent);
    }

    #[ltest]
    fn add_fails_without_superuser() {
        let result = DeviceNode::add();
        assert_eq!(result, false);
    }

    #[ltest]
    fn remove_all_fails_without_superuser() {
        let result = DeviceNode::remove_all();
        assert!(result.is_err())
    }

    #[ltest]
    fn list_available_contains_at_least_one_device() {
        let results = DeviceNode::list_available().unwrap();
        assert!(!results.is_empty(), "No available devices. Have you added at least one device by running the binary add_device at least once?");
    }

    #[ltest]
    fn get_returns_a_device() {
        let result = DeviceNode::get();
        assert!(result.is_some());
    }

    #[ltest]
    fn can_open() {
        let device = DeviceNode::get().unwrap();
        device.open().unwrap();
    }

    #[ltest]
    fn opening_nonexistent_device_fails() {
        let device = DeviceNode::new(4200);
        match device.open() {
            Err(OpenDeviceError::NonexistentDevice) => (),
            _ => panic!(),
        }
    }

    #[ltest]
    fn opening_non_evdi_device_fails() {
        let device = DeviceNode::new(0);
        match device.open() {
            Err(OpenDeviceError::NotEvdiDevice) => (),
            _ => panic!(),
        }
    }
}