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
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0
//
// Computational Storage Integration
// Offload filesystem operations to computational storage devices.

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;

/// Computational storage operation types
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CompStorOp {
    /// Checksum calculation
    Checksum,
    /// Compression (LZ4)
    Compress,
    /// Decompression
    Decompress,
    /// Deduplication hash
    DedupHash,
    /// Pattern scan (e.g., for scrubbing)
    PatternScan,
    /// Encryption
    Encrypt,
    /// Decryption
    Decrypt,
}

impl CompStorOp {
    /// Get operation name
    pub fn name(&self) -> &'static str {
        match self {
            CompStorOp::Checksum => "checksum",
            CompStorOp::Compress => "compress",
            CompStorOp::Decompress => "decompress",
            CompStorOp::DedupHash => "dedup_hash",
            CompStorOp::PatternScan => "pattern_scan",
            CompStorOp::Encrypt => "encrypt",
            CompStorOp::Decrypt => "decrypt",
        }
    }

    /// Estimate CPU cost (relative scale, higher = more expensive)
    pub fn cpu_cost(&self) -> u64 {
        match self {
            CompStorOp::Checksum => 10,
            CompStorOp::Compress => 100,
            CompStorOp::Decompress => 50,
            CompStorOp::DedupHash => 20,
            CompStorOp::PatternScan => 30,
            CompStorOp::Encrypt => 80,
            CompStorOp::Decrypt => 80,
        }
    }
}

/// Computational storage device capabilities
#[derive(Debug, Clone)]
pub struct CompStorCapabilities {
    /// Device ID
    pub device_id: u64,
    /// Device name
    pub device_name: &'static str,
    /// Supported operations
    pub supported_ops: Vec<CompStorOp>,
    /// Maximum command queue depth
    pub max_queue_depth: usize,
    /// Computation throughput (ops/sec)
    pub throughput_ops_sec: u64,
}

impl CompStorCapabilities {
    /// Create new capabilities descriptor
    pub fn new(device_id: u64, device_name: &'static str) -> Self {
        Self {
            device_id,
            device_name,
            supported_ops: Vec::new(),
            max_queue_depth: 32,
            throughput_ops_sec: 100_000,
        }
    }

    /// Add supported operation
    pub fn add_support(&mut self, op: CompStorOp) {
        if !self.supported_ops.contains(&op) {
            self.supported_ops.push(op);
        }
    }

    /// Check if operation is supported
    pub fn supports(&self, op: CompStorOp) -> bool {
        self.supported_ops.contains(&op)
    }
}

/// Computational storage command
#[derive(Debug, Clone)]
pub struct CompStorCommand {
    /// Command ID
    pub cmd_id: u64,
    /// Operation type
    pub operation: CompStorOp,
    /// Input data LBA (Logical Block Address)
    pub input_lba: u64,
    /// Input size in bytes
    pub input_size: u64,
    /// Output data LBA
    pub output_lba: u64,
    /// Command status
    pub status: CompStorStatus,
}

/// Command execution status
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompStorStatus {
    /// Queued, waiting to execute
    Queued,
    /// Currently executing
    Executing,
    /// Completed successfully
    Completed,
    /// Failed
    Failed,
    /// Offload not supported, fell back to CPU
    FallbackCpu,
}

/// Computational storage statistics
#[derive(Debug, Clone, Default)]
pub struct CompStorStats {
    /// Total commands offloaded
    pub total_offloaded: u64,
    /// Commands completed on device
    pub device_completed: u64,
    /// Commands that fell back to CPU
    pub cpu_fallback: u64,
    /// Commands failed
    pub failed: u64,
    /// Total CPU cycles saved (estimate)
    pub cpu_cycles_saved: u64,
}

lazy_static! {
    /// Global computational storage manager
    static ref COMPSTOR_MANAGER: Mutex<CompStorManager> = Mutex::new(CompStorManager::new());
}

/// Computational storage manager
pub struct CompStorManager {
    /// Registered devices
    devices: BTreeMap<u64, CompStorCapabilities>,
    /// Command queue
    commands: BTreeMap<u64, CompStorCommand>,
    /// Next command ID
    next_cmd_id: u64,
    /// Statistics per operation
    stats_per_op: BTreeMap<CompStorOp, CompStorStats>,
    /// Global statistics
    global_stats: CompStorStats,
}

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

impl CompStorManager {
    /// Create new computational storage manager
    pub fn new() -> Self {
        Self {
            devices: BTreeMap::new(),
            commands: BTreeMap::new(),
            next_cmd_id: 1,
            stats_per_op: BTreeMap::new(),
            global_stats: CompStorStats::default(),
        }
    }

    /// Register computational storage device
    ///
    /// # Arguments
    /// * `capabilities` - Device capabilities
    pub fn register_device(&mut self, capabilities: CompStorCapabilities) {
        self.devices.insert(capabilities.device_id, capabilities);
    }

    /// Find device that supports an operation
    ///
    /// # Arguments
    /// * `op` - Operation to find support for
    ///
    /// # Returns
    /// Device ID if found
    fn find_capable_device(&self, op: CompStorOp) -> Option<u64> {
        self.devices
            .iter()
            .find(|(_, caps)| caps.supports(op))
            .map(|(id, _)| *id)
    }

    /// Submit computational storage command
    ///
    /// # Arguments
    /// * `operation` - Operation to perform
    /// * `input_lba` - Input data location
    /// * `input_size` - Input data size
    /// * `output_lba` - Output data location
    ///
    /// # Returns
    /// Command ID if offloaded, None if CPU fallback
    pub fn submit_command(
        &mut self,
        operation: CompStorOp,
        input_lba: u64,
        input_size: u64,
        output_lba: u64,
    ) -> Option<u64> {
        // Find capable device
        let device_id = self.find_capable_device(operation)?;

        let cmd_id = self.next_cmd_id;
        self.next_cmd_id += 1;

        let command = CompStorCommand {
            cmd_id,
            operation,
            input_lba,
            input_size,
            output_lba,
            status: CompStorStatus::Queued,
        };

        self.commands.insert(cmd_id, command);

        // Update statistics
        self.global_stats.total_offloaded += 1;
        self.stats_per_op
            .entry(operation)
            .or_default()
            .total_offloaded += 1;

        Some(cmd_id)
    }

    /// Execute command on device (simulated)
    ///
    /// # Arguments
    /// * `cmd_id` - Command ID
    ///
    /// # Returns
    /// True if successful, false if failed
    pub fn execute_command(&mut self, cmd_id: u64) -> Result<(), &'static str> {
        let cmd = self.commands.get_mut(&cmd_id).ok_or("Command not found")?;

        // Simulate execution
        cmd.status = CompStorStatus::Executing;

        // In real implementation, would issue command to device
        // For now, simulate instant completion
        cmd.status = CompStorStatus::Completed;

        // Update statistics
        self.global_stats.device_completed += 1;
        self.stats_per_op
            .entry(cmd.operation)
            .or_default()
            .device_completed += 1;

        // Estimate CPU cycles saved
        let cycles_saved = cmd.operation.cpu_cost() * cmd.input_size;
        self.global_stats.cpu_cycles_saved += cycles_saved;
        self.stats_per_op
            .entry(cmd.operation)
            .or_default()
            .cpu_cycles_saved += cycles_saved;

        Ok(())
    }

    /// Fall back to CPU execution
    ///
    /// # Arguments
    /// * `operation` - Operation that needs CPU fallback
    pub fn cpu_fallback(&mut self, operation: CompStorOp) {
        self.global_stats.cpu_fallback += 1;
        self.stats_per_op.entry(operation).or_default().cpu_fallback += 1;
    }

    /// Get command status
    ///
    /// # Arguments
    /// * `cmd_id` - Command ID
    pub fn get_command_status(&self, cmd_id: u64) -> Option<CompStorStatus> {
        self.commands.get(&cmd_id).map(|cmd| cmd.status)
    }

    /// Get statistics for an operation
    pub fn get_op_stats(&self, op: CompStorOp) -> CompStorStats {
        self.stats_per_op.get(&op).cloned().unwrap_or_default()
    }

    /// Get global statistics
    pub fn get_global_stats(&self) -> CompStorStats {
        self.global_stats.clone()
    }

    /// Calculate offload efficiency
    ///
    /// # Returns
    /// Percentage of operations offloaded (0.0 - 100.0)
    pub fn offload_efficiency(&self) -> f64 {
        let total = self.global_stats.total_offloaded + self.global_stats.cpu_fallback;
        if total == 0 {
            return 0.0;
        }

        (self.global_stats.device_completed as f64 / total as f64) * 100.0
    }

    /// Get device count
    pub fn device_count(&self) -> usize {
        self.devices.len()
    }
}

/// Global computational storage operations
pub struct CompStorEngine;

impl CompStorEngine {
    /// Register device
    pub fn register_device(capabilities: CompStorCapabilities) {
        let mut mgr = COMPSTOR_MANAGER.lock();
        mgr.register_device(capabilities);
    }

    /// Offload operation to computational storage
    ///
    /// # Arguments
    /// * `operation` - Operation to perform
    /// * `input_lba` - Input data LBA
    /// * `input_size` - Input size
    /// * `output_lba` - Output LBA
    ///
    /// # Returns
    /// Command ID if offloaded, None if not supported (use CPU)
    pub fn offload(
        operation: CompStorOp,
        input_lba: u64,
        input_size: u64,
        output_lba: u64,
    ) -> Option<u64> {
        let mut mgr = COMPSTOR_MANAGER.lock();

        if let Some(cmd_id) = mgr.submit_command(operation, input_lba, input_size, output_lba) {
            // Execute immediately (in real impl, would be async)
            let _ = mgr.execute_command(cmd_id);
            Some(cmd_id)
        } else {
            // Not supported, record CPU fallback
            mgr.cpu_fallback(operation);
            None
        }
    }

    /// Get command status
    pub fn command_status(cmd_id: u64) -> Option<CompStorStatus> {
        let mgr = COMPSTOR_MANAGER.lock();
        mgr.get_command_status(cmd_id)
    }

    /// Get operation statistics
    pub fn op_stats(op: CompStorOp) -> CompStorStats {
        let mgr = COMPSTOR_MANAGER.lock();
        mgr.get_op_stats(op)
    }

    /// Get global statistics
    pub fn global_stats() -> CompStorStats {
        let mgr = COMPSTOR_MANAGER.lock();
        mgr.get_global_stats()
    }

    /// Get offload efficiency
    pub fn efficiency() -> f64 {
        let mgr = COMPSTOR_MANAGER.lock();
        mgr.offload_efficiency()
    }

    /// Get device count
    pub fn device_count() -> usize {
        let mgr = COMPSTOR_MANAGER.lock();
        mgr.device_count()
    }
}

/// Create a typical computational storage device configuration
pub fn create_typical_compstor_device(device_id: u64) -> CompStorCapabilities {
    let mut caps = CompStorCapabilities::new(device_id, "Samsung SmartSSD");

    // SmartSSD supports these operations
    caps.add_support(CompStorOp::Checksum);
    caps.add_support(CompStorOp::Compress);
    caps.add_support(CompStorOp::Decompress);
    caps.add_support(CompStorOp::DedupHash);
    caps.add_support(CompStorOp::PatternScan);

    caps.max_queue_depth = 64;
    caps.throughput_ops_sec = 500_000;

    caps
}

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

    #[test]
    fn test_op_properties() {
        assert_eq!(CompStorOp::Checksum.name(), "checksum");
        assert!(CompStorOp::Compress.cpu_cost() > CompStorOp::Checksum.cpu_cost());
    }

    #[test]
    fn test_capabilities() {
        let mut caps = CompStorCapabilities::new(1, "TestDevice");
        assert!(!caps.supports(CompStorOp::Checksum));

        caps.add_support(CompStorOp::Checksum);
        assert!(caps.supports(CompStorOp::Checksum));
    }

    #[test]
    fn test_register_device() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);

        mgr.register_device(caps);
        assert_eq!(mgr.device_count(), 1);
    }

    #[test]
    fn test_submit_command() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);
        mgr.register_device(caps);

        let cmd_id = mgr.submit_command(CompStorOp::Checksum, 0, 4096, 1000);
        assert!(cmd_id.is_some());

        let status = mgr.get_command_status(cmd_id.expect("test: operation should succeed"));
        assert_eq!(status, Some(CompStorStatus::Queued));
    }

    #[test]
    fn test_execute_command() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);
        mgr.register_device(caps);

        let cmd_id = mgr
            .submit_command(CompStorOp::Checksum, 0, 4096, 1000)
            .expect("test: operation should succeed");
        mgr.execute_command(cmd_id)
            .expect("test: operation should succeed");

        let status = mgr.get_command_status(cmd_id);
        assert_eq!(status, Some(CompStorStatus::Completed));
    }

    #[test]
    fn test_cpu_fallback() {
        let mut mgr = CompStorManager::new();
        // No devices registered

        let cmd_id = mgr.submit_command(CompStorOp::Checksum, 0, 4096, 1000);
        assert!(cmd_id.is_none()); // Should fail, no capable device

        mgr.cpu_fallback(CompStorOp::Checksum);
        assert_eq!(mgr.global_stats.cpu_fallback, 1);
    }

    #[test]
    fn test_statistics() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);
        mgr.register_device(caps);

        // Submit and execute multiple commands
        for i in 0..10 {
            if let Some(cmd_id) =
                mgr.submit_command(CompStorOp::Checksum, i * 4096, 4096, 10000 + i * 4096)
            {
                mgr.execute_command(cmd_id)
                    .expect("test: operation should succeed");
            }
        }

        let stats = mgr.get_global_stats();
        assert_eq!(stats.total_offloaded, 10);
        assert_eq!(stats.device_completed, 10);
        assert!(stats.cpu_cycles_saved > 0);
    }

    #[test]
    fn test_offload_efficiency() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);
        mgr.register_device(caps);

        // 8 offloaded, 2 CPU fallback
        for _ in 0..8 {
            if let Some(cmd_id) = mgr.submit_command(CompStorOp::Checksum, 0, 4096, 1000) {
                mgr.execute_command(cmd_id)
                    .expect("test: operation should succeed");
            }
        }

        for _ in 0..2 {
            mgr.cpu_fallback(CompStorOp::Encrypt); // Not supported
        }

        let efficiency = mgr.offload_efficiency();
        assert!(efficiency > 75.0 && efficiency < 85.0); // ~80%
    }

    #[test]
    fn test_per_op_stats() {
        let mut mgr = CompStorManager::new();
        let caps = create_typical_compstor_device(1);
        mgr.register_device(caps);

        // Checksum operations
        for _ in 0..5 {
            if let Some(cmd_id) = mgr.submit_command(CompStorOp::Checksum, 0, 4096, 1000) {
                mgr.execute_command(cmd_id)
                    .expect("test: operation should succeed");
            }
        }

        // Compress operations
        for _ in 0..3 {
            if let Some(cmd_id) = mgr.submit_command(CompStorOp::Compress, 0, 4096, 1000) {
                mgr.execute_command(cmd_id)
                    .expect("test: operation should succeed");
            }
        }

        let checksum_stats = mgr.get_op_stats(CompStorOp::Checksum);
        let compress_stats = mgr.get_op_stats(CompStorOp::Compress);

        assert_eq!(checksum_stats.device_completed, 5);
        assert_eq!(compress_stats.device_completed, 3);
    }

    #[test]
    fn test_typical_device() {
        let caps = create_typical_compstor_device(1);

        assert!(caps.supports(CompStorOp::Checksum));
        assert!(caps.supports(CompStorOp::Compress));
        assert!(caps.supports(CompStorOp::DedupHash));
        assert!(!caps.supports(CompStorOp::Encrypt)); // Not supported
    }
}