|
| 1 | +use log::{info, warn}; |
| 2 | +use nix::mount::{mount, MsFlags}; |
| 3 | +use std::io; |
| 4 | +use tokio::fs; |
| 5 | + |
| 6 | +const HUGEPAGE_FS_TYPE: &[u8] = b"hugetlbfs"; |
| 7 | +const HUGEPAGE_MOUNT_POINT: &str = "/dev/hugepages"; |
| 8 | + |
| 9 | +pub async fn configure_hugepages(num_pages: u32) -> io::Result<()> { |
| 10 | + let nr_hugepages_path = "/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages"; |
| 11 | + |
| 12 | + info!("Attempting to allocate {num_pages} hugepages..."); |
| 13 | + fs::write(nr_hugepages_path, num_pages.to_string()).await?; |
| 14 | + info!("Successfully wrote to {nr_hugepages_path}"); |
| 15 | + |
| 16 | + let allocated_pages_str = fs::read_to_string(nr_hugepages_path).await?; |
| 17 | + let allocated_pages = allocated_pages_str.trim().parse::<u32>().unwrap_or(0); |
| 18 | + |
| 19 | + if allocated_pages < num_pages { |
| 20 | + warn!( |
| 21 | + "System only allocated {allocated_pages} of the requested {num_pages} hugepages. This might happen due to memory fragmentation." |
| 22 | + ); |
| 23 | + } else { |
| 24 | + info!("System successfully allocated {allocated_pages} hugepages."); |
| 25 | + } |
| 26 | + |
| 27 | + if !is_mounted(HUGEPAGE_MOUNT_POINT).await { |
| 28 | + info!("Mounting hugetlbfs at {HUGEPAGE_MOUNT_POINT}..."); |
| 29 | + fs::create_dir_all(HUGEPAGE_MOUNT_POINT).await?; |
| 30 | + mount_hugetlbfs()?; |
| 31 | + info!("Successfully mounted hugetlbfs."); |
| 32 | + } else { |
| 33 | + info!("hugetlbfs is already mounted at {HUGEPAGE_MOUNT_POINT}."); |
| 34 | + } |
| 35 | + |
| 36 | + Ok(()) |
| 37 | +} |
| 38 | + |
| 39 | +fn mount_hugetlbfs() -> Result<(), io::Error> { |
| 40 | + const NONE: Option<&'static [u8]> = None; |
| 41 | + mount( |
| 42 | + Some(b"none".as_ref()), |
| 43 | + HUGEPAGE_MOUNT_POINT, |
| 44 | + Some(HUGEPAGE_FS_TYPE), |
| 45 | + MsFlags::empty(), |
| 46 | + NONE, |
| 47 | + ) |
| 48 | + .map_err(|e| io::Error::other(format!("Failed to mount hugetlbfs: {e}"))) |
| 49 | +} |
| 50 | + |
| 51 | +async fn is_mounted(path: &str) -> bool { |
| 52 | + let Ok(mounts) = fs::read_to_string("/proc/mounts").await else { |
| 53 | + return false; |
| 54 | + }; |
| 55 | + mounts.lines().any(|line| { |
| 56 | + let parts: Vec<&str> = line.split_whitespace().collect(); |
| 57 | + parts.get(1) == Some(&path) |
| 58 | + }) |
| 59 | +} |
0 commit comments