From 46e34cf5dd0a16dd5344b3085607e62d645b9398 Mon Sep 17 00:00:00 2001 From: Larry Dewey Date: Thu, 25 May 2023 10:40:51 -0500 Subject: [PATCH] msr: Adding check for kernel module Previously, if the kernel module was not present, this was silently returning an empty file-handle. When the MSR kernel module is not present, we want to make sure a specific error is returned letting the user know that it is not present. For now, we are checking this by looking if the device-file is present. Signed-off-by: Larry Dewey --- Cargo.toml | 2 +- README.md | 6 ++++-- src/lib.rs | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index d5abe4a..16db606 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "msru" -version = "0.1.0" +version = "0.2.0" authors = [ "Larry Dewey "] edition = "2021" rust-version = "1.59" diff --git a/README.md b/README.md index dbb0922..a9619e9 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Add the following line to your `Cargo.toml` file: ```toml [dependencies] -msru = "0.1.0" +msru = "0.2.0" ``` ## Usage @@ -19,7 +19,9 @@ msru = "0.1.0" use msru::Msr; // X86_64 SYSCFG MSR -let msr: Msr = Msr::new(0xC0010010, 0); +let msr: Msr = Msr::new(0xC0010010, 0)?; + +let raw_value: u64 = msr.read()?; // ... ``` \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 5c0dcd1..7699d0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -7,11 +7,40 @@ //! Currently this crate only supports Linux. use std::{ + convert::From, fs::{File, OpenOptions}, - io::{Read, Result, Seek, SeekFrom}, + io::{Read, Seek, SeekFrom}, os::unix::fs::FileExt, + path::Path, }; +#[derive(Debug)] +pub enum MsrError { + IoError(std::io::Error), + MissingKernelModule, + UnknownError, +} + +impl std::error::Error for MsrError {} + +impl std::fmt::Display for MsrError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + MsrError::IoError(io_error) => write!(f, "IoError Encountered: {io_error}"), + MsrError::MissingKernelModule => write!(f, "MSR Kernel Module not loaded!"), + MsrError::UnknownError => write!(f, "An unknown error was encountered!"), + } + } +} + +impl From for MsrError { + fn from(value: std::io::Error) -> Self { + Self::IoError(value) + } +} + +type Result = std::result::Result; + /// A Rust-friendly MSR structure. pub struct Msr { /// A model specific register address we would like to read. @@ -24,6 +53,9 @@ impl Msr { /// Construct an Msr for a specified register and CPU. pub fn new(reg: u32, cpu: u16) -> Result { let cpu_msr_path: String = format!("/dev/cpu/{cpu}/msr"); + if !Path::new(&cpu_msr_path).exists() { + return Err(MsrError::MissingKernelModule); + } Ok(Self { reg, fh: OpenOptions::new()