lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! # Thin Provisioning
//!
//! Thin provisioning for LCPFS with overcommit support and space monitoring.
//!
//! ## Overview
//!
//! Thin provisioning allows creating virtual volumes larger than the available
//! physical storage. Blocks are allocated on-demand when data is written,
//! enabling storage overcommitment while maintaining efficiency.
//!
//! ## Features
//!
//! - **On-Demand Allocation**: Blocks allocated only when written
//! - **Copy-on-Write Snapshots**: Instant, space-efficient snapshots
//! - **Overcommit Tracking**: Monitor virtual vs physical usage
//! - **Threshold Alerts**: Warning, critical, and emergency levels
//! - **Hole Punching**: Reclaim space by deallocating blocks
//! - **Extent-Based Allocation**: Efficient free space management
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────┐
//! │                      Thin Pool                               │
//! ├─────────────────────────────────────────────────────────────┤
//! │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐    │
//! │  │ Volume 1 │  │ Volume 2 │  │ Snapshot │  │ Volume N │    │
//! │  │ (100GB)  │  │ (50GB)   │  │  (COW)   │  │  (...)   │    │
//! │  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘    │
//! │       │             │             │             │           │
//! │  ┌────┴─────────────┴─────────────┴─────────────┴────────┐  │
//! │  │              Virtual Block Mappings                    │  │
//! │  │         (Virtual Block → Physical Block)               │  │
//! │  └────────────────────────┬──────────────────────────────┘  │
//! │                           │                                  │
//! │  ┌────────────────────────┴──────────────────────────────┐  │
//! │  │                  Block Allocator                       │  │
//! │  │              (Extent Tree / Bitmap)                    │  │
//! │  └────────────────────────┬──────────────────────────────┘  │
//! │                           │                                  │
//! │  ┌────────────────────────┴──────────────────────────────┐  │
//! │  │                Physical Storage (10GB)                 │  │
//! │  └───────────────────────────────────────────────────────┘  │
//! └─────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Usage
//!
//! ### Creating a Thin Pool
//!
//! ```rust,ignore
//! use lcpfs::thin::{PoolConfig, ThinPool, create_pool};
//!
//! // Create a pool with 100GB capacity
//! let config = PoolConfig::new("data-pool", 100 * 1024 * 1024 * 1024);
//! let pool_id = create_pool(config)?;
//! ```
//!
//! ### Creating Thin Volumes
//!
//! ```rust,ignore
//! use lcpfs::thin::{VolumeConfig, with_pool};
//!
//! with_pool(pool_id, |pool| {
//!     // Create a 1TB virtual volume on a 100GB pool
//!     let config = VolumeConfig::new("big-volume", 1024 * 1024 * 1024 * 1024);
//!     pool.create_volume(config)
//! })?;
//! ```
//!
//! ### Monitoring Overcommit
//!
//! ```rust,ignore
//! use lcpfs::thin::with_pool;
//!
//! with_pool(pool_id, |pool| {
//!     let summary = pool.capacity_summary();
//!     println!("Physical: {} / {}", summary.used_physical, summary.total_physical);
//!     println!("Virtual: {}", summary.total_virtual);
//!     println!("Overcommit: {:.1}x", summary.overcommit_ratio);
//!     println!("Level: {}", summary.threshold_level);
//! })?;
//! ```
//!
//! ### Creating Snapshots
//!
//! ```rust,ignore
//! with_pool(pool_id, |pool| {
//!     let snap_id = pool.create_snapshot(volume_id, "snapshot-2024".into())?;
//!     // Snapshot is instant and space-efficient (COW)
//! })?;
//! ```
//!
//! ### Setting Up Alerts
//!
//! ```rust,ignore
//! use lcpfs::thin::{Alert, with_pool};
//!
//! fn handle_alert(alert: &Alert) {
//!     eprintln!("ALERT: {} - {}", alert.level, alert.message);
//! }
//!
//! with_pool(pool_id, |pool| {
//!     pool.set_alert_callback(handle_alert);
//! })?;
//! ```
//!
//! ## Threshold Configuration
//!
//! | Level | Default | Behavior |
//! |-------|---------|----------|
//! | Warning | 80% | Log warning |
//! | Critical | 90% | Throttle writes |
//! | Emergency | 95% | Block new writes |
//!
//! ## Block Allocation Policies
//!
//! | Policy | Description |
//! |--------|-------------|
//! | FirstFit | Use first available extent |
//! | BestFit | Use smallest suitable extent |
//! | NextFit | Continue from last allocation |
//! | Contiguous | Try to allocate contiguous blocks |
//!
//! ## Overcommit Policies
//!
//! | Policy | Description |
//! |--------|-------------|
//! | StopAtWarning | Block writes at warning level |
//! | StopAtCritical | Block writes at critical level |
//! | StopAtEmergency | Block writes at emergency level |
//! | AllowFull | Allow writes until completely full |

mod alloc;
mod pool;
mod types;
mod volume;

// Re-export types
pub use types::{
    Alert, AlertType, AllocationPolicy, BlockMapping, BlockState, DEFAULT_BLOCK_SIZE,
    DEFAULT_CRITICAL_THRESHOLD, DEFAULT_EMERGENCY_THRESHOLD, DEFAULT_WARN_THRESHOLD,
    MAX_BLOCK_SIZE, MIN_BLOCK_SIZE, MappingFlags, OvercommitPolicy, PhysicalBlock, PoolConfig,
    PoolStats, ThinError, ThinResult, ThresholdLevel, Thresholds, VirtualBlock, VolumeConfig,
    VolumeStats,
};

// Re-export allocator types
pub use alloc::{BlockAllocator, Extent, ExtentTree, FreeBitmap};

// Re-export volume types
pub use volume::{IoContext, ThinVolume};

// Re-export pool types and functions
pub use pool::{
    AlertCallback, CapacitySummary, ThinPool, clear_pools, create_pool, delete_pool, get_pool_id,
    get_pool_name, list_pools, pool_count, pool_exists, pool_exists_by_name, with_pool,
};

// ═══════════════════════════════════════════════════════════════════════════════
// CONVENIENCE FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/// Create a quick thin pool with default settings.
pub fn quick_pool(name: &str, capacity_gb: u64) -> ThinResult<u64> {
    let config = PoolConfig::new(name, capacity_gb * 1024 * 1024 * 1024);
    create_pool(config)
}

/// Create a volume in a pool with default settings.
pub fn quick_volume(pool_id: u64, name: &str, size_gb: u64) -> ThinResult<u64> {
    with_pool(pool_id, |pool| {
        let config = VolumeConfig::new(name, size_gb * 1024 * 1024 * 1024);
        pool.create_volume(config)
    })?
}

/// Get pool usage as a percentage.
pub fn pool_usage(pool_id: u64) -> ThinResult<u8> {
    with_pool(pool_id, |pool| pool.usage_percent())
}

/// Get pool overcommit ratio.
pub fn pool_overcommit(pool_id: u64) -> ThinResult<f64> {
    with_pool(pool_id, |pool| pool.overcommit_ratio())
}

// ═══════════════════════════════════════════════════════════════════════════════
// MODULE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;

    fn setup() {
        clear_pools();
    }

    #[test]
    fn test_quick_pool() {
        setup();

        let pool_id = quick_pool("test-pool", 100).unwrap();
        assert!(pool_exists(pool_id));
    }

    #[test]
    fn test_quick_volume() {
        // Note: Tests run in parallel with shared global state.
        // Use unique pool name to avoid interference.
        let pool_name = "vol-test-unique-112233";
        let pool_id = quick_pool(pool_name, 100).unwrap();
        let vol_id = quick_volume(pool_id, "vol1", 50).unwrap();

        with_pool(pool_id, |pool| {
            assert!(pool.get_volume(vol_id).is_some());
        })
        .unwrap();
    }

    #[test]
    fn test_pool_usage() {
        setup();

        let pool_id = quick_pool("usage-test", 10).unwrap();
        let usage = pool_usage(pool_id).unwrap();

        // Should be low initially (just metadata reservation)
        assert!(usage < 10);
    }

    #[test]
    fn test_pool_overcommit() {
        // Note: Tests run in parallel with shared global state.
        // Don't clear pools - just use a unique pool name and check relative values.
        let pool_name = "overcommit-test-unique-54321";
        let pool_id = quick_pool(pool_name, 10).unwrap();

        // Create volumes totaling 100GB on 10GB pool
        // Use with_pool to keep all operations within one lock acquisition
        let ratio = with_pool(pool_id, |pool| {
            for i in 0..10 {
                let vol_name = ::alloc::format!("vol{}", i);
                let config = VolumeConfig::new(&vol_name, 10 * 1024 * 1024 * 1024);
                pool.create_volume(config).unwrap();
            }
            pool.overcommit_ratio()
        })
        .unwrap();

        assert!(ratio > 9.0, "Expected >9x overcommit, got {}", ratio);
    }

    #[test]
    fn test_exports_accessible() {
        // Verify all public types are accessible
        let _ = BlockState::Unallocated;
        let _ = ThresholdLevel::Normal;
        let _ = AlertType::PoolFull;
        let _ = AllocationPolicy::FirstFit;
        let _ = OvercommitPolicy::StopAtCritical;
    }

    #[test]
    fn test_virtual_block_operations() {
        let vb = VirtualBlock::new(100);
        assert_eq!(vb.block(), 100);

        let pb = PhysicalBlock::new(5000);
        assert_eq!(pb.block(), 5000);
    }

    #[test]
    fn test_threshold_defaults() {
        let t = Thresholds::default();
        assert_eq!(t.warning, DEFAULT_WARN_THRESHOLD);
        assert_eq!(t.critical, DEFAULT_CRITICAL_THRESHOLD);
        assert_eq!(t.emergency, DEFAULT_EMERGENCY_THRESHOLD);
    }

    #[test]
    fn test_volume_config_builder() {
        let config = VolumeConfig::new("test", 1024 * 1024 * 1024)
            .with_block_size(256 * 1024)
            .with_compression()
            .with_reservation(100 * 1024 * 1024);

        assert_eq!(config.block_size, 256 * 1024);
        assert!(config.compression);
        assert_eq!(config.reservation, 100 * 1024 * 1024);
    }

    #[test]
    fn test_pool_config_builder() {
        let config = PoolConfig::new("test", 100 * 1024 * 1024 * 1024)
            .with_block_size(64 * 1024)
            .with_thresholds(Thresholds::new(70, 85, 95))
            .with_overcommit_policy(OvercommitPolicy::StopAtCritical);

        assert_eq!(config.block_size, 64 * 1024);
        assert_eq!(config.thresholds.warning, 70);
        assert!(matches!(
            config.overcommit_policy,
            OvercommitPolicy::StopAtCritical
        ));
    }

    #[test]
    fn test_extent_operations() {
        let e = Extent::new(100, 50);
        assert_eq!(e.start, 100);
        assert_eq!(e.count, 50);
        assert_eq!(e.end(), 150);
        assert!(e.contains(125));
        assert!(!e.contains(150));
    }

    #[test]
    fn test_free_bitmap() {
        let mut bitmap = FreeBitmap::new(1000);

        assert_eq!(bitmap.free_count(), 1000);
        assert!(bitmap.is_free(500));

        bitmap.allocate(500);
        assert!(!bitmap.is_free(500));
        assert_eq!(bitmap.free_count(), 999);

        bitmap.free(500);
        assert!(bitmap.is_free(500));
    }

    #[test]
    fn test_extent_tree() {
        let mut tree = ExtentTree::with_extent(0, 1000);

        let block = tree.allocate_first_fit(100).unwrap();
        assert_eq!(block, 0);
        assert_eq!(tree.free_blocks(), 900);

        tree.free_range(0, 100);
        assert_eq!(tree.free_blocks(), 1000);
    }

    #[test]
    fn test_block_allocator() {
        let mut alloc = BlockAllocator::new(10000, 4096, 100);

        let block = alloc.allocate().unwrap();
        assert!(block.0 >= 100); // After reserved blocks

        alloc.free(block);
    }

    #[test]
    fn test_thin_volume() {
        let config = VolumeConfig::new("test-vol", 1024 * 1024 * 1024);
        let mut vol = ThinVolume::new(1, config);

        assert_eq!(vol.id(), 1);
        assert_eq!(vol.name(), "test-vol");

        let vb = VirtualBlock::new(100);
        let pb = PhysicalBlock::new(5000);

        vol.map_block(vb, pb);
        assert!(vol.is_allocated(vb));
        assert_eq!(vol.get_physical(vb), Some(pb));
    }

    #[test]
    fn test_thin_pool() {
        let config = PoolConfig::new("test-pool", 10 * 1024 * 1024 * 1024);
        let mut pool = ThinPool::new(1, config);

        assert_eq!(pool.name(), "test-pool");
        assert_eq!(pool.volume_count(), 0);

        let vol_config = VolumeConfig::new("vol1", 1024 * 1024 * 1024);
        let vol_id = pool.create_volume(vol_config).unwrap();

        assert_eq!(pool.volume_count(), 1);
        assert!(pool.get_volume(vol_id).is_some());
    }

    #[test]
    fn test_snapshot() {
        let config = PoolConfig::new("snap-test", 10 * 1024 * 1024 * 1024);
        let mut pool = ThinPool::new(1, config);

        let vol_config = VolumeConfig::new("vol1", 1024 * 1024 * 1024);
        let vol_id = pool.create_volume(vol_config).unwrap();

        let snap_id = pool.create_snapshot(vol_id, "snap1".into()).unwrap();

        assert!(pool.get_volume(snap_id).unwrap().is_snapshot());
        assert_eq!(pool.stats().snapshot_count, 1);
    }

    #[test]
    fn test_io_context() {
        let config = VolumeConfig::new("io-test", 1024 * 1024);
        let mut vol = ThinVolume::new(1, config);
        let mut alloc = BlockAllocator::new(1000, 128 * 1024, 0);

        {
            let mut ctx = IoContext::new(&mut vol, &mut alloc);
            let pblock = ctx.write_block(VirtualBlock::new(5)).unwrap();
            assert!(pblock.0 < 1000);
        }

        assert!(vol.is_allocated(VirtualBlock::new(5)));
    }
}