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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! Type definitions for thin provisioning.
//!
//! This module defines the core types used for thin provisioning,
//! including virtual volumes, allocation states, and thresholds.

use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Default block size for thin provisioning (128KB).
pub const DEFAULT_BLOCK_SIZE: u64 = 128 * 1024;

/// Minimum block size (4KB).
pub const MIN_BLOCK_SIZE: u64 = 4 * 1024;

/// Maximum block size (1MB).
pub const MAX_BLOCK_SIZE: u64 = 1024 * 1024;

/// Default warning threshold (80%).
pub const DEFAULT_WARN_THRESHOLD: u8 = 80;

/// Default critical threshold (90%).
pub const DEFAULT_CRITICAL_THRESHOLD: u8 = 90;

/// Default emergency threshold (95%).
pub const DEFAULT_EMERGENCY_THRESHOLD: u8 = 95;

// ═══════════════════════════════════════════════════════════════════════════════
// ALLOCATION STATE
// ═══════════════════════════════════════════════════════════════════════════════

/// State of a virtual block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum BlockState {
    /// Block has not been allocated (zero on read).
    Unallocated = 0,
    /// Block is allocated and contains data.
    Allocated = 1,
    /// Block is pending allocation (write in progress).
    Pending = 2,
    /// Block has been deallocated (hole punched).
    Deallocated = 3,
    /// Block is reserved but not yet written.
    Reserved = 4,
}

impl BlockState {
    /// Convert from raw u8.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            0 => Some(Self::Unallocated),
            1 => Some(Self::Allocated),
            2 => Some(Self::Pending),
            3 => Some(Self::Deallocated),
            4 => Some(Self::Reserved),
            _ => None,
        }
    }

    /// Check if block needs physical space.
    pub fn is_physical(&self) -> bool {
        matches!(self, Self::Allocated | Self::Pending | Self::Reserved)
    }

    /// Check if block returns zeros on read.
    pub fn is_zero(&self) -> bool {
        matches!(self, Self::Unallocated | Self::Deallocated)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VIRTUAL BLOCK ADDRESS
// ═══════════════════════════════════════════════════════════════════════════════

/// Virtual block address in a thin volume.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct VirtualBlock(pub u64);

impl VirtualBlock {
    /// Create a new virtual block address.
    pub fn new(block: u64) -> Self {
        Self(block)
    }

    /// Get the block number.
    pub fn block(&self) -> u64 {
        self.0
    }

    /// Get byte offset with given block size.
    pub fn offset(&self, block_size: u64) -> u64 {
        self.0 * block_size
    }

    /// Get virtual block from byte offset.
    pub fn from_offset(offset: u64, block_size: u64) -> Self {
        Self(offset / block_size)
    }
}

impl From<u64> for VirtualBlock {
    fn from(v: u64) -> Self {
        Self(v)
    }
}

/// Physical block address in a pool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PhysicalBlock(pub u64);

impl PhysicalBlock {
    /// Create a new physical block address.
    pub fn new(block: u64) -> Self {
        Self(block)
    }

    /// Get the block number.
    pub fn block(&self) -> u64 {
        self.0
    }

    /// Get byte offset with given block size.
    pub fn offset(&self, block_size: u64) -> u64 {
        self.0 * block_size
    }
}

impl From<u64> for PhysicalBlock {
    fn from(v: u64) -> Self {
        Self(v)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BLOCK MAPPING
// ═══════════════════════════════════════════════════════════════════════════════

/// Mapping from virtual to physical block.
#[derive(Debug, Clone, Copy)]
pub struct BlockMapping {
    /// Virtual block address.
    pub virtual_block: VirtualBlock,
    /// Physical block address (None if unallocated).
    pub physical_block: Option<PhysicalBlock>,
    /// Block state.
    pub state: BlockState,
    /// Reference count (for snapshots).
    pub refcount: u16,
    /// Flags.
    pub flags: MappingFlags,
}

impl BlockMapping {
    /// Create a new unallocated mapping.
    pub fn unallocated(virtual_block: VirtualBlock) -> Self {
        Self {
            virtual_block,
            physical_block: None,
            state: BlockState::Unallocated,
            refcount: 0,
            flags: MappingFlags::empty(),
        }
    }

    /// Create a new allocated mapping.
    pub fn allocated(virtual_block: VirtualBlock, physical_block: PhysicalBlock) -> Self {
        Self {
            virtual_block,
            physical_block: Some(physical_block),
            state: BlockState::Allocated,
            refcount: 1,
            flags: MappingFlags::empty(),
        }
    }

    /// Check if this mapping has physical storage.
    pub fn is_allocated(&self) -> bool {
        self.physical_block.is_some()
    }

    /// Mark as deallocated (hole).
    pub fn deallocate(&mut self) {
        self.physical_block = None;
        self.state = BlockState::Deallocated;
        self.refcount = 0;
    }

    /// Increment reference count.
    pub fn add_ref(&mut self) {
        self.refcount = self.refcount.saturating_add(1);
    }

    /// Decrement reference count.
    pub fn release(&mut self) -> bool {
        self.refcount = self.refcount.saturating_sub(1);
        self.refcount == 0
    }
}

/// Flags for block mappings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct MappingFlags(pub u8);

impl MappingFlags {
    /// No flags.
    pub const NONE: u8 = 0;
    /// Block is shared (copy-on-write).
    pub const SHARED: u8 = 0x01;
    /// Block is dirty (needs flush).
    pub const DIRTY: u8 = 0x02;
    /// Block is compressed.
    pub const COMPRESSED: u8 = 0x04;
    /// Block is encrypted.
    pub const ENCRYPTED: u8 = 0x08;
    /// Block is being migrated.
    pub const MIGRATING: u8 = 0x10;

    /// Create empty flags.
    pub fn empty() -> Self {
        Self(0)
    }

    /// Create with shared flag.
    pub fn shared() -> Self {
        Self(Self::SHARED)
    }

    /// Check if shared.
    pub fn is_shared(&self) -> bool {
        self.0 & Self::SHARED != 0
    }

    /// Check if dirty.
    pub fn is_dirty(&self) -> bool {
        self.0 & Self::DIRTY != 0
    }

    /// Set dirty flag.
    pub fn set_dirty(&mut self) {
        self.0 |= Self::DIRTY;
    }

    /// Clear dirty flag.
    pub fn clear_dirty(&mut self) {
        self.0 &= !Self::DIRTY;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ALLOCATION THRESHOLDS
// ═══════════════════════════════════════════════════════════════════════════════

/// Space usage thresholds.
#[derive(Debug, Clone, Copy)]
pub struct Thresholds {
    /// Warning threshold (percentage).
    pub warning: u8,
    /// Critical threshold (percentage).
    pub critical: u8,
    /// Emergency threshold (percentage).
    pub emergency: u8,
}

impl Default for Thresholds {
    fn default() -> Self {
        Self {
            warning: DEFAULT_WARN_THRESHOLD,
            critical: DEFAULT_CRITICAL_THRESHOLD,
            emergency: DEFAULT_EMERGENCY_THRESHOLD,
        }
    }
}

impl Thresholds {
    /// Create new thresholds.
    pub fn new(warning: u8, critical: u8, emergency: u8) -> Self {
        Self {
            warning: warning.min(100),
            critical: critical.min(100),
            emergency: emergency.min(100),
        }
    }

    /// Get the threshold level for a given percentage.
    pub fn level(&self, percent: u8) -> ThresholdLevel {
        if percent >= self.emergency {
            ThresholdLevel::Emergency
        } else if percent >= self.critical {
            ThresholdLevel::Critical
        } else if percent >= self.warning {
            ThresholdLevel::Warning
        } else {
            ThresholdLevel::Normal
        }
    }
}

/// Threshold level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum ThresholdLevel {
    /// Normal operation.
    #[default]
    Normal = 0,
    /// Warning level reached.
    Warning = 1,
    /// Critical level reached.
    Critical = 2,
    /// Emergency level reached.
    Emergency = 3,
}

impl ThresholdLevel {
    /// Check if this is a problem level.
    pub fn is_problem(&self) -> bool {
        !matches!(self, Self::Normal)
    }

    /// Get the level name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Warning => "warning",
            Self::Critical => "critical",
            Self::Emergency => "emergency",
        }
    }
}

impl fmt::Display for ThresholdLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VOLUME STATS
// ═══════════════════════════════════════════════════════════════════════════════

/// Statistics for a thin volume.
#[derive(Debug, Clone, Default)]
pub struct VolumeStats {
    /// Virtual size in bytes.
    pub virtual_size: u64,
    /// Physical size used in bytes.
    pub physical_used: u64,
    /// Number of allocated blocks.
    pub allocated_blocks: u64,
    /// Number of unallocated blocks.
    pub unallocated_blocks: u64,
    /// Number of deallocated blocks (holes).
    pub deallocated_blocks: u64,
    /// Number of shared blocks (snapshots).
    pub shared_blocks: u64,
    /// Bytes written.
    pub bytes_written: u64,
    /// Bytes read.
    pub bytes_read: u64,
    /// Allocation operations.
    pub alloc_ops: u64,
    /// Deallocation operations.
    pub dealloc_ops: u64,
    /// Copy-on-write operations.
    pub cow_ops: u64,
}

impl VolumeStats {
    /// Create new empty stats.
    pub fn new(virtual_size: u64) -> Self {
        Self {
            virtual_size,
            ..Default::default()
        }
    }

    /// Get usage percentage.
    pub fn usage_percent(&self) -> u8 {
        if self.virtual_size == 0 {
            return 0;
        }
        ((self.physical_used as u128 * 100) / self.virtual_size as u128) as u8
    }

    /// Get allocation ratio.
    pub fn allocation_ratio(&self) -> f64 {
        if self.physical_used == 0 {
            return 0.0;
        }
        self.virtual_size as f64 / self.physical_used as f64
    }

    /// Get total blocks.
    pub fn total_blocks(&self) -> u64 {
        self.allocated_blocks + self.unallocated_blocks + self.deallocated_blocks
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// POOL STATS
// ═══════════════════════════════════════════════════════════════════════════════

/// Statistics for a thin pool.
#[derive(Debug, Clone, Default)]
pub struct PoolStats {
    /// Total physical capacity in bytes.
    pub total_capacity: u64,
    /// Physical space used by all volumes.
    pub physical_used: u64,
    /// Physical space available.
    pub physical_free: u64,
    /// Total virtual space across all volumes.
    pub total_virtual: u64,
    /// Number of thin volumes.
    pub volume_count: u32,
    /// Number of snapshots.
    pub snapshot_count: u32,
    /// Overcommit ratio.
    pub overcommit_ratio: f64,
    /// Current threshold level.
    pub threshold_level: ThresholdLevel,
}

impl PoolStats {
    /// Create new pool stats.
    pub fn new(total_capacity: u64) -> Self {
        Self {
            total_capacity,
            physical_free: total_capacity,
            ..Default::default()
        }
    }

    /// Get usage percentage.
    pub fn usage_percent(&self) -> u8 {
        if self.total_capacity == 0 {
            return 0;
        }
        ((self.physical_used as u128 * 100) / self.total_capacity as u128) as u8
    }

    /// Update overcommit ratio.
    pub fn update_overcommit(&mut self) {
        if self.total_capacity > 0 {
            self.overcommit_ratio = self.total_virtual as f64 / self.total_capacity as f64;
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ALLOCATION POLICY
// ═══════════════════════════════════════════════════════════════════════════════

/// Policy for block allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AllocationPolicy {
    /// First fit - use first available block.
    #[default]
    FirstFit,
    /// Best fit - use smallest suitable region.
    BestFit,
    /// Next fit - continue from last allocation.
    NextFit,
    /// Contiguous - try to allocate contiguous blocks.
    Contiguous,
    /// Striped - spread across devices.
    Striped,
}

/// Policy for when pool is nearly full.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OvercommitPolicy {
    /// Allow writes until pool is completely full.
    AllowFull,
    /// Stop writes at warning threshold.
    StopAtWarning,
    /// Stop writes at critical threshold.
    StopAtCritical,
    /// Stop writes at emergency threshold.
    #[default]
    StopAtEmergency,
    /// Never stop writes (risk data loss).
    Never,
}

impl OvercommitPolicy {
    /// Check if writes should be allowed at the given level.
    pub fn allows_write(&self, level: ThresholdLevel) -> bool {
        match self {
            Self::AllowFull => true,
            Self::Never => true,
            Self::StopAtWarning => level < ThresholdLevel::Warning,
            Self::StopAtCritical => level < ThresholdLevel::Critical,
            Self::StopAtEmergency => level < ThresholdLevel::Emergency,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VOLUME CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for a thin volume.
#[derive(Debug, Clone)]
pub struct VolumeConfig {
    /// Volume name.
    pub name: String,
    /// Virtual size in bytes.
    pub virtual_size: u64,
    /// Block size.
    pub block_size: u64,
    /// Allocation policy.
    pub allocation_policy: AllocationPolicy,
    /// Enable zero detection (skip zero blocks).
    pub zero_detect: bool,
    /// Enable compression for allocated blocks.
    pub compression: bool,
    /// Dedup key (if dedup is enabled).
    pub dedup_key: Option<String>,
    /// Maximum physical space (None = unlimited).
    pub max_physical: Option<u64>,
    /// Reservation (guaranteed space).
    pub reservation: u64,
}

impl VolumeConfig {
    /// Create a new volume configuration.
    pub fn new(name: impl Into<String>, virtual_size: u64) -> Self {
        Self {
            name: name.into(),
            virtual_size,
            block_size: DEFAULT_BLOCK_SIZE,
            allocation_policy: AllocationPolicy::default(),
            zero_detect: true,
            compression: false,
            dedup_key: None,
            max_physical: None,
            reservation: 0,
        }
    }

    /// Set block size.
    pub fn with_block_size(mut self, size: u64) -> Self {
        self.block_size = size.clamp(MIN_BLOCK_SIZE, MAX_BLOCK_SIZE);
        self
    }

    /// Enable compression.
    pub fn with_compression(mut self) -> Self {
        self.compression = true;
        self
    }

    /// Set maximum physical space.
    pub fn with_max_physical(mut self, max: u64) -> Self {
        self.max_physical = Some(max);
        self
    }

    /// Set reservation.
    pub fn with_reservation(mut self, reservation: u64) -> Self {
        self.reservation = reservation;
        self
    }

    /// Calculate number of virtual blocks.
    pub fn virtual_blocks(&self) -> u64 {
        self.virtual_size.div_ceil(self.block_size)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// POOL CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for a thin pool.
#[derive(Debug, Clone)]
pub struct PoolConfig {
    /// Pool name.
    pub name: String,
    /// Block size.
    pub block_size: u64,
    /// Total physical capacity.
    pub capacity: u64,
    /// Thresholds.
    pub thresholds: Thresholds,
    /// Overcommit policy.
    pub overcommit_policy: OvercommitPolicy,
    /// Allocation policy.
    pub allocation_policy: AllocationPolicy,
    /// Enable automatic trimming.
    pub auto_trim: bool,
    /// Metadata reservation percentage.
    pub metadata_reserve_percent: u8,
}

impl PoolConfig {
    /// Create a new pool configuration.
    pub fn new(name: impl Into<String>, capacity: u64) -> Self {
        Self {
            name: name.into(),
            block_size: DEFAULT_BLOCK_SIZE,
            capacity,
            thresholds: Thresholds::default(),
            overcommit_policy: OvercommitPolicy::default(),
            allocation_policy: AllocationPolicy::default(),
            auto_trim: true,
            metadata_reserve_percent: 5,
        }
    }

    /// Set block size.
    pub fn with_block_size(mut self, size: u64) -> Self {
        self.block_size = size.clamp(MIN_BLOCK_SIZE, MAX_BLOCK_SIZE);
        self
    }

    /// Set thresholds.
    pub fn with_thresholds(mut self, thresholds: Thresholds) -> Self {
        self.thresholds = thresholds;
        self
    }

    /// Set overcommit policy.
    pub fn with_overcommit_policy(mut self, policy: OvercommitPolicy) -> Self {
        self.overcommit_policy = policy;
        self
    }

    /// Calculate usable capacity (after metadata reservation).
    pub fn usable_capacity(&self) -> u64 {
        let reserved = (self.capacity as u128 * self.metadata_reserve_percent as u128 / 100) as u64;
        self.capacity.saturating_sub(reserved)
    }

    /// Calculate number of physical blocks.
    pub fn physical_blocks(&self) -> u64 {
        self.usable_capacity() / self.block_size
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ALERTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Alert type for thin provisioning events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertType {
    /// Threshold crossed.
    ThresholdCrossed,
    /// Pool nearly full.
    PoolNearlyFull,
    /// Pool full (writes will fail).
    PoolFull,
    /// Volume exceeded reservation.
    ReservationExceeded,
    /// Allocation failure.
    AllocationFailed,
    /// Snapshot space issue.
    SnapshotSpaceIssue,
}

/// An alert from the thin provisioning system.
#[derive(Debug, Clone)]
pub struct Alert {
    /// Alert type.
    pub alert_type: AlertType,
    /// Severity level.
    pub level: ThresholdLevel,
    /// Pool name.
    pub pool_name: String,
    /// Volume name (if applicable).
    pub volume_name: Option<String>,
    /// Current usage percentage.
    pub usage_percent: u8,
    /// Alert message.
    pub message: String,
    /// Timestamp (epoch seconds).
    pub timestamp: u64,
}

impl Alert {
    /// Create a new alert.
    pub fn new(
        alert_type: AlertType,
        level: ThresholdLevel,
        pool_name: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            alert_type,
            level,
            pool_name: pool_name.into(),
            volume_name: None,
            usage_percent: 0,
            message: message.into(),
            timestamp: 0,
        }
    }

    /// Set volume name.
    pub fn with_volume(mut self, name: impl Into<String>) -> Self {
        self.volume_name = Some(name.into());
        self
    }

    /// Set usage percentage.
    pub fn with_usage(mut self, percent: u8) -> Self {
        self.usage_percent = percent;
        self
    }

    /// Set timestamp.
    pub fn with_timestamp(mut self, ts: u64) -> Self {
        self.timestamp = ts;
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR TYPE
// ═══════════════════════════════════════════════════════════════════════════════

/// Error type for thin provisioning operations.
#[derive(Debug, Clone)]
pub enum ThinError {
    /// Pool not found.
    PoolNotFound(String),
    /// Volume not found.
    VolumeNotFound(String),
    /// Pool is full.
    PoolFull,
    /// Volume limit reached.
    VolumeLimitReached,
    /// Allocation failed.
    AllocationFailed,
    /// Invalid block size.
    InvalidBlockSize,
    /// Invalid configuration.
    InvalidConfig(String),
    /// Volume already exists.
    VolumeExists(String),
    /// Snapshot not found.
    SnapshotNotFound(String),
    /// Operation not permitted.
    NotPermitted,
    /// I/O error.
    IoError,
}

impl fmt::Display for ThinError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PoolNotFound(name) => write!(f, "Pool not found: {}", name),
            Self::VolumeNotFound(name) => write!(f, "Volume not found: {}", name),
            Self::PoolFull => write!(f, "Pool is full"),
            Self::VolumeLimitReached => write!(f, "Volume physical limit reached"),
            Self::AllocationFailed => write!(f, "Block allocation failed"),
            Self::InvalidBlockSize => write!(f, "Invalid block size"),
            Self::InvalidConfig(msg) => write!(f, "Invalid configuration: {}", msg),
            Self::VolumeExists(name) => write!(f, "Volume already exists: {}", name),
            Self::SnapshotNotFound(name) => write!(f, "Snapshot not found: {}", name),
            Self::NotPermitted => write!(f, "Operation not permitted"),
            Self::IoError => write!(f, "I/O error"),
        }
    }
}

/// Result type for thin provisioning.
pub type ThinResult<T> = core::result::Result<T, ThinError>;

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_block_state() {
        assert!(BlockState::Unallocated.is_zero());
        assert!(BlockState::Deallocated.is_zero());
        assert!(!BlockState::Allocated.is_zero());

        assert!(BlockState::Allocated.is_physical());
        assert!(BlockState::Pending.is_physical());
        assert!(!BlockState::Unallocated.is_physical());
    }

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

        let vb2 = VirtualBlock::from_offset(409600, 4096);
        assert_eq!(vb2.block(), 100);
    }

    #[test]
    fn test_block_mapping() {
        let vb = VirtualBlock::new(50);
        let pb = PhysicalBlock::new(1000);

        let mut mapping = BlockMapping::unallocated(vb);
        assert!(!mapping.is_allocated());
        assert_eq!(mapping.state, BlockState::Unallocated);

        let allocated = BlockMapping::allocated(vb, pb);
        assert!(allocated.is_allocated());
        assert_eq!(allocated.refcount, 1);
    }

    #[test]
    fn test_block_mapping_refcount() {
        let vb = VirtualBlock::new(50);
        let pb = PhysicalBlock::new(1000);

        let mut mapping = BlockMapping::allocated(vb, pb);
        assert_eq!(mapping.refcount, 1);

        mapping.add_ref();
        assert_eq!(mapping.refcount, 2);

        assert!(!mapping.release()); // returns false, refcount > 0
        assert_eq!(mapping.refcount, 1);

        assert!(mapping.release()); // returns true, refcount == 0
        assert_eq!(mapping.refcount, 0);
    }

    #[test]
    fn test_mapping_flags() {
        let mut flags = MappingFlags::empty();
        assert!(!flags.is_dirty());

        flags.set_dirty();
        assert!(flags.is_dirty());

        flags.clear_dirty();
        assert!(!flags.is_dirty());

        let shared = MappingFlags::shared();
        assert!(shared.is_shared());
    }

    #[test]
    fn test_thresholds() {
        let t = Thresholds::default();
        assert_eq!(t.level(50), ThresholdLevel::Normal);
        assert_eq!(t.level(80), ThresholdLevel::Warning);
        assert_eq!(t.level(90), ThresholdLevel::Critical);
        assert_eq!(t.level(95), ThresholdLevel::Emergency);
    }

    #[test]
    fn test_threshold_level() {
        assert!(!ThresholdLevel::Normal.is_problem());
        assert!(ThresholdLevel::Warning.is_problem());
        assert!(ThresholdLevel::Critical.is_problem());
        assert!(ThresholdLevel::Emergency.is_problem());
    }

    #[test]
    fn test_volume_stats() {
        let mut stats = VolumeStats::new(1024 * 1024 * 1024); // 1GB
        stats.physical_used = 256 * 1024 * 1024; // 256MB

        assert_eq!(stats.usage_percent(), 25);
        assert_eq!(stats.allocation_ratio(), 4.0);
    }

    #[test]
    fn test_pool_stats() {
        let mut stats = PoolStats::new(10 * 1024 * 1024 * 1024); // 10GB
        stats.physical_used = 5 * 1024 * 1024 * 1024; // 5GB
        stats.total_virtual = 50 * 1024 * 1024 * 1024; // 50GB
        stats.update_overcommit();

        assert_eq!(stats.usage_percent(), 50);
        assert_eq!(stats.overcommit_ratio, 5.0);
    }

    #[test]
    fn test_overcommit_policy() {
        let policy = OvercommitPolicy::StopAtCritical;

        assert!(policy.allows_write(ThresholdLevel::Normal));
        assert!(policy.allows_write(ThresholdLevel::Warning));
        assert!(!policy.allows_write(ThresholdLevel::Critical));
        assert!(!policy.allows_write(ThresholdLevel::Emergency));
    }

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

        assert_eq!(config.name, "test-vol");
        assert_eq!(config.block_size, 256 * 1024);
        assert!(config.compression);
        assert_eq!(config.reservation, 10 * 1024 * 1024 * 1024);
    }

    #[test]
    fn test_pool_config() {
        let config = PoolConfig::new("test-pool", 100 * 1024 * 1024 * 1024);

        // 5% reserved for metadata
        let usable = config.usable_capacity();
        assert_eq!(usable, 95 * 1024 * 1024 * 1024);
    }

    #[test]
    fn test_alert() {
        let alert = Alert::new(
            AlertType::ThresholdCrossed,
            ThresholdLevel::Warning,
            "pool1",
            "Pool usage at 80%",
        )
        .with_volume("vol1")
        .with_usage(80);

        assert_eq!(alert.alert_type, AlertType::ThresholdCrossed);
        assert_eq!(alert.level, ThresholdLevel::Warning);
        assert_eq!(alert.volume_name, Some("vol1".into()));
        assert_eq!(alert.usage_percent, 80);
    }

    #[test]
    fn test_thin_error_display() {
        let err = ThinError::PoolFull;
        assert_eq!(alloc::format!("{}", err), "Pool is full");

        let err2 = ThinError::VolumeNotFound("vol1".into());
        assert_eq!(alloc::format!("{}", err2), "Volume not found: vol1");
    }
}