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

//! ZPL (ZFS POSIX Layer) adapter for NFS.
//!
//! This module provides the bridge between the NFS server and the LCPFS
//! storage layer, implementing the `NfsFilesystem` trait by delegating
//! to ZPL operations.
//!
//! ## Architecture
//!
//! ```text
//! ┌──────────────────┐     ┌──────────────────┐     ┌──────────────────┐
//! │   NFS Server     │────▶│   ZplNfsAdapter  │────▶│       ZPL        │
//! │ (NfsFilesystem)  │     │  (implements     │     │ (actual storage) │
//! │                  │     │   NfsFilesystem) │     │                  │
//! └──────────────────┘     └──────────────────┘     └──────────────────┘
//! ```
//!
//! ## Type Conversions
//!
//! - `FileHandle` ↔ object_id (u64)
//! - `NfsAttr` ↔ `Znode`/`ZnodePhys`
//! - `FsError` → `NfsStatus`

use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use super::error::{NfsError, NfsResult, NfsStatus};
use super::ops::StableHow;
use super::server::{NfsFilesystem, RequestContext};
use super::types::{DirEntry, FileHandle, FileType, FsInfo, FsStat, NfsAttr, SetAttr, Verifier};
use crate::FsError;
use crate::storage::zpl::{
    S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFLNK, S_IFMT, S_IFREG, S_IFSOCK, ZPL, Znode, ZnodePhys,
};

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

/// Default dataset ID (ZPL is single-instance currently)
const DEFAULT_DATASET_ID: u64 = 1;

/// Root object ID in ZPL
const ROOT_OBJECT_ID: u64 = 2;

/// Default block size
const BLOCK_SIZE: u32 = 4096;

/// Maximum read/write size
const MAX_RW_SIZE: u32 = 1024 * 1024; // 1 MB

/// Maximum link count
const MAX_LINK: u32 = 65535;

// ═══════════════════════════════════════════════════════════════════════════════
// ERROR CONVERSION
// ═══════════════════════════════════════════════════════════════════════════════

/// Convert FsError to NfsStatus
fn fs_error_to_nfs_status(err: FsError) -> NfsStatus {
    match err {
        FsError::NotFound => NfsStatus::Noent,
        FsError::PathNotFound { .. } => NfsStatus::Noent,
        FsError::DiskFull { .. } => NfsStatus::Nospc,
        FsError::IoError { .. } => NfsStatus::Io,
        FsError::Corruption { .. } => NfsStatus::Io,
        FsError::ChecksumMismatch { .. } => NfsStatus::Io,
        FsError::EncryptionFailed => NfsStatus::Io,
        FsError::DecryptionFailed => NfsStatus::Io,
        FsError::CompressionFailed => NfsStatus::Io,
        FsError::DecompressionFailed => NfsStatus::Io,
        FsError::InvalidBlockPointer => NfsStatus::Io,
        FsError::PoolNotImported => NfsStatus::Serverfault,
        FsError::InvalidPoolConfig { .. } => NfsStatus::Serverfault,
        FsError::TxgError { .. } => NfsStatus::Io,
        FsError::ZapError { .. } => NfsStatus::Io,
        FsError::DatasetError { .. } => NfsStatus::Serverfault,
        FsError::DeviceTooSmall { .. } => NfsStatus::Nospc,
        FsError::AlreadyExists => NfsStatus::Exist,
        FsError::IsDirectory => NfsStatus::Isdir,
        FsError::IsFile => NfsStatus::Notdir,
        FsError::PermissionDenied => NfsStatus::Acces,
        FsError::ResourceBusy => NfsStatus::Locked,
        FsError::ReadOnly => NfsStatus::Rofs,
        FsError::InvalidArgument { .. } => NfsStatus::Inval,
        FsError::NotDirectory => NfsStatus::Notdir,
        FsError::BadFileDescriptor => NfsStatus::Badhandle,
        FsError::NotImplemented => NfsStatus::Notsupp,
        FsError::DirectoryNotEmpty => NfsStatus::Notempty,
        FsError::NoDevice => NfsStatus::Nxio,
        FsError::SecurityViolation { .. } => NfsStatus::Acces,
    }
}

/// Convert FsError to NfsError
fn fs_error_to_nfs(err: FsError) -> NfsError {
    NfsError::new(fs_error_to_nfs_status(err))
}

// ═══════════════════════════════════════════════════════════════════════════════
// TYPE CONVERSION
// ═══════════════════════════════════════════════════════════════════════════════

/// Extract FileType from mode bits
fn mode_to_file_type(mode: u64) -> FileType {
    match (mode as u32) & S_IFMT {
        S_IFREG => FileType::Regular,
        S_IFDIR => FileType::Directory,
        S_IFLNK => FileType::Symlink,
        S_IFBLK => FileType::Block,
        S_IFCHR => FileType::Character,
        S_IFIFO => FileType::Fifo,
        S_IFSOCK => FileType::Socket,
        _ => FileType::Regular, // Default to regular file
    }
}

/// Convert Znode to NfsAttr
fn znode_to_nfs_attr(znode: &Znode) -> NfsAttr {
    let phys = &znode.phys;
    let file_type = mode_to_file_type(phys.mode);

    NfsAttr {
        file_type,
        mode: (phys.mode & 0o7777) as u32,
        nlink: phys.links as u32,
        uid: phys.uid as u32,
        gid: phys.gid as u32,
        size: phys.size,
        used: phys.size.div_ceil(512) * 512, // Round up to 512-byte blocks
        rdev: phys.rdev,
        fsid: DEFAULT_DATASET_ID,
        fileid: znode.object_id,
        atime_sec: phys.atime[0],
        atime_nsec: phys.atime[1] as u32,
        mtime_sec: phys.mtime[0],
        mtime_nsec: phys.mtime[1] as u32,
        ctime_sec: phys.ctime[0],
        ctime_nsec: phys.ctime[1] as u32,
        blksize: BLOCK_SIZE,
        blocks: phys.size.div_ceil(512),
    }
}

/// Create a FileHandle from an object ID
fn object_id_to_handle(object_id: u64, generation: u64) -> FileHandle {
    FileHandle::new(DEFAULT_DATASET_ID, object_id, generation)
}

/// Extract object ID from FileHandle
fn handle_to_object_id(fh: &FileHandle) -> u64 {
    fh.object_id()
}

// ═══════════════════════════════════════════════════════════════════════════════
// ZPL NFS ADAPTER
// ═══════════════════════════════════════════════════════════════════════════════

/// Adapter that bridges NFS operations to ZPL storage.
///
/// This struct implements `NfsFilesystem` by delegating all operations
/// to the global ZPL instance, performing necessary type conversions.
///
/// # Example
///
/// ```rust,ignore
/// use lcpfs::nfs::{NfsServer, ZplNfsAdapter};
///
/// let adapter = ZplNfsAdapter::new();
/// let server = NfsServer::new(adapter);
/// ```
pub struct ZplNfsAdapter;

impl ZplNfsAdapter {
    /// Create a new ZPL NFS adapter.
    pub fn new() -> Self {
        Self
    }
}

impl Default for ZplNfsAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl NfsFilesystem for ZplNfsAdapter {
    fn lookup(&self, dir_fh: &FileHandle, name: &str) -> NfsResult<FileHandle> {
        let dir_id = handle_to_object_id(dir_fh);

        let zpl = ZPL.lock();
        let child_id = zpl.lookup(dir_id, name).map_err(fs_error_to_nfs)?;

        // Get generation from znode
        let generation = zpl
            .get_znode(child_id)
            .map(|z| z.phys.generation)
            .unwrap_or(0);

        Ok(object_id_to_handle(child_id, generation))
    }

    fn parent(&self, fh: &FileHandle) -> NfsResult<FileHandle> {
        let object_id = handle_to_object_id(fh);

        let zpl = ZPL.lock();
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Stale))?;

        let parent_id = znode.phys.parent;
        let parent_gen = zpl
            .get_znode(parent_id)
            .map(|z| z.phys.generation)
            .unwrap_or(0);

        Ok(object_id_to_handle(parent_id, parent_gen))
    }

    fn getattr(&self, fh: &FileHandle) -> NfsResult<NfsAttr> {
        let object_id = handle_to_object_id(fh);

        let zpl = ZPL.lock();
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Stale))?;

        Ok(znode_to_nfs_attr(znode))
    }

    fn setattr(
        &self,
        fh: &FileHandle,
        attrs: &SetAttr,
        _ctx: &RequestContext,
    ) -> NfsResult<NfsAttr> {
        let object_id = handle_to_object_id(fh);

        let mut zpl = ZPL.lock();

        // Apply attribute changes
        if let Some(mode) = attrs.mode {
            zpl.setattr(object_id, Some(mode), None, None)
                .map_err(fs_error_to_nfs)?;
        }
        if let Some(uid) = attrs.uid {
            zpl.setattr(object_id, None, Some(uid), None)
                .map_err(fs_error_to_nfs)?;
        }
        if let Some(gid) = attrs.gid {
            zpl.setattr(object_id, None, None, Some(gid))
                .map_err(fs_error_to_nfs)?;
        }
        if let Some(size) = attrs.size {
            // Handle truncate
            // First open a handle, then truncate, then close
            let handle = zpl.open(object_id, 0o2).map_err(fs_error_to_nfs)?; // O_RDWR
            zpl.truncate(handle, size).map_err(fs_error_to_nfs)?;
            let _ = zpl.close(handle);
        }

        // Get updated attributes
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Stale))?;

        Ok(znode_to_nfs_attr(znode))
    }

    fn read(&self, fh: &FileHandle, offset: u64, count: u32) -> NfsResult<(Vec<u8>, bool)> {
        let object_id = handle_to_object_id(fh);

        let mut zpl = ZPL.lock();

        // Open file, read, close
        let handle = zpl.open(object_id, 0).map_err(fs_error_to_nfs)?; // O_RDONLY

        // Seek to offset (SEEK_SET = 0)
        zpl.seek(handle, offset as i64, 0)
            .map_err(fs_error_to_nfs)?;

        // Read data
        let mut buf = vec![0u8; count as usize];
        let bytes_read = zpl.read(handle, &mut buf).map_err(fs_error_to_nfs)?;
        buf.truncate(bytes_read);

        let _ = zpl.close(handle);

        // Check if EOF
        let znode = zpl.get_znode(object_id);
        let eof = match znode {
            Some(z) => offset + bytes_read as u64 >= z.phys.size,
            None => true,
        };

        Ok((buf, eof))
    }

    fn write(
        &self,
        fh: &FileHandle,
        offset: u64,
        data: &[u8],
        stable: StableHow,
    ) -> NfsResult<(u32, StableHow)> {
        let object_id = handle_to_object_id(fh);

        let mut zpl = ZPL.lock();

        // Open file, write, close
        let handle = zpl.open(object_id, 0o1).map_err(fs_error_to_nfs)?; // O_WRONLY

        // Seek to offset (SEEK_SET = 0)
        zpl.seek(handle, offset as i64, 0)
            .map_err(fs_error_to_nfs)?;

        // Write data
        let bytes_written = zpl.write(handle, data).map_err(fs_error_to_nfs)?;

        // Sync if requested
        let committed = match stable {
            StableHow::Unstable => {
                let _ = zpl.close(handle);
                StableHow::Unstable
            }
            StableHow::DataSync | StableHow::FileSync => {
                zpl.fsync(handle).map_err(fs_error_to_nfs)?;
                let _ = zpl.close(handle);
                StableHow::FileSync
            }
        };

        Ok((bytes_written as u32, committed))
    }

    fn readdir(
        &self,
        fh: &FileHandle,
        cookie: u64,
        count: u32,
    ) -> NfsResult<(Vec<DirEntry>, bool)> {
        let object_id = handle_to_object_id(fh);

        let zpl = ZPL.lock();

        // Get directory entries from ZPL
        let entries = zpl.readdir(object_id).map_err(fs_error_to_nfs)?;

        // Convert to NFS DirEntry format
        let mut nfs_entries = Vec::new();
        let mut current_cookie: u64 = 0;
        let mut bytes_used: u32 = 0;

        for entry in entries {
            current_cookie += 1;

            // Skip entries before cookie
            if current_cookie <= cookie {
                continue;
            }

            // Estimate entry size (name + overhead)
            let entry_size = 32 + entry.name.len() as u32;
            if bytes_used + entry_size > count {
                // Would exceed count, stop here
                return Ok((nfs_entries, false));
            }

            // Get attributes for entry if possible
            let child_id = entry.object_id;
            let (attrs, entry_fh) = {
                let child_znode = zpl.get_znode(child_id);
                match child_znode {
                    Some(z) => {
                        let attr = znode_to_nfs_attr(z);
                        let handle = object_id_to_handle(child_id, z.phys.generation);
                        (Some(attr), Some(handle))
                    }
                    None => (None, None),
                }
            };

            nfs_entries.push(DirEntry {
                cookie: current_cookie,
                name: entry.name,
                attrs,
                fh: entry_fh,
            });

            bytes_used += entry_size;
        }

        // If we got here, we've consumed all entries
        Ok((nfs_entries, true))
    }

    fn create(
        &self,
        dir_fh: &FileHandle,
        name: &str,
        attrs: &SetAttr,
        _ctx: &RequestContext,
    ) -> NfsResult<(FileHandle, NfsAttr)> {
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // Determine mode and ownership
        let mode = attrs.mode.unwrap_or(0o644);
        let uid = attrs.uid.unwrap_or(0);
        let gid = attrs.gid.unwrap_or(0);

        // Create file with ownership
        let object_id = zpl
            .create(dir_id, name, mode, uid, gid)
            .map_err(fs_error_to_nfs)?;

        // Get the created znode
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Serverfault))?;

        let nfs_attr = znode_to_nfs_attr(znode);
        let handle = object_id_to_handle(object_id, znode.phys.generation);

        Ok((handle, nfs_attr))
    }

    fn mkdir(
        &self,
        dir_fh: &FileHandle,
        name: &str,
        attrs: &SetAttr,
        _ctx: &RequestContext,
    ) -> NfsResult<(FileHandle, NfsAttr)> {
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // Determine mode and ownership
        let mode = attrs.mode.unwrap_or(0o755);
        let uid = attrs.uid.unwrap_or(0);
        let gid = attrs.gid.unwrap_or(0);

        // Create directory with ownership
        let object_id = zpl
            .mkdir(dir_id, name, mode, uid, gid)
            .map_err(fs_error_to_nfs)?;

        // Get the created znode
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Serverfault))?;

        let nfs_attr = znode_to_nfs_attr(znode);
        let handle = object_id_to_handle(object_id, znode.phys.generation);

        Ok((handle, nfs_attr))
    }

    fn remove(&self, dir_fh: &FileHandle, name: &str) -> NfsResult<()> {
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // First lookup to get the object
        let object_id = zpl.lookup(dir_id, name).map_err(fs_error_to_nfs)?;

        // Check if it's a directory
        if let Some(znode) = zpl.get_znode(object_id) {
            if znode.is_dir() {
                return Err(NfsError::from(NfsStatus::Isdir));
            }
        }

        // Remove the file
        zpl.unlink(dir_id, name).map_err(fs_error_to_nfs)?;

        Ok(())
    }

    fn rmdir(&self, dir_fh: &FileHandle, name: &str) -> NfsResult<()> {
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // First lookup to get the object
        let object_id = zpl.lookup(dir_id, name).map_err(fs_error_to_nfs)?;

        // Check if it's actually a directory
        if let Some(znode) = zpl.get_znode(object_id) {
            if !znode.is_dir() {
                return Err(NfsError::from(NfsStatus::Notdir));
            }
        }

        // Remove the directory
        zpl.rmdir(dir_id, name).map_err(fs_error_to_nfs)?;

        Ok(())
    }

    fn rename(
        &self,
        from_dir: &FileHandle,
        from_name: &str,
        to_dir: &FileHandle,
        to_name: &str,
    ) -> NfsResult<()> {
        let from_dir_id = handle_to_object_id(from_dir);
        let to_dir_id = handle_to_object_id(to_dir);

        let mut zpl = ZPL.lock();

        zpl.rename(from_dir_id, from_name, to_dir_id, to_name)
            .map_err(fs_error_to_nfs)?;

        Ok(())
    }

    fn symlink(
        &self,
        dir_fh: &FileHandle,
        name: &str,
        target: &str,
        _attrs: &SetAttr,
        _ctx: &RequestContext,
    ) -> NfsResult<(FileHandle, NfsAttr)> {
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // Create symlink (use uid/gid 0 by default)
        let object_id = zpl
            .symlink(dir_id, name, target, 0, 0)
            .map_err(fs_error_to_nfs)?;

        // Get the created znode
        let znode = zpl
            .get_znode(object_id)
            .ok_or(NfsError::from(NfsStatus::Serverfault))?;

        let nfs_attr = znode_to_nfs_attr(znode);
        let handle = object_id_to_handle(object_id, znode.phys.generation);

        Ok((handle, nfs_attr))
    }

    fn readlink(&self, fh: &FileHandle) -> NfsResult<String> {
        let object_id = handle_to_object_id(fh);

        let zpl = ZPL.lock();

        let target = zpl.readlink(object_id).map_err(fs_error_to_nfs)?;

        Ok(target)
    }

    fn link(&self, fh: &FileHandle, dir_fh: &FileHandle, name: &str) -> NfsResult<()> {
        let object_id = handle_to_object_id(fh);
        let dir_id = handle_to_object_id(dir_fh);

        let mut zpl = ZPL.lock();

        // Create hard link
        zpl.link_create(dir_id, name, object_id)
            .map_err(fs_error_to_nfs)?;

        Ok(())
    }

    fn commit(&self, fh: &FileHandle, _offset: u64, _count: u32) -> NfsResult<Verifier> {
        let object_id = handle_to_object_id(fh);

        let mut zpl = ZPL.lock();

        // Sync the transaction group (device 0)
        let _ = zpl.txg_sync(0);

        // Get mtime as verifier
        let verifier = if let Some(znode) = zpl.get_znode(object_id) {
            let mtime = znode.phys.mtime[0];
            Verifier::from_u64(mtime)
        } else {
            Verifier::from_u64(0)
        };

        Ok(verifier)
    }

    fn fsinfo(&self, _fh: &FileHandle) -> NfsResult<FsInfo> {
        Ok(FsInfo {
            rtmax: MAX_RW_SIZE,
            rtpref: MAX_RW_SIZE,
            rtmult: BLOCK_SIZE,
            wtmax: MAX_RW_SIZE,
            wtpref: MAX_RW_SIZE,
            wtmult: BLOCK_SIZE,
            dtpref: BLOCK_SIZE,
            maxfilesize: u64::MAX,
            time_delta_sec: 0,
            time_delta_nsec: 1,
            properties: 0x001B, // FSF3_LINK | FSF3_SYMLINK | FSF3_HOMOGENEOUS | FSF3_CANSETTIME
        })
    }

    fn fsstat(&self, _fh: &FileHandle) -> NfsResult<FsStat> {
        let zpl = ZPL.lock();

        let used = zpl.used_bytes();
        let quota = zpl.quota();

        // If no quota, assume 1TB total
        let total = if quota > 0 {
            quota
        } else {
            1024 * 1024 * 1024 * 1024
        };
        let free = total.saturating_sub(used);

        // Estimate file counts (we don't track this exactly)
        let files_total = total / BLOCK_SIZE as u64;
        let files_free = free / BLOCK_SIZE as u64;

        Ok(FsStat {
            tbytes: total,
            fbytes: free,
            abytes: free, // Available = free for now
            tfiles: files_total,
            ffiles: files_free,
            afiles: files_free,
            invarsec: 0, // No invariant seconds
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// GLOBAL NFS SERVER INSTANCE
// ═══════════════════════════════════════════════════════════════════════════════

use lazy_static::lazy_static;
use spin::Mutex;

use super::server::NfsServer;

lazy_static! {
    /// Global NFS server instance backed by ZPL.
    pub static ref NFS_SERVER: Mutex<NfsServer<ZplNfsAdapter>> =
        Mutex::new(NfsServer::new(ZplNfsAdapter::new()));
}

/// Get the root file handle for the NFS server.
pub fn get_root_handle() -> FileHandle {
    // Get root generation from ZPL
    let generation = {
        let zpl = ZPL.lock();
        zpl.get_znode(ROOT_OBJECT_ID)
            .map(|z| z.phys.generation)
            .unwrap_or(0)
    };

    FileHandle::new(DEFAULT_DATASET_ID, ROOT_OBJECT_ID, generation)
}

/// Process an NFS COMPOUND request using the global server.
pub fn process_request(
    request: super::ops::CompoundRequest,
    ctx: &mut RequestContext,
) -> super::ops::CompoundResponse {
    let server = NFS_SERVER.lock();
    server.process_compound(request, ctx)
}

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

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

    #[test]
    fn test_error_conversion() {
        assert_eq!(fs_error_to_nfs_status(FsError::NotFound), NfsStatus::Noent);
        assert_eq!(
            fs_error_to_nfs_status(FsError::AlreadyExists),
            NfsStatus::Exist
        );
        assert_eq!(
            fs_error_to_nfs_status(FsError::IsDirectory),
            NfsStatus::Isdir
        );
        assert_eq!(
            fs_error_to_nfs_status(FsError::NotDirectory),
            NfsStatus::Notdir
        );
        assert_eq!(
            fs_error_to_nfs_status(FsError::PermissionDenied),
            NfsStatus::Acces
        );
        assert_eq!(fs_error_to_nfs_status(FsError::ReadOnly), NfsStatus::Rofs);
        assert_eq!(
            fs_error_to_nfs_status(FsError::DirectoryNotEmpty),
            NfsStatus::Notempty
        );
    }

    #[test]
    fn test_mode_to_file_type() {
        assert_eq!(mode_to_file_type(S_IFREG as u64), FileType::Regular);
        assert_eq!(mode_to_file_type(S_IFDIR as u64), FileType::Directory);
        assert_eq!(mode_to_file_type(S_IFLNK as u64), FileType::Symlink);
        assert_eq!(mode_to_file_type(S_IFBLK as u64), FileType::Block);
        assert_eq!(mode_to_file_type(S_IFCHR as u64), FileType::Character);
        assert_eq!(mode_to_file_type(S_IFIFO as u64), FileType::Fifo);
        assert_eq!(mode_to_file_type(S_IFSOCK as u64), FileType::Socket);
    }

    #[test]
    fn test_file_handle_conversion() {
        let handle = object_id_to_handle(12345, 1);
        assert_eq!(handle.dataset_id(), DEFAULT_DATASET_ID);
        assert_eq!(handle.object_id(), 12345);
        assert_eq!(handle.generation(), 1);

        let object_id = handle_to_object_id(&handle);
        assert_eq!(object_id, 12345);
    }

    #[test]
    fn test_adapter_creation() {
        let adapter = ZplNfsAdapter::new();
        let _ = adapter; // Just verify it compiles

        let default_adapter: ZplNfsAdapter = Default::default();
        let _ = default_adapter;
    }

    #[test]
    fn test_root_handle() {
        let handle = get_root_handle();
        assert_eq!(handle.dataset_id(), DEFAULT_DATASET_ID);
        assert_eq!(handle.object_id(), ROOT_OBJECT_ID);
    }

    #[test]
    fn test_fsinfo() {
        let adapter = ZplNfsAdapter::new();
        let root = get_root_handle();

        let info = adapter.fsinfo(&root).unwrap();
        assert_eq!(info.rtmax, MAX_RW_SIZE);
        assert_eq!(info.wtmax, MAX_RW_SIZE);
        assert!(info.maxfilesize > 0);
    }

    #[test]
    fn test_fsstat() {
        let adapter = ZplNfsAdapter::new();
        let root = get_root_handle();

        let stat = adapter.fsstat(&root).unwrap();
        assert!(stat.tbytes > 0);
        // Free bytes should be <= total bytes
        assert!(stat.fbytes <= stat.tbytes);
    }

    #[test]
    fn test_getattr_root() {
        let adapter = ZplNfsAdapter::new();
        let root = get_root_handle();

        // This may fail if ZPL isn't initialized, but the code path is tested
        let result = adapter.getattr(&root);
        // Root should exist or return stale
        assert!(result.is_ok() || result.err().unwrap().status == NfsStatus::Stale);
    }
}