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
//! APIs for interacting with Compute Express Link (CXL) devices.

pub mod lsa;
pub mod query;
pub mod send;

use serde::{Deserialize, Serialize};
use std::{fs, io, path::Path, path::PathBuf};

/// Magic IOCTL number from the kernel.
pub const CXL_IOC_MAGIC: u8 = 0xce;

/// A CXL memory device.
#[derive(Debug, Serialize, Deserialize)]
pub struct Memdev {
    #[serde(skip_serializing)]
    sysfs_path: PathBuf,
    #[serde(skip_serializing)]
    chardev_path: PathBuf,

    name: String,
    fw_vers: String,
    payload_max: u64,
    pmem: u64,
    ram: u64,
}

impl Memdev {
    /// Returns a memory device for the given path
    pub fn new(path: &str) -> Option<Self> {
        let p = Path::new(path);
        if p.is_dir() {
            let name = &p
                .file_name()
                .map(|name| name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "".into());
            let sysfs_path = &PathBuf::from(path);
            Some(Memdev {
                sysfs_path: sysfs_path.to_path_buf(),
                name: name.to_string(),
                chardev_path: PathBuf::from("/dev/cxl/").join(name),
                fw_vers: get_sysfs_node(path, "firmware_version").ok()?,
                payload_max: get_sysfs_node_u64(path, "payload_max").ok()?,
                pmem: get_sysfs_node_hex(path, "pmem/size").ok()?,
                ram: get_sysfs_node_hex(path, "ram/size").ok()?,
            })
        } else {
            None
        }
    }

    /// Get the name of the memory device (ie. mem1)
    pub fn get_name(&self) -> &str {
        &self.name
    }
}

/// Returns the contents of a sysfs node
///
/// # Arguments
///
///  * `path` - Top level directory of a CXL sysfs node.
///  * `node` - Specific node without the directory @path.
///
/// # Examples
///
/// ```no_run
/// let cxl_dev = "/sys/devices/pci0000:34/0000:34:00.0/0000:35:00.0/mem0";
/// let fw_version: String = cxl_rs::get_sysfs_node(cxl_dev, "firmware_version").unwrap();
/// ```
pub fn get_sysfs_node(path: &str, node: &str) -> Result<String, std::io::Error> {
    let f = Path::new(path).join(node);
    Ok(fs::read_to_string(f)?.trim_end().to_string())
}

/// Returns the parsed hex value from a sysfs node.
///
/// # Arguments
///
///  * `path` - Top level directory of a CXL sysfs node.
///  * `node` - Specific node without the directory @path.
///
/// # Examples
///
/// ```no_run
/// # use std::io;
/// let cxl_dev = "/sys/devices/pci0000:34/0000:34:00.0/0000:35:00.0/mem0";
/// let pmem_size: u64 = cxl_rs::get_sysfs_node_hex(cxl_dev, "pmem/size")?;
/// # Ok::<(), io::Error>(())
/// ```
pub fn get_sysfs_node_hex(path: &str, node: &str) -> Result<u64, std::io::Error> {
    Ok(u64::from_str_radix(&get_sysfs_node(path, node)?[2..], 16).expect("Couldn't parse"))
}

/// Returns a u64 value from a sysfs node.
///
/// # Arguments
///
///  * `path` - Top level directory of a CXL sysfs node.
///  * `node` - Specific node without the directory @path.
///
/// # Examples
///
/// ```no_run
/// # use std::io;
/// let cxl_dev = "/sys/devices/pci0000:34/0000:34:00.0/0000:35:00.0/mem0";
/// let payload_size = cxl_rs::get_sysfs_node_u64(cxl_dev, "payload_size")?;
/// # Ok::<(), io::Error>(())
/// ```
pub fn get_sysfs_node_u64(path: &str, node: &str) -> Result<u64, std::io::Error> {
    Ok(get_sysfs_node(path, node)?.parse().expect("Couldn't parse"))
}

/// Returns CXL memory devices found in sysfs.
///
/// # Arguments
///
/// * `path` - Optional path to start the search
///
/// # Examples
///
/// ```no_run
/// let files = cxl_rs::get_sysfs_devices(None);
/// for devs in files {
///     // do something like create a memdev
/// }
/// ```
pub fn get_sysfs_devices(path: Option<&Path>) -> io::Result<Vec<(String, PathBuf)>> {
    let sysfs_dir = path.unwrap_or_else(|| Path::new("/sys/bus/cxl/devices/"));
    let mut result = Vec::<(String, PathBuf)>::new();

    let files = fs::read_dir(sysfs_dir).unwrap();
    files
        .filter_map(Result::ok)
        .filter_map(|d| {
            d.path().file_name().and_then(|f| {
                if f.to_string_lossy().starts_with("mem") {
                    Some(d)
                } else {
                    None
                }
            })
        })
        .for_each(|f| {
            result.push((
                f.file_name().to_str().unwrap().to_string(),
                f.path().canonicalize().unwrap(),
            ))
        });

    Ok(result)
}

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

    #[test]
    fn no_devices() {
        assert_eq!(0, get_sysfs_devices(Some(Path::new("/tmp"))).unwrap().len());
    }
}