disk.rs 4.52 KB
Newer Older
1
2
3
4
5
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use super::*;

6
use core::ffi::c_char;
7
use nix::fcntl::{FallocateFlags, fallocate};
Ryan Olson's avatar
Ryan Olson committed
8
9
use nix::unistd::unlink;
use std::ffi::CStr;
10
use std::ffi::CString;
Ryan Olson's avatar
Ryan Olson committed
11
12
13
14
use std::path::Path;

const DISK_CACHE_KEY: &str = "DYN_KVBM_DISK_CACHE_DIR";
const DEFAULT_DISK_CACHE_DIR: &str = "/tmp/";
15
16
17

#[derive(Debug)]
pub struct DiskStorage {
Ryan Olson's avatar
Ryan Olson committed
18
    fd: u64,
19
20
21
    file_name: String,
    size: usize,
    handles: RegistrationHandles,
Ryan Olson's avatar
Ryan Olson committed
22
    unlinked: bool,
23
24
25
26
27
28
29
30
31
32
}

impl Local for DiskStorage {}
impl SystemAccessible for DiskStorage {}

impl DiskStorage {
    pub fn new(size: usize) -> Result<Self, StorageError> {
        // We need to open our file with some special flags that aren't supported by the tempfile crate.
        // Instead, we'll use the mkostemp function to create a temporary file with the correct flags.

Ryan Olson's avatar
Ryan Olson committed
33
34
35
36
37
38
39
40
41
42
43
        let specified_dir =
            std::env::var(DISK_CACHE_KEY).unwrap_or_else(|_| DEFAULT_DISK_CACHE_DIR.to_string());
        let file_path = Path::new(&specified_dir).join("dynamo-kvbm-disk-cache-XXXXXX");

        if !file_path.exists() {
            std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
        }

        tracing::debug!("Allocating disk cache file at {}", file_path.display());

        let template = CString::new(file_path.to_str().unwrap()).unwrap();
44
45
46
47
        let mut template_bytes = template.into_bytes_with_nul();

        let raw_fd = unsafe {
            nix::libc::mkostemp(
48
                template_bytes.as_mut_ptr() as *mut c_char,
49
50
51
52
53
54
55
                // For maximum performance, GPU DirectStorage requires O_DIRECT.
                // This allows transfers to bypass the kernel page cache.
                // It also introduces the restriction that all accesses must be page-aligned.
                nix::libc::O_RDWR | nix::libc::O_DIRECT,
            )
        };

Ryan Olson's avatar
Ryan Olson committed
56
57
58
59
60
61
        let file_name = CStr::from_bytes_with_nul(template_bytes.as_slice())
            .unwrap()
            .to_str()
            .map_err(|e| {
                StorageError::AllocationFailed(format!("Failed to read temp file name: {}", e))
            })?
62
63
64
            .to_string();

        // We need to use fallocate to actually allocate the storage and create the blocks on disk.
Ryan Olson's avatar
Ryan Olson committed
65
66
        fallocate(raw_fd, FallocateFlags::empty(), 0, size as i64).map_err(|e| {
            StorageError::AllocationFailed(format!("Failed to allocate temp file: {}", e))
67
68
69
        })?;

        Ok(Self {
Ryan Olson's avatar
Ryan Olson committed
70
            fd: raw_fd as u64,
71
72
73
            file_name,
            size,
            handles: RegistrationHandles::new(),
Ryan Olson's avatar
Ryan Olson committed
74
            unlinked: false,
75
76
77
78
        })
    }

    pub fn fd(&self) -> u64 {
Ryan Olson's avatar
Ryan Olson committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
        self.fd
    }

    /// Unlink our temp file.
    /// This means that when this process terminates, the file will be automatically deleted by the OS.
    /// Unfortunately, GDS requires that files we try to register must be linked.
    /// To get around this, we unlink the file only after we've registered it with NIXL.
    pub fn unlink(&mut self) -> Result<(), StorageError> {
        if self.unlinked {
            return Ok(());
        }

        self.unlinked = true;

        unlink(self.file_name.as_str()).map_err(|e| {
            StorageError::AllocationFailed(format!("Failed to unlink temp file: {}", e))
        })
    }

    pub fn unlinked(&self) -> bool {
        self.unlinked
100
101
102
103
104
    }
}

impl Drop for DiskStorage {
    fn drop(&mut self) {
105
        self.handles.release();
Ryan Olson's avatar
Ryan Olson committed
106
        let _ = self.unlink();
107
108
109
110
111
    }
}

impl Storage for DiskStorage {
    fn storage_type(&self) -> StorageType {
Ryan Olson's avatar
Ryan Olson committed
112
        StorageType::Disk(self.fd())
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
    }

    fn addr(&self) -> u64 {
        0
    }

    fn size(&self) -> usize {
        self.size
    }

    unsafe fn as_ptr(&self) -> *const u8 {
        std::ptr::null()
    }

    unsafe fn as_mut_ptr(&mut self) -> *mut u8 {
        std::ptr::null_mut()
    }
}

impl RegisterableStorage for DiskStorage {
    fn register(
        &mut self,
        key: &str,
        handle: Box<dyn RegistationHandle>,
    ) -> Result<(), StorageError> {
        self.handles.register(key, handle)
    }

    fn is_registered(&self, key: &str) -> bool {
        self.handles.is_registered(key)
    }

    fn registration_handle(&self, key: &str) -> Option<&dyn RegistationHandle> {
        self.handles.registration_handle(key)
    }
}

#[derive(Default)]
pub struct DiskAllocator;

impl StorageAllocator<DiskStorage> for DiskAllocator {
    fn allocate(&self, size: usize) -> Result<DiskStorage, StorageError> {
        DiskStorage::new(size)
    }
}