Skip to content

Commit

Permalink
msr: Adding check for kernel module
Browse files Browse the repository at this point in the history
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 <larry.dewey@amd.com>
  • Loading branch information
larrydewey authored and tylerfanelli committed May 25, 2023
1 parent ab1a059 commit 46e34cf
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "msru"
version = "0.1.0"
version = "0.2.0"
authors = [ "Larry Dewey <larry.dewey@amd.com>"]
edition = "2021"
rust-version = "1.59"
Expand Down
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Add the following line to your `Cargo.toml` file:

```toml
[dependencies]
msru = "0.1.0"
msru = "0.2.0"
```

## Usage
Expand All @@ -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()?;

// ...
```
34 changes: 33 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::io::Error> for MsrError {
fn from(value: std::io::Error) -> Self {
Self::IoError(value)
}
}

type Result<T> = std::result::Result<T, MsrError>;

/// A Rust-friendly MSR structure.
pub struct Msr {
/// A model specific register address we would like to read.
Expand All @@ -24,6 +53,9 @@ impl Msr {
/// Construct an Msr for a specified register and CPU.
pub fn new(reg: u32, cpu: u16) -> Result<Self> {
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()
Expand Down

0 comments on commit 46e34cf

Please sign in to comment.