Debian Codegraph @

debian/rust-vendor/procfs/src/kpagecount.rs

raw
1 use std::{
2 io::{BufReader, Read, Seek, SeekFrom},
3 mem::size_of,
4 path::Path,
5 };
6
7 use crate::{process::Pfn, FileWrapper};
8
9 use super::ProcResult;
10
11 /// Parse physical memory references accessing `/proc/kpagecount`
12 ///
13 /// Require root or CAP_SYS_ADMIN
14 pub struct KPageCount {
15 reader: BufReader<FileWrapper>,
16 }
17
18 impl KPageCount {
19 /// Get a parser from default `/proc/kpagecount`
20 ///
21 /// Return `Err` if process is not running as root or don't have CAP_SYS_ADMIN
22 pub fn new() -> ProcResult<Self> {
23 Self::from_custom_root("/proc")
24 }
25
26 /// Get a parser from custom `/proc`
27 ///
28 /// Return `Err` if process is not running as root or don't have CAP_SYS_ADMIN
29 pub fn from_custom_root<P: AsRef<Path>>(root: P) -> ProcResult<Self> {
30 let mut path = root.as_ref().to_path_buf();
31 path.push("kpagecount");
32
33 let reader = BufReader::new(FileWrapper::open(path)?);
34
35 Ok(Self { reader })
36 }
37
38 /// Get the number of references to physical memory at `pfn`
39 ///
40 /// Return Err if pfn is not in RAM. See [crate::iomem()] for a list of valid physical RAM addresses
41 ///
42 /// See [crate::process::Process::pagemap] and [crate::process::MemoryPageFlags::get_page_frame_number]
43 pub fn get_count_at_pfn(&mut self, pfn: Pfn) -> ProcResult<u64> {
44 self.get_count_in_range(pfn, Pfn(pfn.0 + 1))
45 .map(|mut vec| vec.pop().unwrap())
46 }
47
48 /// Get the number of references to physical memory at for PFNs within `start` and `end` PFNs, `end` is excluded
49 ///
50 /// Return Err if any pfn is not in RAM. See [crate::iomem()] for a list of valid physical RAM addresses
51 ///
52 /// See [crate::process::Process::pagemap] and [crate::process::MemoryPageFlags::get_page_frame_number]
53 pub fn get_count_in_range(&mut self, start: Pfn, end: Pfn) -> ProcResult<Vec<u64>> {
54 let mut result = Vec::with_capacity((end.0 - start.0) as usize);
55
56 let start_position = start.0 * size_of::<u64>() as u64;
57 self.reader.seek(SeekFrom::Start(start_position))?;
58
59 for _pfn in start.0..end.0 {
60 // Each entry is a 64 bits counter
61 let mut buf = [0; size_of::<u64>()];
62
63 self.reader.read_exact(&mut buf)?;
64 let page_references: u64 = u64::from_le_bytes(buf);
65
66 result.push(page_references);
67 }
68
69 Ok(result)
70 }
71 }