ax-fs 0.5.14

ArceOS filesystem module
Documentation
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
// Copyright 2025 The Axvisor Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use alloc::{
    collections::BTreeMap,
    format,
    string::{String, ToString},
    sync::Arc,
    vec::Vec,
};

use ax_fs_vfs::{
    VfsDirEntry, VfsError, VfsNodeAttr, VfsNodeOps, VfsNodePerm, VfsNodeRef, VfsNodeType, VfsOps,
    VfsResult,
};
use rsext4::{
    Ext4Error, Ext4FileSystem as Rsext4FileSystem, Ext4Result, Ext4Timestamp, Jbd2Dev,
    api::{OpenFile, fs_mount, lseek, open, read_at},
    dir::{get_inode_with_num, mkdir},
    entries::classic_dir::list_entries,
    file::{delete_dir, mkfile, mv, truncate, unlink, write_file},
    loopfile::resolve_inode_block_allextend,
};
use spin::Mutex;

use crate::dev::{Disk, Partition};

/// Block size for ext4 filesystem operations
pub const BLOCK_SIZE: usize = 4096;

/// Ext4 filesystem implementation that works with a disk device
#[allow(dead_code)]
pub struct Ext4FileSystem {
    inner: Arc<Mutex<Jbd2Dev<Disk>>>,
    fs: Arc<Mutex<Rsext4FileSystem>>,
}

/// Ext4FileSystem that works with a partition
pub struct Ext4FileSystemPartition {
    inner: Arc<Mutex<Jbd2Dev<Partition>>>,
    fs: Arc<Mutex<Rsext4FileSystem>>,
}

unsafe impl Sync for Ext4FileSystem {}
unsafe impl Send for Ext4FileSystem {}

unsafe impl Sync for Ext4FileSystemPartition {}
unsafe impl Send for Ext4FileSystemPartition {}

impl Ext4FileSystem {
    /// Create a new ext4 filesystem from a disk device
    #[allow(dead_code)]
    pub fn new(disk: Disk) -> Self {
        info!(
            "Got Disk size:{}, position:{}",
            disk.size(),
            disk.position()
        );
        let mut inner = Jbd2Dev::initial_jbd2dev(0, disk, false);
        let fs = fs_mount(&mut inner).expect("failed to initialize EXT4 filesystem");
        Self {
            inner: Arc::new(Mutex::new(inner)),
            fs: Arc::new(Mutex::new(fs)),
        }
    }

    /// Create a new ext4 filesystem from a partition
    pub fn from_partition(partition: Partition) -> Ext4FileSystemPartition {
        info!(
            "Got Partition size:{}, position:{}",
            partition.size(),
            partition.position()
        );
        let mut inner = Jbd2Dev::initial_jbd2dev(0, partition, false);
        let fs = fs_mount(&mut inner).expect("failed to initialize EXT4 filesystem on partition");
        Ext4FileSystemPartition {
            inner: Arc::new(Mutex::new(inner)),
            fs: Arc::new(Mutex::new(fs)),
        }
    }
}

/// The [`VfsOps`] trait provides operations on a filesystem.
impl VfsOps for Ext4FileSystem {
    fn root_dir(&self) -> VfsNodeRef {
        debug!("Get root_dir");
        Arc::new(FileWrapper::new(
            "/",
            Ext4Inner::Disk(Arc::clone(&self.inner)),
            Arc::clone(&self.fs),
        ))
    }
}

/// The [`VfsOps`] trait provides operations on a filesystem.
impl VfsOps for Ext4FileSystemPartition {
    fn root_dir(&self) -> VfsNodeRef {
        debug!("Get root_dir");
        Arc::new(FileWrapper::new(
            "/",
            Ext4Inner::Partition(Arc::clone(&self.inner)),
            Arc::clone(&self.fs),
        ))
    }
}

/// Inner state for ext4 filesystem, either backed by a full disk or a partition
#[derive(Clone)]
pub enum Ext4Inner {
    /// Full disk device
    Disk(Arc<Mutex<Jbd2Dev<Disk>>>),
    /// Partition device
    Partition(Arc<Mutex<Jbd2Dev<Partition>>>),
}

/// Wrapper for files and directories in the ext4 filesystem
pub struct FileWrapper {
    path: String,
    file: Mutex<Option<OpenFile>>,
    inner: Ext4Inner,
    fs: Arc<Mutex<Rsext4FileSystem>>,
}

unsafe impl Send for FileWrapper {}
unsafe impl Sync for FileWrapper {}

impl FileWrapper {
    fn new(path: &str, inner: Ext4Inner, fs: Arc<Mutex<Rsext4FileSystem>>) -> Self {
        debug!("FileWrapper new {}", path);
        Self {
            path: path.to_string(),
            file: Mutex::new(None),
            inner,
            fs,
        }
    }

    fn path_deal_with(&self, path: &str) -> String {
        if path.starts_with('/') {
            debug!("path_deal_with: {}", path);
        }
        let trim_path = path.trim_matches('/');
        if trim_path.is_empty() || trim_path == "." {
            return self.path.to_string();
        }

        if let Some(rest) = trim_path.strip_prefix("./") {
            // if starts with "./"
            return self.path_deal_with(rest);
        }
        let rest_p = trim_path.replace("//", "/");
        if trim_path != rest_p {
            return self.path_deal_with(&rest_p);
        }

        let base_path = self.path.trim_end_matches('/');
        if base_path == "/" {
            format!("/{}", trim_path)
        } else {
            format!("{}/{}", base_path, trim_path)
        }
    }
}

/// The [`VfsNodeOps`] trait provides operations on a file or a directory.
impl VfsNodeOps for FileWrapper {
    fn get_attr(&self) -> VfsResult<VfsNodeAttr> {
        let mut fs = self.fs.lock();
        let perm = VfsNodePerm::from_bits_truncate(0o755);
        let (_inode_num, inode) = match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &self.path)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &self.path)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
        };
        let vtype = if inode.is_dir() {
            VfsNodeType::Dir
        } else {
            VfsNodeType::File
        };
        let size = inode.size();
        let blocks = inode.blocks_count();

        trace!(
            "get_attr of {:?}, size: {}, blocks: {}",
            self.path, size, blocks
        );

        Ok(VfsNodeAttr::new(perm, vtype, size, blocks))
    }

    fn create(&self, path: &str, ty: VfsNodeType) -> VfsResult {
        debug!("create {:?} on Ext4fs: {}", ty, path);
        let fpath = self.path_deal_with(path);
        if fpath.is_empty() {
            return Ok(());
        }

        let mut fs = self.fs.lock();
        match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                match ty {
                    VfsNodeType::Dir => {
                        let _ = mkdir(&mut inner, &mut fs, &fpath);
                    }
                    _ => {
                        let _ = mkfile(&mut inner, &mut fs, &fpath, None, None);
                    }
                }
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                match ty {
                    VfsNodeType::Dir => {
                        let _ = mkdir(&mut inner, &mut fs, &fpath);
                    }
                    _ => {
                        let _ = mkfile(&mut inner, &mut fs, &fpath, None, None);
                    }
                }
            }
        }
        Ok(())
    }

    fn remove(&self, path: &str) -> VfsResult {
        debug!("remove ext4fs: {}", path);
        let fpath = self.path_deal_with(path);
        assert!(!fpath.is_empty()); // already check at `root.rs`

        let mut fs = self.fs.lock();
        let (_inode_num, inode) = match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &fpath)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &fpath)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
        };

        match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                if inode.is_dir() {
                    let _ = delete_dir(&mut fs, &mut inner, &fpath);
                } else {
                    let _ = unlink(&mut fs, &mut inner, &fpath);
                }
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                if inode.is_dir() {
                    let _ = delete_dir(&mut fs, &mut inner, &fpath);
                } else {
                    let _ = unlink(&mut fs, &mut inner, &fpath);
                }
            }
        }
        Ok(())
    }

    /// Get the parent directory of this directory.
    /// Return `None` if the node is a file.
    fn parent(&self) -> Option<VfsNodeRef> {
        let path = &self.path;
        debug!("Get the parent dir of {}", path);
        let path = path.trim_end_matches('/').trim_end_matches(|c| c != '/');
        if !path.is_empty() {
            return Some(Arc::new(Self::new(
                path,
                self.inner.clone(),
                Arc::clone(&self.fs),
            )));
        }
        None
    }

    /// Read directory entries into `dirents`, starting from `start_idx`.
    fn read_dir(&self, start_idx: usize, dirents: &mut [VfsDirEntry]) -> VfsResult<usize> {
        let mut fs = self.fs.lock();
        let (_inode_num, mut inode) = match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &self.path)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &self.path)
                    .map_err(|_| VfsError::Io)?
                    .ok_or(VfsError::NotFound)?
            }
        };

        if !inode.is_dir() {
            return Err(VfsError::Unsupported);
        }

        let blocks = match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                resolve_inode_block_allextend(&mut fs, &mut inner, &mut inode)
                    .map_err(|_| VfsError::Io)?
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                resolve_inode_block_allextend(&mut fs, &mut inner, &mut inode)
                    .map_err(|_| VfsError::Io)?
            }
        };

        let mut data = Vec::new();
        for (_, phys_block) in blocks {
            let cached = match self.inner {
                Ext4Inner::Disk(ref inner) => {
                    let mut inner = inner.lock();
                    fs.datablock_cache
                        .get_or_load(&mut inner, phys_block)
                        .map_err(|_| VfsError::Io)?
                }
                Ext4Inner::Partition(ref inner) => {
                    let mut inner = inner.lock();
                    fs.datablock_cache
                        .get_or_load(&mut inner, phys_block)
                        .map_err(|_| VfsError::Io)?
                }
            };
            data.extend_from_slice(&cached.data);
        }

        let entries = list_entries(&data);
        let mut unique = BTreeMap::new();
        for entry in entries {
            if let Some(name) = entry.name_str()
                && name != "."
                && name != ".."
            {
                unique.insert(name.to_string(), entry.file_type);
            }
        }
        let unique_vec: Vec<_> = unique.into_iter().collect();
        let mut count = 0;
        for (name, file_type) in unique_vec.iter().skip(start_idx) {
            if count >= dirents.len() {
                break;
            }
            let ty = match *file_type {
                2 => VfsNodeType::Dir,
                _ => VfsNodeType::File,
            };
            dirents[count] = VfsDirEntry::new(name, ty);
            count += 1;
        }
        Ok(count)
    }

    /// Lookup the node with given `path` in the directory.
    /// Return the node if found.
    fn lookup(self: Arc<Self>, path: &str) -> VfsResult<VfsNodeRef> {
        trace!("lookup ext4fs: {}, {}", self.path, path);
        let fpath = self.path_deal_with(path);
        if fpath.is_empty() {
            return Ok(self.clone());
        }

        let mut fs = self.fs.lock();
        let exists = match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &fpath)
                    .map_err(|_| VfsError::Io)?
                    .is_some()
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                get_inode_with_num(&mut fs, &mut inner, &fpath)
                    .map_err(|_| VfsError::Io)?
                    .is_some()
            }
        };

        if exists {
            Ok(Arc::new(Self::new(
                &fpath,
                self.inner.clone(),
                Arc::clone(&self.fs),
            )))
        } else {
            Err(VfsError::NotFound)
        }
    }

    fn read_at(&self, offset: u64, buf: &mut [u8]) -> VfsResult<usize> {
        let mut file_guard = self.file.lock();
        if file_guard.is_none() {
            let mut fs = self.fs.lock();
            *file_guard = match self.inner {
                Ext4Inner::Disk(ref inner) => {
                    let mut inner = inner.lock();
                    open(&mut inner, &mut fs, &self.path, false).ok()
                }
                Ext4Inner::Partition(ref inner) => {
                    let mut inner = inner.lock();
                    open(&mut inner, &mut fs, &self.path, false).ok()
                }
            };
        }

        if let Some(ref mut file) = *file_guard {
            let mut fs = self.fs.lock();
            let _ = lseek(file, offset);
            let data = match self.inner {
                Ext4Inner::Disk(ref inner) => {
                    let mut inner = inner.lock();
                    read_at(&mut inner, &mut fs, file, buf.len()).map_err(|_| VfsError::Io)?
                }
                Ext4Inner::Partition(ref inner) => {
                    let mut inner = inner.lock();
                    read_at(&mut inner, &mut fs, file, buf.len()).map_err(|_| VfsError::Io)?
                }
            };
            let len = data.len().min(buf.len());
            buf[..len].copy_from_slice(&data[..len]);
            Ok(len)
        } else {
            Err(VfsError::NotFound)
        }
    }

    fn write_at(&self, offset: u64, buf: &[u8]) -> VfsResult<usize> {
        let mut fs = self.fs.lock();
        match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                write_file(&mut inner, &mut fs, &self.path, offset, buf)
                    .map_err(|_| VfsError::Io)?;
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                write_file(&mut inner, &mut fs, &self.path, offset, buf)
                    .map_err(|_| VfsError::Io)?;
            }
        };
        Ok(buf.len())
    }

    fn truncate(&self, size: u64) -> VfsResult {
        let mut fs = self.fs.lock();
        match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                let _ = truncate(&mut inner, &mut fs, &self.path, size);
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                let _ = truncate(&mut inner, &mut fs, &self.path, size);
            }
        }
        Ok(())
    }

    fn rename(&self, src_path: &str, dst_path: &str) -> VfsResult {
        debug!("rename from {} to {}", src_path, dst_path);

        let src_fpath = self.path_deal_with(src_path);
        let dst_fpath = self.path_deal_with(dst_path);

        let mut fs = self.fs.lock();
        match self.inner {
            Ext4Inner::Disk(ref inner) => {
                let mut inner = inner.lock();
                let _ = mv(&mut fs, &mut inner, &src_fpath, &dst_fpath);
            }
            Ext4Inner::Partition(ref inner) => {
                let mut inner = inner.lock();
                let _ = mv(&mut fs, &mut inner, &src_fpath, &dst_fpath);
            }
        }
        Ok(())
    }

    fn as_any(&self) -> &dyn core::any::Any {
        self as &dyn core::any::Any
    }
}

impl Drop for FileWrapper {
    fn drop(&mut self) {
        debug!("Drop struct FileWrapper {:?}", self.path);
        // File will be automatically closed when OpenFile is dropped
    }
}

impl rsext4::BlockDevice for Disk {
    fn write(
        &mut self,
        buffer: &[u8],
        block_id: rsext4::bmalloc::AbsoluteBN,
        count: u32,
    ) -> Ext4Result<()> {
        // RVlwext4 uses 4096 byte blocks, but Disk uses 512 byte blocks
        self.set_position(block_id.raw() * BLOCK_SIZE as u64);
        let mut total_written = 0;
        let to_write = count as usize * BLOCK_SIZE;

        while total_written < to_write {
            let remaining = &buffer[total_written..];
            let written = self.write_one(remaining).map_err(|_| Ext4Error::io())?;
            total_written += written;
        }

        Ok(())
    }

    fn read(
        &mut self,
        buffer: &mut [u8],
        block_id: rsext4::bmalloc::AbsoluteBN,
        count: u32,
    ) -> Ext4Result<()> {
        self.set_position(block_id.raw() * BLOCK_SIZE as u64);
        let mut total_read = 0;
        let to_read = count as usize * BLOCK_SIZE;

        while total_read < to_read {
            let remaining = &mut buffer[total_read..];
            let read = self.read_one(remaining).map_err(|_| Ext4Error::io())?;
            total_read += read;
        }

        Ok(())
    }

    fn open(&mut self) -> Ext4Result<()> {
        Ok(())
    }

    fn close(&mut self) -> Ext4Result<()> {
        Ok(())
    }

    fn total_blocks(&self) -> u64 {
        // RVlwext4 uses 4096 byte blocks
        self.size() / BLOCK_SIZE as u64
    }

    fn current_time(&self) -> Ext4Result<Ext4Timestamp> {
        let now = ax_hal::time::wall_time();
        let sec =
            i64::try_from(now.as_secs()).map_err(|_| Ext4Error::from(rsext4::Errno::EOVERFLOW))?;
        Ok(Ext4Timestamp::new(sec, now.subsec_nanos()))
    }
}

impl rsext4::BlockDevice for Partition {
    fn write(
        &mut self,
        buffer: &[u8],
        block_id: rsext4::bmalloc::AbsoluteBN,
        count: u32,
    ) -> Ext4Result<()> {
        self.set_position(block_id.raw() * BLOCK_SIZE as u64);
        let mut total_written = 0;
        let to_write = count as usize * BLOCK_SIZE;

        while total_written < to_write {
            let remaining = &buffer[total_written..];
            let written = self.write_one(remaining).map_err(|_| Ext4Error::io())?;
            total_written += written;
        }

        Ok(())
    }

    fn read(
        &mut self,
        buffer: &mut [u8],
        block_id: rsext4::bmalloc::AbsoluteBN,
        count: u32,
    ) -> Ext4Result<()> {
        self.set_position(block_id.raw() * BLOCK_SIZE as u64);
        let mut total_read = 0;
        let to_read = count as usize * BLOCK_SIZE;

        while total_read < to_read {
            let remaining = &mut buffer[total_read..];
            let read = self.read_one(remaining).map_err(|_| Ext4Error::io())?;
            total_read += read;
        }

        Ok(())
    }

    fn open(&mut self) -> Ext4Result<()> {
        Ok(())
    }

    fn close(&mut self) -> Ext4Result<()> {
        Ok(())
    }

    fn total_blocks(&self) -> u64 {
        // RVlwext4 uses 4096 byte blocks
        self.size() / BLOCK_SIZE as u64
    }

    fn current_time(&self) -> Ext4Result<Ext4Timestamp> {
        let now = ax_hal::time::wall_time();
        let sec =
            i64::try_from(now.as_secs()).map_err(|_| Ext4Error::from(rsext4::Errno::EOVERFLOW))?;
        Ok(Ext4Timestamp::new(sec, now.subsec_nanos()))
    }
}