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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! NFS type definitions for NFSv4 protocol implementation.
//!
//! This module defines the core types used by the NFS server, including
//! file handles, attributes, operations, and error codes.

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

// ═══════════════════════════════════════════════════════════════════════════════
// NFS4 CONSTANTS
// ═══════════════════════════════════════════════════════════════════════════════

/// NFS4 program number.
pub const NFS4_PROGRAM: u32 = 100003;

/// NFS4 version.
pub const NFS4_VERSION: u32 = 4;

/// Maximum file handle size (RFC 7530 specifies 128 bytes).
pub const NFS4_FHSIZE: usize = 128;

/// Maximum name length.
pub const NFS4_MAXNAMLEN: usize = 255;

/// Maximum path length.
pub const NFS4_MAXPATHLEN: usize = 4096;

// ═══════════════════════════════════════════════════════════════════════════════
// FILE HANDLE
// ═══════════════════════════════════════════════════════════════════════════════

/// NFS file handle - opaque identifier for files/directories.
///
/// The handle encodes:
/// - Dataset ID (for multi-dataset exports)
/// - Object ID (inode equivalent)
/// - Generation number (for stale handle detection)
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct FileHandle {
    /// Raw handle data.
    data: [u8; NFS4_FHSIZE],
    /// Actual length of handle data.
    len: usize,
}

impl FileHandle {
    /// Create a new file handle from components.
    pub fn new(dataset_id: u64, object_id: u64, generation: u64) -> Self {
        let mut data = [0u8; NFS4_FHSIZE];

        // Encode dataset ID (8 bytes)
        data[0..8].copy_from_slice(&dataset_id.to_le_bytes());
        // Encode object ID (8 bytes)
        data[8..16].copy_from_slice(&object_id.to_le_bytes());
        // Encode generation (8 bytes)
        data[16..24].copy_from_slice(&generation.to_le_bytes());

        Self { data, len: 24 }
    }

    /// Create a root file handle for a dataset.
    pub fn root(dataset_id: u64) -> Self {
        Self::new(dataset_id, 0, 0)
    }

    /// Create from raw bytes.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() > NFS4_FHSIZE {
            return None;
        }

        let mut data = [0u8; NFS4_FHSIZE];
        data[..bytes.len()].copy_from_slice(bytes);

        Some(Self {
            data,
            len: bytes.len(),
        })
    }

    /// Get the raw bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.data[..self.len]
    }

    /// Get the dataset ID.
    pub fn dataset_id(&self) -> u64 {
        if self.len >= 8 {
            u64::from_le_bytes(self.data[0..8].try_into().unwrap())
        } else {
            0
        }
    }

    /// Get the object ID.
    pub fn object_id(&self) -> u64 {
        if self.len >= 16 {
            u64::from_le_bytes(self.data[8..16].try_into().unwrap())
        } else {
            0
        }
    }

    /// Get the generation number.
    pub fn generation(&self) -> u64 {
        if self.len >= 24 {
            u64::from_le_bytes(self.data[16..24].try_into().unwrap())
        } else {
            0
        }
    }

    /// Check if this is a root handle.
    pub fn is_root(&self) -> bool {
        self.object_id() == 0
    }

    /// Get handle length.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Check if handle is empty.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }
}

impl fmt::Debug for FileHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "FileHandle(ds={}, obj={}, gen={})",
            self.dataset_id(),
            self.object_id(),
            self.generation()
        )
    }
}

impl Default for FileHandle {
    fn default() -> Self {
        Self {
            data: [0u8; NFS4_FHSIZE],
            len: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILE TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// NFS file type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum FileType {
    /// Regular file.
    Regular = 1,
    /// Directory.
    Directory = 2,
    /// Block device.
    Block = 3,
    /// Character device.
    Character = 4,
    /// Symbolic link.
    Symlink = 5,
    /// Socket.
    Socket = 6,
    /// Named pipe (FIFO).
    Fifo = 7,
    /// Attribute directory (NFSv4).
    AttrDir = 8,
    /// Named attribute (NFSv4).
    NamedAttr = 9,
}

impl FileType {
    /// Convert from raw u32.
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            1 => Some(Self::Regular),
            2 => Some(Self::Directory),
            3 => Some(Self::Block),
            4 => Some(Self::Character),
            5 => Some(Self::Symlink),
            6 => Some(Self::Socket),
            7 => Some(Self::Fifo),
            8 => Some(Self::AttrDir),
            9 => Some(Self::NamedAttr),
            _ => None,
        }
    }

    /// Check if this is a directory type.
    pub fn is_directory(&self) -> bool {
        matches!(self, Self::Directory | Self::AttrDir)
    }

    /// Check if this is a regular file.
    pub fn is_regular(&self) -> bool {
        matches!(self, Self::Regular)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILE ATTRIBUTES
// ═══════════════════════════════════════════════════════════════════════════════

/// NFS file attributes.
#[derive(Debug, Clone)]
pub struct NfsAttr {
    /// File type.
    pub file_type: FileType,
    /// Permission mode (Unix-style).
    pub mode: u32,
    /// Number of hard links.
    pub nlink: u32,
    /// Owner user ID.
    pub uid: u32,
    /// Owner group ID.
    pub gid: u32,
    /// File size in bytes.
    pub size: u64,
    /// Allocated space in bytes.
    pub used: u64,
    /// Block size for I/O.
    pub blksize: u32,
    /// Number of blocks allocated.
    pub blocks: u64,
    /// File system ID.
    pub fsid: u64,
    /// File ID (inode).
    pub fileid: u64,
    /// Access time (seconds since epoch).
    pub atime_sec: u64,
    /// Access time (nanoseconds).
    pub atime_nsec: u32,
    /// Modification time (seconds).
    pub mtime_sec: u64,
    /// Modification time (nanoseconds).
    pub mtime_nsec: u32,
    /// Status change time (seconds).
    pub ctime_sec: u64,
    /// Status change time (nanoseconds).
    pub ctime_nsec: u32,
    /// Device ID for special files.
    pub rdev: u64,
}

impl NfsAttr {
    /// Create attributes for a directory.
    pub fn directory(fileid: u64, mode: u32, uid: u32, gid: u32) -> Self {
        Self {
            file_type: FileType::Directory,
            mode: mode | 0o40000, // S_IFDIR
            nlink: 2,
            uid,
            gid,
            size: 4096,
            used: 4096,
            blksize: 4096,
            blocks: 8,
            fsid: 0,
            fileid,
            atime_sec: 0,
            atime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
            ctime_sec: 0,
            ctime_nsec: 0,
            rdev: 0,
        }
    }

    /// Create attributes for a regular file.
    pub fn file(fileid: u64, size: u64, mode: u32, uid: u32, gid: u32) -> Self {
        let blocks = size.div_ceil(512);
        Self {
            file_type: FileType::Regular,
            mode: mode | 0o100000, // S_IFREG
            nlink: 1,
            uid,
            gid,
            size,
            used: blocks * 512,
            blksize: 4096,
            blocks,
            fsid: 0,
            fileid,
            atime_sec: 0,
            atime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
            ctime_sec: 0,
            ctime_nsec: 0,
            rdev: 0,
        }
    }

    /// Set timestamps.
    pub fn with_times(mut self, atime: u64, mtime: u64, ctime: u64) -> Self {
        self.atime_sec = atime;
        self.mtime_sec = mtime;
        self.ctime_sec = ctime;
        self
    }

    /// Set filesystem ID.
    pub fn with_fsid(mut self, fsid: u64) -> Self {
        self.fsid = fsid;
        self
    }
}

impl Default for NfsAttr {
    fn default() -> Self {
        Self {
            file_type: FileType::Regular,
            mode: 0o644,
            nlink: 1,
            uid: 0,
            gid: 0,
            size: 0,
            used: 0,
            blksize: 4096,
            blocks: 0,
            fsid: 0,
            fileid: 0,
            atime_sec: 0,
            atime_nsec: 0,
            mtime_sec: 0,
            mtime_nsec: 0,
            ctime_sec: 0,
            ctime_nsec: 0,
            rdev: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ATTRIBUTE BITMASK
// ═══════════════════════════════════════════════════════════════════════════════

/// NFSv4 attribute bitmask for selecting which attributes to return.
#[derive(Debug, Clone, Default)]
pub struct AttrBitmap {
    /// Bitmap words.
    pub words: [u32; 3],
}

impl AttrBitmap {
    /// Create empty bitmap.
    pub fn new() -> Self {
        Self { words: [0; 3] }
    }

    /// Create bitmap with all supported attributes.
    pub fn all_supported() -> Self {
        Self {
            words: [
                0x0011a7ff, // Word 0: type, size, fileid, mode, owner, etc.
                0x00b0a23a, // Word 1: time attributes, etc.
                0x00000000, // Word 2: extended attributes
            ],
        }
    }

    /// Set a specific attribute bit.
    pub fn set(&mut self, attr: u32) {
        let word = (attr / 32) as usize;
        let bit = attr % 32;
        if word < 3 {
            self.words[word] |= 1 << bit;
        }
    }

    /// Check if an attribute bit is set.
    pub fn is_set(&self, attr: u32) -> bool {
        let word = (attr / 32) as usize;
        let bit = attr % 32;
        word < 3 && (self.words[word] & (1 << bit)) != 0
    }

    /// Create from raw words.
    pub fn from_words(words: &[u32]) -> Self {
        let mut bitmap = Self::new();
        for (i, &w) in words.iter().take(3).enumerate() {
            bitmap.words[i] = w;
        }
        bitmap
    }
}

// Standard attribute numbers
/// Supported attributes.
pub const FATTR4_SUPPORTED_ATTRS: u32 = 0;
/// File type.
pub const FATTR4_TYPE: u32 = 1;
/// File handle expiration.
pub const FATTR4_FH_EXPIRE_TYPE: u32 = 2;
/// Change attribute.
pub const FATTR4_CHANGE: u32 = 3;
/// File size.
pub const FATTR4_SIZE: u32 = 4;
/// Link support.
pub const FATTR4_LINK_SUPPORT: u32 = 5;
/// Symlink support.
pub const FATTR4_SYMLINK_SUPPORT: u32 = 6;
/// Named attr support.
pub const FATTR4_NAMED_ATTR: u32 = 7;
/// Filesystem ID.
pub const FATTR4_FSID: u32 = 8;
/// File ID.
pub const FATTR4_FILEID: u32 = 20;
/// Files available.
pub const FATTR4_FILES_AVAIL: u32 = 11;
/// Files free.
pub const FATTR4_FILES_FREE: u32 = 12;
/// Files total.
pub const FATTR4_FILES_TOTAL: u32 = 13;
/// Max file size.
pub const FATTR4_MAXFILESIZE: u32 = 27;
/// Max link.
pub const FATTR4_MAXLINK: u32 = 28;
/// Max name.
pub const FATTR4_MAXNAME: u32 = 29;
/// Max read.
pub const FATTR4_MAXREAD: u32 = 30;
/// Max write.
pub const FATTR4_MAXWRITE: u32 = 31;
/// Mode.
pub const FATTR4_MODE: u32 = 33;
/// Number of links.
pub const FATTR4_NUMLINKS: u32 = 35;
/// Owner.
pub const FATTR4_OWNER: u32 = 36;
/// Owner group.
pub const FATTR4_OWNER_GROUP: u32 = 37;
/// Space available.
pub const FATTR4_SPACE_AVAIL: u32 = 42;
/// Space free.
pub const FATTR4_SPACE_FREE: u32 = 43;
/// Space total.
pub const FATTR4_SPACE_TOTAL: u32 = 44;
/// Space used.
pub const FATTR4_SPACE_USED: u32 = 45;
/// Time access.
pub const FATTR4_TIME_ACCESS: u32 = 47;
/// Time metadata (ctime).
pub const FATTR4_TIME_METADATA: u32 = 52;
/// Time modify.
pub const FATTR4_TIME_MODIFY: u32 = 53;

// ═══════════════════════════════════════════════════════════════════════════════
// ACCESS BITS
// ═══════════════════════════════════════════════════════════════════════════════

/// Access check bits for ACCESS operation.
#[derive(Debug, Clone, Copy, Default)]
pub struct AccessBits(pub u32);

impl AccessBits {
    /// Read data.
    pub const READ: u32 = 0x00000001;
    /// Lookup in directory.
    pub const LOOKUP: u32 = 0x00000002;
    /// Modify file data.
    pub const MODIFY: u32 = 0x00000004;
    /// Extend file.
    pub const EXTEND: u32 = 0x00000008;
    /// Delete file.
    pub const DELETE: u32 = 0x00000010;
    /// Execute file.
    pub const EXECUTE: u32 = 0x00000020;

    /// Create new access bits.
    pub fn new(bits: u32) -> Self {
        Self(bits)
    }

    /// Check if read access is requested.
    pub fn read(&self) -> bool {
        self.0 & Self::READ != 0
    }

    /// Check if lookup access is requested.
    pub fn lookup(&self) -> bool {
        self.0 & Self::LOOKUP != 0
    }

    /// Check if modify access is requested.
    pub fn modify(&self) -> bool {
        self.0 & Self::MODIFY != 0
    }

    /// Check if extend access is requested.
    pub fn extend(&self) -> bool {
        self.0 & Self::EXTEND != 0
    }

    /// Check if delete access is requested.
    pub fn delete(&self) -> bool {
        self.0 & Self::DELETE != 0
    }

    /// Check if execute access is requested.
    pub fn execute(&self) -> bool {
        self.0 & Self::EXECUTE != 0
    }

    /// Get all access bits for a file.
    pub fn all_file() -> Self {
        Self(Self::READ | Self::MODIFY | Self::EXTEND | Self::EXECUTE)
    }

    /// Get all access bits for a directory.
    pub fn all_dir() -> Self {
        Self(Self::READ | Self::LOOKUP | Self::MODIFY | Self::EXTEND | Self::DELETE)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// OPEN FLAGS
// ═══════════════════════════════════════════════════════════════════════════════

/// Open/create mode for OPEN operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum OpenMode {
    /// No create, fail if doesn't exist.
    Unchecked = 0,
    /// Create if doesn't exist.
    Guarded = 1,
    /// Exclusive create (fail if exists).
    Exclusive = 2,
    /// Exclusive create with verifier (NFSv4.1).
    Exclusive4_1 = 3,
}

/// Share access mode for OPEN operation.
#[derive(Debug, Clone, Copy)]
pub struct ShareAccess(pub u32);

impl ShareAccess {
    /// Read access.
    pub const READ: u32 = 0x00000001;
    /// Write access.
    pub const WRITE: u32 = 0x00000002;
    /// Both read and write.
    pub const BOTH: u32 = 0x00000003;

    /// Create new share access.
    pub fn new(bits: u32) -> Self {
        Self(bits)
    }

    /// Check if read access.
    pub fn read(&self) -> bool {
        self.0 & Self::READ != 0
    }

    /// Check if write access.
    pub fn write(&self) -> bool {
        self.0 & Self::WRITE != 0
    }
}

/// Share deny mode for OPEN operation.
#[derive(Debug, Clone, Copy)]
pub struct ShareDeny(pub u32);

impl ShareDeny {
    /// No denial.
    pub const NONE: u32 = 0x00000000;
    /// Deny read.
    pub const READ: u32 = 0x00000001;
    /// Deny write.
    pub const WRITE: u32 = 0x00000002;
    /// Deny both.
    pub const BOTH: u32 = 0x00000003;

    /// Create new share deny.
    pub fn new(bits: u32) -> Self {
        Self(bits)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// STATE IDS
// ═══════════════════════════════════════════════════════════════════════════════

/// NFSv4 state ID for tracking open/lock state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct StateId {
    /// Sequence number.
    pub seqid: u32,
    /// Other data (12 bytes).
    pub other: [u8; 12],
}

impl StateId {
    /// Create a new state ID.
    pub fn new(seqid: u32, other: [u8; 12]) -> Self {
        Self { seqid, other }
    }

    /// Anonymous state ID (all zeros).
    pub fn anonymous() -> Self {
        Self {
            seqid: 0,
            other: [0; 12],
        }
    }

    /// Current state ID (for stateless operations).
    pub fn current() -> Self {
        Self {
            seqid: 1,
            other: [0xff; 12],
        }
    }

    /// Special bypass state ID (for internal use).
    pub fn bypass() -> Self {
        Self {
            seqid: 0xffffffff,
            other: [0xff; 12],
        }
    }

    /// Check if this is the anonymous state ID.
    pub fn is_anonymous(&self) -> bool {
        self.seqid == 0 && self.other == [0; 12]
    }

    /// Check if this is the current state ID.
    pub fn is_current(&self) -> bool {
        self.seqid == 1 && self.other == [0xff; 12]
    }
}

impl Default for StateId {
    fn default() -> Self {
        Self::anonymous()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CLIENT ID
// ═══════════════════════════════════════════════════════════════════════════════

/// NFSv4 client ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClientId {
    /// Client ID value.
    pub id: u64,
}

impl ClientId {
    /// Create a new client ID.
    pub fn new(id: u64) -> Self {
        Self { id }
    }

    /// Generate a new unique client ID.
    pub fn generate() -> Self {
        use core::sync::atomic::{AtomicU64, Ordering};
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Self {
            id: NEXT_ID.fetch_add(1, Ordering::SeqCst),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SESSION (NFSv4.1)
// ═══════════════════════════════════════════════════════════════════════════════

/// NFSv4.1 session ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct SessionId {
    /// Session ID (16 bytes).
    pub id: [u8; 16],
}

impl SessionId {
    /// Create a new session ID.
    pub fn new(id: [u8; 16]) -> Self {
        Self { id }
    }

    /// Generate a new session ID.
    pub fn generate() -> Self {
        use core::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);

        let count = COUNTER.fetch_add(1, Ordering::SeqCst);
        let mut id = [0u8; 16];
        id[0..8].copy_from_slice(&count.to_le_bytes());
        // Add some distinguishing bytes
        id[8..16].copy_from_slice(&0x4C435046534E4653_u64.to_le_bytes()); // "LCPFSNFS"

        Self { id }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// DIRECTORY ENTRY
// ═══════════════════════════════════════════════════════════════════════════════

/// Directory entry for READDIR.
#[derive(Debug, Clone)]
pub struct DirEntry {
    /// Cookie for this entry.
    pub cookie: u64,
    /// Entry name.
    pub name: String,
    /// File attributes (if requested).
    pub attrs: Option<NfsAttr>,
    /// File handle (if requested).
    pub fh: Option<FileHandle>,
}

impl DirEntry {
    /// Create a new directory entry.
    pub fn new(cookie: u64, name: String) -> Self {
        Self {
            cookie,
            name,
            attrs: None,
            fh: None,
        }
    }

    /// Add attributes.
    pub fn with_attrs(mut self, attrs: NfsAttr) -> Self {
        self.attrs = Some(attrs);
        self
    }

    /// Add file handle.
    pub fn with_handle(mut self, fh: FileHandle) -> Self {
        self.fh = Some(fh);
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SET ATTRIBUTES
// ═══════════════════════════════════════════════════════════════════════════════

/// Attributes to set on a file.
#[derive(Debug, Clone, Default)]
pub struct SetAttr {
    /// New mode (if Some).
    pub mode: Option<u32>,
    /// New UID (if Some).
    pub uid: Option<u32>,
    /// New GID (if Some).
    pub gid: Option<u32>,
    /// New size (if Some).
    pub size: Option<u64>,
    /// New access time.
    pub atime: Option<TimeHow>,
    /// New modify time.
    pub mtime: Option<TimeHow>,
}

/// How to set a time attribute.
#[derive(Debug, Clone, Copy)]
pub enum TimeHow {
    /// Don't change.
    DontChange,
    /// Set to server time.
    SetToServerTime,
    /// Set to client time.
    SetToClientTime {
        /// Seconds since epoch.
        sec: u64,
        /// Nanoseconds.
        nsec: u32,
    },
}

impl SetAttr {
    /// Create empty set attributes.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set mode.
    pub fn with_mode(mut self, mode: u32) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Set size.
    pub fn with_size(mut self, size: u64) -> Self {
        self.size = Some(size);
        self
    }

    /// Set owner.
    pub fn with_owner(mut self, uid: u32, gid: u32) -> Self {
        self.uid = Some(uid);
        self.gid = Some(gid);
        self
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// LOCK TYPES
// ═══════════════════════════════════════════════════════════════════════════════

/// Lock type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum LockType {
    /// Read lock.
    Read = 1,
    /// Write lock.
    Write = 2,
    /// Read lock (blocking).
    ReadBlocking = 3,
    /// Write lock (blocking).
    WriteBlocking = 4,
}

/// Lock range.
#[derive(Debug, Clone, Copy)]
pub struct LockRange {
    /// Offset.
    pub offset: u64,
    /// Length (0 = to end of file).
    pub length: u64,
}

impl LockRange {
    /// Create a new lock range.
    pub fn new(offset: u64, length: u64) -> Self {
        Self { offset, length }
    }

    /// Create a range covering the entire file.
    pub fn all() -> Self {
        Self {
            offset: 0,
            length: 0,
        }
    }

    /// Check if ranges overlap.
    pub fn overlaps(&self, other: &Self) -> bool {
        let end1 = if self.length == 0 {
            u64::MAX
        } else {
            self.offset.saturating_add(self.length)
        };
        let end2 = if other.length == 0 {
            u64::MAX
        } else {
            other.offset.saturating_add(other.length)
        };

        self.offset < end2 && other.offset < end1
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FILESYSTEM INFO
// ═══════════════════════════════════════════════════════════════════════════════

/// Filesystem information for FSINFO/FSSTAT.
#[derive(Debug, Clone)]
pub struct FsInfo {
    /// Maximum read size.
    pub rtmax: u32,
    /// Preferred read size.
    pub rtpref: u32,
    /// Multiple for reads.
    pub rtmult: u32,
    /// Maximum write size.
    pub wtmax: u32,
    /// Preferred write size.
    pub wtpref: u32,
    /// Multiple for writes.
    pub wtmult: u32,
    /// Preferred READDIR size.
    pub dtpref: u32,
    /// Maximum file size.
    pub maxfilesize: u64,
    /// Time delta.
    pub time_delta_sec: u32,
    /// Time delta nanoseconds.
    pub time_delta_nsec: u32,
    /// Properties bitmap.
    pub properties: u32,
}

impl Default for FsInfo {
    fn default() -> Self {
        Self {
            rtmax: 1024 * 1024,    // 1MB
            rtpref: 128 * 1024,    // 128KB
            rtmult: 4096,          // 4KB
            wtmax: 1024 * 1024,    // 1MB
            wtpref: 128 * 1024,    // 128KB
            wtmult: 4096,          // 4KB
            dtpref: 8192,          // 8KB
            maxfilesize: u64::MAX, // No limit
            time_delta_sec: 0,
            time_delta_nsec: 1,     // 1ns precision
            properties: 0x0000001b, // link, symlink, homogeneous, cansettime
        }
    }
}

/// Filesystem statistics for FSSTAT.
#[derive(Debug, Clone)]
pub struct FsStat {
    /// Total bytes.
    pub tbytes: u64,
    /// Free bytes.
    pub fbytes: u64,
    /// Available bytes.
    pub abytes: u64,
    /// Total files.
    pub tfiles: u64,
    /// Free files.
    pub ffiles: u64,
    /// Available files.
    pub afiles: u64,
    /// Seconds since last update.
    pub invarsec: u32,
}

impl Default for FsStat {
    fn default() -> Self {
        Self {
            tbytes: 1024 * 1024 * 1024 * 1024, // 1TB
            fbytes: 512 * 1024 * 1024 * 1024,  // 512GB
            abytes: 512 * 1024 * 1024 * 1024,  // 512GB
            tfiles: 1_000_000_000,
            ffiles: 500_000_000,
            afiles: 500_000_000,
            invarsec: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// VERIFIER
// ═══════════════════════════════════════════════════════════════════════════════

/// NFS verifier (8 bytes) for operations like READDIR.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Verifier(pub [u8; 8]);

impl Verifier {
    /// Create a new verifier.
    pub fn new(data: [u8; 8]) -> Self {
        Self(data)
    }

    /// Create a verifier from a u64.
    pub fn from_u64(v: u64) -> Self {
        Self(v.to_le_bytes())
    }

    /// Get as u64.
    pub fn as_u64(&self) -> u64 {
        u64::from_le_bytes(self.0)
    }

    /// Generate a new unique verifier.
    pub fn generate() -> Self {
        use core::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self::from_u64(COUNTER.fetch_add(1, Ordering::SeqCst))
    }
}

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

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

    #[test]
    fn test_file_handle_creation() {
        let fh = FileHandle::new(1, 100, 5);
        assert_eq!(fh.dataset_id(), 1);
        assert_eq!(fh.object_id(), 100);
        assert_eq!(fh.generation(), 5);
        assert!(!fh.is_root());
    }

    #[test]
    fn test_file_handle_root() {
        let fh = FileHandle::root(42);
        assert_eq!(fh.dataset_id(), 42);
        assert_eq!(fh.object_id(), 0);
        assert!(fh.is_root());
    }

    #[test]
    fn test_file_handle_from_bytes() {
        let fh1 = FileHandle::new(1, 2, 3);
        let fh2 = FileHandle::from_bytes(fh1.as_bytes()).unwrap();
        assert_eq!(fh1.dataset_id(), fh2.dataset_id());
        assert_eq!(fh1.object_id(), fh2.object_id());
        assert_eq!(fh1.generation(), fh2.generation());
    }

    #[test]
    fn test_file_type() {
        assert!(FileType::Directory.is_directory());
        assert!(FileType::AttrDir.is_directory());
        assert!(!FileType::Regular.is_directory());
        assert!(FileType::Regular.is_regular());
    }

    #[test]
    fn test_nfs_attr_directory() {
        let attr = NfsAttr::directory(100, 0o755, 1000, 1000);
        assert_eq!(attr.file_type, FileType::Directory);
        assert_eq!(attr.fileid, 100);
        assert_eq!(attr.nlink, 2);
    }

    #[test]
    fn test_nfs_attr_file() {
        let attr = NfsAttr::file(200, 4096, 0o644, 1000, 1000);
        assert_eq!(attr.file_type, FileType::Regular);
        assert_eq!(attr.size, 4096);
        assert_eq!(attr.blocks, 8); // 4096 / 512
    }

    #[test]
    fn test_attr_bitmap() {
        let mut bitmap = AttrBitmap::new();
        bitmap.set(FATTR4_SIZE);
        assert!(bitmap.is_set(FATTR4_SIZE));
        assert!(!bitmap.is_set(FATTR4_MODE));
    }

    #[test]
    fn test_access_bits() {
        let access = AccessBits::new(AccessBits::READ | AccessBits::MODIFY);
        assert!(access.read());
        assert!(!access.lookup());
        assert!(access.modify()); // WRITE implies MODIFY
    }

    #[test]
    fn test_state_id() {
        let anon = StateId::anonymous();
        assert!(anon.is_anonymous());
        assert!(!anon.is_current());

        let current = StateId::current();
        assert!(!current.is_anonymous());
        assert!(current.is_current());
    }

    #[test]
    fn test_lock_range_overlap() {
        let r1 = LockRange::new(0, 100);
        let r2 = LockRange::new(50, 100);
        let r3 = LockRange::new(200, 100);

        assert!(r1.overlaps(&r2));
        assert!(!r1.overlaps(&r3));

        let all = LockRange::all();
        assert!(all.overlaps(&r1));
        assert!(all.overlaps(&r3));
    }

    #[test]
    fn test_verifier() {
        let v1 = Verifier::generate();
        let v2 = Verifier::generate();
        assert_ne!(v1, v2);

        let v3 = Verifier::from_u64(12345);
        assert_eq!(v3.as_u64(), 12345);
    }

    #[test]
    fn test_client_id_generate() {
        let c1 = ClientId::generate();
        let c2 = ClientId::generate();
        assert_ne!(c1.id, c2.id);
    }

    #[test]
    fn test_session_id_generate() {
        let s1 = SessionId::generate();
        let s2 = SessionId::generate();
        assert_ne!(s1.id, s2.id);
    }

    #[test]
    fn test_dir_entry() {
        let entry = DirEntry::new(1, "test.txt".into())
            .with_attrs(NfsAttr::file(100, 1024, 0o644, 0, 0))
            .with_handle(FileHandle::new(1, 100, 1));

        assert_eq!(entry.name, "test.txt");
        assert!(entry.attrs.is_some());
        assert!(entry.fh.is_some());
    }

    #[test]
    fn test_fs_info_defaults() {
        let info = FsInfo::default();
        assert_eq!(info.rtmax, 1024 * 1024);
        assert_eq!(info.maxfilesize, u64::MAX);
    }

    #[test]
    fn test_fs_stat_defaults() {
        let stat = FsStat::default();
        assert!(stat.tbytes > 0);
        assert!(stat.fbytes <= stat.tbytes);
    }
}