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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! NFS error types and status codes.
//!
//! This module defines NFSv4 error status codes as defined in RFC 7530.

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

// ═══════════════════════════════════════════════════════════════════════════════
// NFS STATUS CODES
// ═══════════════════════════════════════════════════════════════════════════════

/// NFSv4 status codes (RFC 7530).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum NfsStatus {
    /// No error.
    Ok = 0,
    /// Permission denied.
    Perm = 1,
    /// No such file or directory.
    Noent = 2,
    /// I/O error.
    Io = 5,
    /// No such device or address.
    Nxio = 6,
    /// Permission denied.
    Acces = 13,
    /// File exists.
    Exist = 17,
    /// Cross-device link.
    Xdev = 18,
    /// Not a directory.
    Notdir = 20,
    /// Is a directory.
    Isdir = 21,
    /// Invalid argument.
    Inval = 22,
    /// File too large.
    Fbig = 27,
    /// No space left on device.
    Nospc = 28,
    /// Read-only file system.
    Rofs = 30,
    /// Too many hard links.
    Mlink = 31,
    /// File name too long.
    Nametoolong = 63,
    /// Directory not empty.
    Notempty = 66,
    /// Disk quota exceeded.
    Dquot = 69,
    /// Stale file handle.
    Stale = 70,
    /// Remote I/O error.
    Remote = 71,

    // NFSv4 specific errors
    /// Bad file handle.
    Badhandle = 10001,
    /// Update synchronization mismatch.
    NotSync = 10002,
    /// READDIR cookie is stale.
    BadCookie = 10003,
    /// Operation not supported.
    Notsupp = 10004,
    /// Buffer or request is too small.
    Toosmall = 10005,
    /// An error occurred on the server which does not map to any RFC.
    Serverfault = 10006,
    /// Type not supported.
    Badtype = 10007,
    /// A delay occurred during the processing.
    Delay = 10008,
    /// The file is the same as the source.
    Same = 10009,
    /// Lock denied.
    Denied = 10010,
    /// The server has run out of a resource.
    Resource = 10011,
    /// An XDR decode error.
    Badxdr = 10036,
    /// Lock held by another.
    Locked = 10012,
    /// Lock grace period in effect.
    Grace = 10013,
    /// File lock range not supported.
    FhExpired = 10014,
    /// Share reservation conflict.
    ShareDenied = 10015,
    /// Wrong security flavor.
    Wrongsec = 10016,
    /// Client ID in use.
    ClidInuse = 10017,
    /// Operation moved to a different server.
    Moved = 10019,
    /// No matching grant for LOCKT.
    NoGrace = 10020,
    /// Reclaim outside of grace period.
    ReclaimBad = 10021,
    /// Reclaim conflict.
    ReclaimConflict = 10022,
    /// Request too big.
    ReqTooBig = 10023,
    /// Bad sequence number.
    BadSeqid = 10026,
    /// Not the same client.
    NotSame = 10027,
    /// Lock range is not supported.
    LockRange = 10028,
    /// Symlink too many levels.
    Symlink = 10029,
    /// Lease expired.
    Expired = 10035,
    /// Lock was not contested.
    LockNotsupp = 10043,
    /// Old state ID.
    OldStateid = 10024,
    /// Bad state ID.
    BadStateid = 10025,
    /// Admin revoked the state.
    AdminRevoked = 10047,
    /// Operation not in session.
    OpNotInSession = 10071,

    // NFSv4.1 specific
    /// Client must use BIND_CONN_TO_SESSION.
    ConnNotBoundToSession = 10055,
    /// Wrong credential.
    WrongCred = 10082,
    /// Wrong type.
    WrongType = 10083,
    /// Dir delegation unavailable.
    DirDelegUnavail = 10084,
    /// Reject.
    Reject = 10085,
    /// Return conflict.
    Returnconflict = 10086,
    /// Server ran out of deleg.
    DelegAlreadyWanted = 10087,
    /// Sequence position is bad.
    BadHighSlot = 10077,
    /// Retry.
    Retry = 10049,
    /// Server is null.
    SeqMisordered = 10063,
    /// Sequence false retry.
    SeqFalseRetry = 10076,

    /// No file handle.
    Nofilehandle = 10040,
    /// Bad session (NFSv4.1).
    BadSession = 10052,

    /// Unknown error.
    Unknown = 0xFFFFFFFF,
}

impl NfsStatus {
    /// Convert from raw u32.
    pub fn from_u32(v: u32) -> Self {
        match v {
            0 => Self::Ok,
            1 => Self::Perm,
            2 => Self::Noent,
            5 => Self::Io,
            6 => Self::Nxio,
            13 => Self::Acces,
            17 => Self::Exist,
            18 => Self::Xdev,
            20 => Self::Notdir,
            21 => Self::Isdir,
            22 => Self::Inval,
            27 => Self::Fbig,
            28 => Self::Nospc,
            30 => Self::Rofs,
            31 => Self::Mlink,
            63 => Self::Nametoolong,
            66 => Self::Notempty,
            69 => Self::Dquot,
            70 => Self::Stale,
            71 => Self::Remote,
            10001 => Self::Badhandle,
            10002 => Self::NotSync,
            10003 => Self::BadCookie,
            10004 => Self::Notsupp,
            10005 => Self::Toosmall,
            10006 => Self::Serverfault,
            10007 => Self::Badtype,
            10008 => Self::Delay,
            10009 => Self::Same,
            10010 => Self::Denied,
            10011 => Self::Resource,
            10012 => Self::Locked,
            10013 => Self::Grace,
            10014 => Self::FhExpired,
            10015 => Self::ShareDenied,
            10016 => Self::Wrongsec,
            10017 => Self::ClidInuse,
            10019 => Self::Moved,
            10020 => Self::NoGrace,
            10021 => Self::ReclaimBad,
            10022 => Self::ReclaimConflict,
            10023 => Self::ReqTooBig,
            10024 => Self::OldStateid,
            10025 => Self::BadStateid,
            10026 => Self::BadSeqid,
            10027 => Self::NotSame,
            10028 => Self::LockRange,
            10029 => Self::Symlink,
            10035 => Self::Expired,
            10036 => Self::Badxdr,
            10043 => Self::LockNotsupp,
            10047 => Self::AdminRevoked,
            10049 => Self::Retry,
            10055 => Self::ConnNotBoundToSession,
            10063 => Self::SeqMisordered,
            10071 => Self::OpNotInSession,
            10076 => Self::SeqFalseRetry,
            10077 => Self::BadHighSlot,
            10082 => Self::WrongCred,
            10083 => Self::WrongType,
            10084 => Self::DirDelegUnavail,
            10085 => Self::Reject,
            10086 => Self::Returnconflict,
            10087 => Self::DelegAlreadyWanted,
            10040 => Self::Nofilehandle,
            10052 => Self::BadSession,
            _ => Self::Unknown,
        }
    }

    /// Get the numeric status code.
    pub fn code(&self) -> u32 {
        *self as u32
    }

    /// Check if this is a success status.
    pub fn is_ok(&self) -> bool {
        matches!(self, Self::Ok)
    }

    /// Check if this is an error status.
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /// Get a human-readable message for the status.
    pub fn message(&self) -> &'static str {
        match self {
            Self::Ok => "No error",
            Self::Perm => "Permission denied",
            Self::Noent => "No such file or directory",
            Self::Io => "I/O error",
            Self::Nxio => "No such device or address",
            Self::Acces => "Permission denied",
            Self::Exist => "File exists",
            Self::Xdev => "Cross-device link",
            Self::Notdir => "Not a directory",
            Self::Isdir => "Is a directory",
            Self::Inval => "Invalid argument",
            Self::Fbig => "File too large",
            Self::Nospc => "No space left on device",
            Self::Rofs => "Read-only file system",
            Self::Mlink => "Too many hard links",
            Self::Nametoolong => "File name too long",
            Self::Notempty => "Directory not empty",
            Self::Dquot => "Disk quota exceeded",
            Self::Stale => "Stale file handle",
            Self::Remote => "Remote I/O error",
            Self::Badhandle => "Bad file handle",
            Self::NotSync => "Update synchronization mismatch",
            Self::BadCookie => "READDIR cookie is stale",
            Self::Notsupp => "Operation not supported",
            Self::Toosmall => "Buffer or request is too small",
            Self::Serverfault => "Server fault",
            Self::Badtype => "Type not supported",
            Self::Delay => "Delay occurred during processing",
            Self::Same => "File is the same as source",
            Self::Denied => "Lock denied",
            Self::Resource => "Server ran out of resources",
            Self::Badxdr => "XDR decode error",
            Self::Locked => "Lock held by another",
            Self::Grace => "Lock grace period in effect",
            Self::FhExpired => "File handle expired",
            Self::ShareDenied => "Share reservation conflict",
            Self::Wrongsec => "Wrong security flavor",
            Self::ClidInuse => "Client ID in use",
            Self::Moved => "Operation moved to different server",
            Self::NoGrace => "No matching grant for LOCKT",
            Self::ReclaimBad => "Reclaim outside of grace period",
            Self::ReclaimConflict => "Reclaim conflict",
            Self::ReqTooBig => "Request too big",
            Self::BadSeqid => "Bad sequence number",
            Self::NotSame => "Not the same client",
            Self::LockRange => "Lock range not supported",
            Self::Symlink => "Symlink too many levels",
            Self::Expired => "Lease expired",
            Self::LockNotsupp => "Lock not supported",
            Self::OldStateid => "Old state ID",
            Self::BadStateid => "Bad state ID",
            Self::AdminRevoked => "Admin revoked the state",
            Self::OpNotInSession => "Operation not in session",
            Self::ConnNotBoundToSession => "Connection not bound to session",
            Self::WrongCred => "Wrong credential",
            Self::WrongType => "Wrong type",
            Self::DirDelegUnavail => "Dir delegation unavailable",
            Self::Reject => "Reject",
            Self::Returnconflict => "Return conflict",
            Self::DelegAlreadyWanted => "Delegation already wanted",
            Self::BadHighSlot => "Bad high slot",
            Self::Retry => "Retry",
            Self::SeqMisordered => "Sequence misordered",
            Self::SeqFalseRetry => "Sequence false retry",
            Self::Nofilehandle => "No file handle",
            Self::BadSession => "Bad session",
            Self::Unknown => "Unknown error",
        }
    }
}

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

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

/// NFS error with status and optional message.
#[derive(Debug, Clone)]
pub struct NfsError {
    /// Status code.
    pub status: NfsStatus,
    /// Optional detail message.
    pub message: Option<String>,
}

impl NfsError {
    /// Create a new error.
    pub fn new(status: NfsStatus) -> Self {
        Self {
            status,
            message: None,
        }
    }

    /// Create an error with a message.
    pub fn with_message(status: NfsStatus, msg: impl Into<String>) -> Self {
        Self {
            status,
            message: Some(msg.into()),
        }
    }

    // Convenience constructors for common errors

    /// Permission denied.
    pub fn perm() -> Self {
        Self::new(NfsStatus::Perm)
    }

    /// No such file or directory.
    pub fn noent() -> Self {
        Self::new(NfsStatus::Noent)
    }

    /// I/O error.
    pub fn io() -> Self {
        Self::new(NfsStatus::Io)
    }

    /// Access denied.
    pub fn access() -> Self {
        Self::new(NfsStatus::Acces)
    }

    /// File exists.
    pub fn exist() -> Self {
        Self::new(NfsStatus::Exist)
    }

    /// Not a directory.
    pub fn notdir() -> Self {
        Self::new(NfsStatus::Notdir)
    }

    /// Is a directory.
    pub fn isdir() -> Self {
        Self::new(NfsStatus::Isdir)
    }

    /// Invalid argument.
    pub fn inval() -> Self {
        Self::new(NfsStatus::Inval)
    }

    /// No space left.
    pub fn nospc() -> Self {
        Self::new(NfsStatus::Nospc)
    }

    /// Read-only file system.
    pub fn rofs() -> Self {
        Self::new(NfsStatus::Rofs)
    }

    /// Name too long.
    pub fn nametoolong() -> Self {
        Self::new(NfsStatus::Nametoolong)
    }

    /// Directory not empty.
    pub fn notempty() -> Self {
        Self::new(NfsStatus::Notempty)
    }

    /// Stale file handle.
    pub fn stale() -> Self {
        Self::new(NfsStatus::Stale)
    }

    /// Bad file handle.
    pub fn badhandle() -> Self {
        Self::new(NfsStatus::Badhandle)
    }

    /// Operation not supported.
    pub fn notsupp() -> Self {
        Self::new(NfsStatus::Notsupp)
    }

    /// Server fault.
    pub fn serverfault() -> Self {
        Self::new(NfsStatus::Serverfault)
    }

    /// Bad XDR.
    pub fn badxdr() -> Self {
        Self::new(NfsStatus::Badxdr)
    }

    /// Locked.
    pub fn locked() -> Self {
        Self::new(NfsStatus::Locked)
    }

    /// Bad state ID.
    pub fn bad_stateid() -> Self {
        Self::new(NfsStatus::BadStateid)
    }

    /// Get the status code.
    pub fn code(&self) -> u32 {
        self.status.code()
    }
}

impl fmt::Display for NfsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref msg) = self.message {
            write!(
                f,
                "NFS error {}: {} ({})",
                self.status.code(),
                self.status.message(),
                msg
            )
        } else {
            write!(
                f,
                "NFS error {}: {}",
                self.status.code(),
                self.status.message()
            )
        }
    }
}

impl From<NfsStatus> for NfsError {
    fn from(status: NfsStatus) -> Self {
        Self::new(status)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// RESULT TYPE
// ═══════════════════════════════════════════════════════════════════════════════

/// Result type for NFS operations.
pub type NfsResult<T> = core::result::Result<T, NfsError>;

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

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

    #[test]
    fn test_nfs_status_from_u32() {
        assert_eq!(NfsStatus::from_u32(0), NfsStatus::Ok);
        assert_eq!(NfsStatus::from_u32(2), NfsStatus::Noent);
        assert_eq!(NfsStatus::from_u32(10001), NfsStatus::Badhandle);
        assert_eq!(NfsStatus::from_u32(99999), NfsStatus::Unknown);
    }

    #[test]
    fn test_nfs_status_code() {
        assert_eq!(NfsStatus::Ok.code(), 0);
        assert_eq!(NfsStatus::Noent.code(), 2);
        assert_eq!(NfsStatus::Badhandle.code(), 10001);
    }

    #[test]
    fn test_nfs_status_is_ok() {
        assert!(NfsStatus::Ok.is_ok());
        assert!(!NfsStatus::Noent.is_ok());
        assert!(NfsStatus::Noent.is_err());
    }

    #[test]
    fn test_nfs_status_message() {
        assert_eq!(NfsStatus::Ok.message(), "No error");
        assert_eq!(NfsStatus::Noent.message(), "No such file or directory");
    }

    #[test]
    fn test_nfs_error_creation() {
        let err = NfsError::new(NfsStatus::Noent);
        assert_eq!(err.status, NfsStatus::Noent);
        assert!(err.message.is_none());

        let err2 = NfsError::with_message(NfsStatus::Io, "disk failure");
        assert_eq!(err2.status, NfsStatus::Io);
        assert_eq!(err2.message, Some("disk failure".into()));
    }

    #[test]
    fn test_nfs_error_convenience() {
        assert_eq!(NfsError::noent().status, NfsStatus::Noent);
        assert_eq!(NfsError::stale().status, NfsStatus::Stale);
        assert_eq!(NfsError::inval().status, NfsStatus::Inval);
    }

    #[test]
    fn test_nfs_error_from_status() {
        let err: NfsError = NfsStatus::Perm.into();
        assert_eq!(err.status, NfsStatus::Perm);
    }

    #[test]
    fn test_nfs_error_display() {
        let err = NfsError::new(NfsStatus::Noent);
        let msg = alloc::format!("{}", err);
        assert!(msg.contains("No such file or directory"));

        let err2 = NfsError::with_message(NfsStatus::Io, "disk read failed");
        let msg2 = alloc::format!("{}", err2);
        assert!(msg2.contains("disk read failed"));
    }
}