ahrightos-fs 0.1.0

Portable filesystem, block-device, and IPC primitives for the AhRightOS teaching kernel.
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
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
//! Persistent block-backed file system (BlkFS)
//!
//! A simple block-device-backed filesystem for AhRightOS.
//! Layout: superblock (block 0) | inode table (blocks 1..N) | data blocks
//!
//! Each inode occupies one full block (512 bytes), supporting direct
//! block pointers for small files — sufficient for a teaching OS.

use super::block_dev::{BlockDeviceHandle, BLOCK_SIZE};
use super::file::{File, FileError, FileType, SeekFrom};
use super::inode::Inode;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use spin::Mutex;

// --- On-disk layout constants ---

/// Magic number for BlkFS superblock
const BLKFS_MAGIC: u32 = 0x424C4B46; // "BLKF"
/// Maximum number of inodes supported
const MAX_INODES: usize = 128;
/// Number of direct block pointers per inode
const DIRECT_BLOCKS: usize = 12;
/// Maximum file size (12 direct blocks × 512 bytes)
const MAX_FILE_SIZE: usize = DIRECT_BLOCKS * BLOCK_SIZE;
/// Fixed on-disk directory entry size.
const DIR_ENTRY_SIZE: usize = 256;
/// Directory entry name bytes available before the inode field.
const DIR_ENTRY_NAME_BYTES: usize = 250;
/// Superblock lives at block 0
const SUPERBLOCK_BLOCK: usize = 0;
/// Inode table starts at block 1
const INODE_TABLE_START: usize = 1;
/// Each inode occupies one block
const INODE_BLOCK_SIZE: usize = 1;
/// Data blocks start immediately after the inode table
const DATA_BLOCK_START: usize = INODE_TABLE_START + MAX_INODES * INODE_BLOCK_SIZE;

/// Public teaching contract: maximum BlkFS inode count.
pub const BLKFS_MAX_INODES: usize = MAX_INODES;
/// Public teaching contract: maximum BlkFS file size in bytes.
pub const BLKFS_MAX_FILE_SIZE: usize = MAX_FILE_SIZE;
/// Public teaching contract: maximum BlkFS path component length in bytes.
pub const BLKFS_MAX_NAME_BYTES: usize = DIR_ENTRY_NAME_BYTES;
/// Public teaching contract: minimum block-device size that can hold one data block.
pub const BLKFS_MIN_BLOCKS: usize = DATA_BLOCK_START + 1;

// --- Superblock ---

/// On-disk superblock structure (packed)
#[repr(C, packed)]
#[derive(Clone, Copy)]
struct Superblock {
    magic: u32,
    total_blocks: u32,
    free_blocks: u32,
    inode_count: u32,
    root_inode: u32, // inode number of root directory (0 = none)
    _reserved: [u8; 488],
}

impl Superblock {
    fn new(total_blocks: usize) -> Self {
        let free_blocks = total_blocks.saturating_sub(DATA_BLOCK_START);
        Superblock {
            magic: BLKFS_MAGIC,
            total_blocks: total_blocks as u32,
            free_blocks: free_blocks as u32,
            inode_count: 0,
            root_inode: 0,
            _reserved: [0u8; 488],
        }
    }

    fn data_start_block(&self) -> usize {
        DATA_BLOCK_START
    }
}

// --- On-disk inode ---

#[repr(C, packed)]
#[derive(Clone, Copy)]
struct DiskInode {
    ino: u32,
    file_type: u8, // 0=free, 1=file, 2=directory
    mode: u32,
    size: u32,
    created: u64,
    modified: u64,
    nlinks: u32,
    blocks: [u32; DIRECT_BLOCKS], // block numbers (0 = unused)
    _reserved: [u8; 6],
}

impl DiskInode {
    fn zero() -> Self {
        DiskInode {
            ino: 0,
            file_type: 0,
            mode: 0,
            size: 0,
            created: 0,
            modified: 0,
            nlinks: 0,
            blocks: [0u32; DIRECT_BLOCKS],
            _reserved: [0u8; 6],
        }
    }

    fn block_bytes(&self) -> [u8; BLOCK_SIZE] {
        let mut buf = [0u8; BLOCK_SIZE];
        let src = unsafe {
            core::slice::from_raw_parts(
                self as *const DiskInode as *const u8,
                core::mem::size_of::<DiskInode>(),
            )
        };
        buf[..src.len()].copy_from_slice(src);
        buf
    }

    fn from_bytes(bytes: &[u8; BLOCK_SIZE]) -> Self {
        unsafe { core::ptr::read(bytes.as_ptr() as *const DiskInode) }
    }
}

// --- In-memory inode wrapper ---

/// BlkInode wraps an on-disk inode entry with block-device I/O.
pub struct BlkInode {
    ino: usize,
    disk: DiskInode,
    dev: BlockDeviceHandle,
}

impl BlkInode {
    fn load(dev: &BlockDeviceHandle, ino: usize) -> Result<Self, FileError> {
        if ino >= MAX_INODES {
            return Err(FileError::NotFound);
        }
        let block_no = INODE_TABLE_START + ino * INODE_BLOCK_SIZE;
        let mut buf = [0u8; BLOCK_SIZE];
        dev.read_block(block_no, &mut buf)?;
        let disk = DiskInode::from_bytes(&buf);
        if disk.ino as usize != ino || disk.file_type == 0 {
            return Err(FileError::NotFound);
        }
        Ok(BlkInode {
            ino,
            disk,
            dev: Arc::clone(dev),
        })
    }

    fn store(&self) -> Result<(), FileError> {
        let block_no = INODE_TABLE_START + self.ino * INODE_BLOCK_SIZE;
        let buf = self.disk.block_bytes();
        self.dev.write_block(block_no, &buf)
    }

    fn alloc_block(&mut self) -> Result<usize, FileError> {
        for i in 0..DIRECT_BLOCKS {
            if self.disk.blocks[i] == 0 {
                let sb = Self::read_superblock(&self.dev)?;
                let data_start = sb.data_start_block();
                if sb.free_blocks == 0 {
                    return Err(FileError::IoError);
                }
                // simple alloc: use next free block from the end
                let used_data_blocks =
                    (sb.total_blocks as usize).saturating_sub(data_start + sb.free_blocks as usize);
                let new_block = data_start + used_data_blocks;
                if new_block >= sb.total_blocks as usize {
                    return Err(FileError::IoError);
                }
                self.disk.blocks[i] = new_block as u32;
                // update superblock free count
                let mut sb = sb;
                sb.free_blocks -= 1;
                Self::write_superblock(&self.dev, &sb)?;
                self.store()?;
                return Ok(new_block);
            }
        }
        Err(FileError::IoError)
    }

    fn read_superblock(dev: &BlockDeviceHandle) -> Result<Superblock, FileError> {
        let mut buf = [0u8; BLOCK_SIZE];
        dev.read_block(SUPERBLOCK_BLOCK, &mut buf)?;
        Ok(unsafe { core::ptr::read(buf.as_ptr() as *const Superblock) })
    }

    fn write_superblock(dev: &BlockDeviceHandle, sb: &Superblock) -> Result<(), FileError> {
        let mut buf = [0u8; BLOCK_SIZE];
        let src = unsafe {
            core::slice::from_raw_parts(
                sb as *const Superblock as *const u8,
                core::mem::size_of::<Superblock>(),
            )
        };
        buf[..src.len()].copy_from_slice(src);
        dev.write_block(SUPERBLOCK_BLOCK, &buf)
    }

    /// Read from this inode at the given offset.
    pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize, FileError> {
        if self.disk.file_type != 1 && self.disk.file_type != 2 {
            return Err(FileError::IsDirectory);
        }
        let size = self.disk.size as usize;
        if offset >= size {
            return Ok(0);
        }
        let end = core::cmp::min(offset.saturating_add(buf.len()), size);
        let mut read_total = 0usize;
        let mut pos = offset;
        while pos < end {
            let block_idx = pos / BLOCK_SIZE;
            if block_idx >= DIRECT_BLOCKS {
                break;
            }
            let block_off = pos % BLOCK_SIZE;
            let disk_block = self.disk.blocks[block_idx] as usize;
            if disk_block == 0 {
                break;
            }
            let mut block_buf = [0u8; BLOCK_SIZE];
            self.dev.read_block(disk_block, &mut block_buf)?;
            let chunk = core::cmp::min(BLOCK_SIZE - block_off, end - pos);
            buf[read_total..read_total + chunk]
                .copy_from_slice(&block_buf[block_off..block_off + chunk]);
            read_total += chunk;
            pos += chunk;
        }
        Ok(read_total)
    }

    /// Write to this inode at the given offset.
    pub fn write_at(&mut self, offset: usize, buf: &[u8]) -> Result<usize, FileError> {
        if self.disk.file_type != 1 && self.disk.file_type != 2 {
            return Err(FileError::IsDirectory);
        }
        let write_end = offset
            .checked_add(buf.len())
            .ok_or(FileError::InvalidOperation)?;
        if write_end > MAX_FILE_SIZE {
            return Err(FileError::InvalidOperation);
        }
        // ensure blocks are allocated
        let needed_blocks = if write_end == 0 {
            0
        } else {
            (write_end - 1) / BLOCK_SIZE + 1
        };
        for i in 0..needed_blocks.min(DIRECT_BLOCKS) {
            if self.disk.blocks[i] == 0 {
                self.alloc_block()?;
            }
        }
        let mut written = 0usize;
        let mut pos = offset;
        while pos < write_end {
            let block_idx = pos / BLOCK_SIZE;
            let block_off = pos % BLOCK_SIZE;
            if block_idx >= DIRECT_BLOCKS || self.disk.blocks[block_idx] == 0 {
                break;
            }
            let disk_block = self.disk.blocks[block_idx] as usize;
            let mut block_buf = [0u8; BLOCK_SIZE];
            self.dev.read_block(disk_block, &mut block_buf)?;
            let chunk = core::cmp::min(BLOCK_SIZE - block_off, write_end - pos);
            block_buf[block_off..block_off + chunk].copy_from_slice(&buf[written..written + chunk]);
            self.dev.write_block(disk_block, &block_buf)?;
            written += chunk;
            pos += chunk;
        }
        if pos > self.disk.size as usize {
            self.disk.size = pos as u32;
        }
        self.disk.modified += 1;
        self.store()?;
        Ok(written)
    }

    // --- Directory operations ---

    /// Add a directory entry: "name\0ino_le_u32"
    pub fn add_entry(&mut self, name: &str, child_ino: usize) -> Result<(), FileError> {
        if self.disk.file_type != 2 {
            return Err(FileError::NotDirectory);
        }
        validate_entry_name(name)?;
        if child_ino >= MAX_INODES {
            return Err(FileError::InvalidOperation);
        }
        // check for duplicate
        match self.lookup(name) {
            Ok(_) => return Err(FileError::AlreadyExists),
            Err(FileError::NotFound) => {}
            Err(e) => return Err(e),
        }
        // encode entry: name + '\0' + 4-byte LE ino, padded to fixed size
        let mut entry = [0u8; DIR_ENTRY_SIZE];
        let name_bytes = name.as_bytes();
        let name_len = name_bytes.len();
        entry[..name_len].copy_from_slice(&name_bytes[..name_len]);
        entry[name_len] = 0; // null terminator
        entry[252..256].copy_from_slice(&(child_ino as u32).to_le_bytes());

        let offset = self.disk.size as usize;
        self.write_at(offset, &entry)?;
        self.disk.modified += 1;
        self.store()?;
        Ok(())
    }

    /// Look up a directory entry by name.
    pub fn lookup(&self, name: &str) -> Result<usize, FileError> {
        if self.disk.file_type != 2 {
            return Err(FileError::NotDirectory);
        }
        validate_entry_name(name)?;
        let size = self.disk.size as usize;
        let mut offset = 0usize;
        while offset < size {
            let mut entry = [0u8; DIR_ENTRY_SIZE];
            let n = self.read_at(offset, &mut entry)?;
            if n < DIR_ENTRY_SIZE {
                break;
            }
            // extract name (null-terminated in first 252 bytes)
            let entry_name_len = entry[..252].iter().position(|&b| b == 0).unwrap_or(252);
            let entry_name = core::str::from_utf8(&entry[..entry_name_len]).unwrap_or("");
            let child_ino =
                u32::from_le_bytes([entry[252], entry[253], entry[254], entry[255]]) as usize;
            if entry_name == name {
                return Ok(child_ino);
            }
            offset += DIR_ENTRY_SIZE;
        }
        Err(FileError::NotFound)
    }

    /// Remove a directory entry.
    pub fn remove_entry(&mut self, name: &str) -> Result<(), FileError> {
        if self.disk.file_type != 2 {
            return Err(FileError::NotDirectory);
        }
        validate_entry_name(name)?;
        let _ino = self.lookup(name)?; // verify exists
                                       // mark entry as deleted by writing empty name
        let mut entry = [0u8; DIR_ENTRY_SIZE];
        entry[0] = 0; // null name = deleted
        let size = self.disk.size as usize;
        let mut offset = 0usize;
        while offset < size {
            let mut buf = [0u8; DIR_ENTRY_SIZE];
            let n = self.read_at(offset, &mut buf)?;
            if n < DIR_ENTRY_SIZE {
                break;
            }
            let entry_name_len = buf[..252].iter().position(|&b| b == 0).unwrap_or(252);
            let entry_name = core::str::from_utf8(&buf[..entry_name_len]).unwrap_or("");
            if entry_name == name {
                self.write_at(offset, &entry)?;
                return Ok(());
            }
            offset += DIR_ENTRY_SIZE;
        }
        Err(FileError::NotFound)
    }

    /// List directory entries.
    pub fn list_entries(&self) -> Result<Vec<String>, FileError> {
        if self.disk.file_type != 2 {
            return Err(FileError::NotDirectory);
        }
        let mut names = Vec::new();
        let size = self.disk.size as usize;
        let mut offset = 0usize;
        while offset < size {
            let mut buf = [0u8; DIR_ENTRY_SIZE];
            let n = self.read_at(offset, &mut buf)?;
            if n < DIR_ENTRY_SIZE {
                break;
            }
            if buf[0] == 0 {
                offset += DIR_ENTRY_SIZE;
                continue; // deleted entry
            }
            let entry_name_len = buf[..252].iter().position(|&b| b == 0).unwrap_or(252);
            if entry_name_len > 0 {
                if let Ok(name) = core::str::from_utf8(&buf[..entry_name_len]) {
                    names.push(String::from(name));
                }
            }
            offset += DIR_ENTRY_SIZE;
        }
        Ok(names)
    }
}

fn validate_entry_name(name: &str) -> Result<(), FileError> {
    let bytes = name.as_bytes();
    if bytes.is_empty()
        || bytes.len() > DIR_ENTRY_NAME_BYTES
        || bytes.iter().any(|&b| b == b'/' || b == 0)
    {
        return Err(FileError::InvalidOperation);
    }
    Ok(())
}

// --- Inode trait implementation ---

impl Inode for BlkInode {
    fn ino(&self) -> usize {
        self.ino
    }
    fn file_type(&self) -> FileType {
        match self.disk.file_type {
            1 => FileType::RegularFile,
            2 => FileType::Directory,
            _ => FileType::RegularFile,
        }
    }
    fn size(&self) -> usize {
        self.disk.size as usize
    }
    fn mode(&self) -> u32 {
        self.disk.mode
    }
}

// --- File trait implementation ---

/// BlkFile: a file handle for BlkFS, wrapping a BlkInode with a current offset.
pub struct BlkFile {
    inode: BlkInode,
    offset: usize,
}

impl BlkFile {
    pub fn new(inode: BlkInode) -> Self {
        BlkFile { inode, offset: 0 }
    }
}

impl File for BlkFile {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, FileError> {
        let n = self.inode.read_at(self.offset, buf)?;
        self.offset += n;
        Ok(n)
    }

    fn write(&mut self, buf: &[u8]) -> Result<usize, FileError> {
        let n = self.inode.write_at(self.offset, buf)?;
        self.offset += n;
        Ok(n)
    }

    fn seek(&mut self, pos: SeekFrom) -> Result<usize, FileError> {
        let size = self.inode.size();
        let new_offset = match pos {
            SeekFrom::Start(o) => o,
            SeekFrom::Current(delta) => {
                if delta >= 0 {
                    self.offset.saturating_add(delta as usize)
                } else {
                    self.offset.saturating_sub((-delta) as usize)
                }
            }
            SeekFrom::End(delta) => {
                if delta >= 0 {
                    size.saturating_add(delta as usize)
                } else {
                    size.saturating_sub((-delta) as usize)
                }
            }
        };
        self.offset = new_offset;
        Ok(self.offset)
    }
}

// --- BlkFS file system ---

/// The persistent block-backed filesystem.
pub struct BlkFS {
    dev: BlockDeviceHandle,
    next_ino: Mutex<usize>,
}

impl BlkFS {
    /// Create a new BlkFS on the given block device, formatting it.
    pub fn create(dev: BlockDeviceHandle) -> Result<Self, FileError> {
        let total_blocks = dev.block_count();
        if total_blocks < BLKFS_MIN_BLOCKS {
            return Err(FileError::InvalidOperation);
        }
        // write superblock
        let sb = Superblock::new(total_blocks);
        let mut sb_buf = [0u8; BLOCK_SIZE];
        let src = unsafe {
            core::slice::from_raw_parts(
                &sb as *const Superblock as *const u8,
                core::mem::size_of::<Superblock>(),
            )
        };
        sb_buf[..src.len()].copy_from_slice(src);
        dev.write_block(SUPERBLOCK_BLOCK, &sb_buf)?;

        // zero the inode table
        let zero_block = DiskInode::zero().block_bytes();
        for i in 0..MAX_INODES {
            dev.write_block(INODE_TABLE_START + i * INODE_BLOCK_SIZE, &zero_block)?;
        }

        // create root directory (inode 0)
        let root_disk = DiskInode {
            ino: 0,
            file_type: 2, // directory
            mode: 0o755,
            size: 0,
            created: 0,
            modified: 1,
            nlinks: 1,
            blocks: [0u32; DIRECT_BLOCKS],
            _reserved: [0u8; 6],
        };
        let root_buf = root_disk.block_bytes();
        dev.write_block(INODE_TABLE_START, &root_buf)?;

        // update superblock
        let mut sb = sb;
        sb.root_inode = 0;
        sb.inode_count = 1;
        let mut sb_buf2 = [0u8; BLOCK_SIZE];
        let src2 = unsafe {
            core::slice::from_raw_parts(
                &sb as *const Superblock as *const u8,
                core::mem::size_of::<Superblock>(),
            )
        };
        sb_buf2[..src2.len()].copy_from_slice(src2);
        dev.write_block(SUPERBLOCK_BLOCK, &sb_buf2)?;

        Ok(BlkFS {
            dev,
            next_ino: Mutex::new(1),
        })
    }

    /// Open an existing BlkFS on the given device (no formatting).
    pub fn open(dev: BlockDeviceHandle) -> Result<Self, FileError> {
        let mut sb_buf = [0u8; BLOCK_SIZE];
        dev.read_block(SUPERBLOCK_BLOCK, &mut sb_buf)?;
        let sb: Superblock = unsafe { core::ptr::read(sb_buf.as_ptr() as *const Superblock) };
        let total_blocks = sb.total_blocks as usize;
        let inode_count = sb.inode_count as usize;
        if sb.magic != BLKFS_MAGIC
            || total_blocks < BLKFS_MIN_BLOCKS
            || total_blocks > dev.block_count()
            || inode_count == 0
            || inode_count > MAX_INODES
            || sb.root_inode != 0
        {
            return Err(FileError::InvalidOperation);
        }
        let next_ino = inode_count;
        Ok(BlkFS {
            dev,
            next_ino: Mutex::new(next_ino),
        })
    }

    fn alloc_ino(&self) -> Result<usize, FileError> {
        let mut next = self.next_ino.lock();
        if *next >= MAX_INODES {
            return Err(FileError::IoError);
        }
        let ino = *next;
        *next += 1;
        Ok(ino)
    }

    fn record_inode_allocated(&self, ino: usize) -> Result<(), FileError> {
        if ino >= MAX_INODES {
            return Err(FileError::InvalidOperation);
        }
        let mut sb = BlkInode::read_superblock(&self.dev)?;
        let needed = ino + 1;
        if sb.inode_count as usize >= needed {
            return Ok(());
        }
        sb.inode_count = needed as u32;
        BlkInode::write_superblock(&self.dev, &sb)
    }

    pub fn device(&self) -> BlockDeviceHandle {
        Arc::clone(&self.dev)
    }

    pub fn sync(&self) -> Result<(), FileError> {
        self.dev.flush()
    }

    /// Get the root inode.
    pub fn root_inode(&self) -> Result<BlkInode, FileError> {
        BlkInode::load(&self.dev, 0)
    }

    /// Create a regular file in a parent directory.
    pub fn create_file(&self, parent: &mut BlkInode, name: &str) -> Result<BlkInode, FileError> {
        validate_entry_name(name)?;
        match parent.lookup(name) {
            Ok(_) => return Err(FileError::AlreadyExists),
            Err(FileError::NotFound) => {}
            Err(e) => return Err(e),
        }
        let ino = self.alloc_ino()?;
        let disk = DiskInode {
            ino: ino as u32,
            file_type: 1,
            mode: 0o644,
            size: 0,
            created: 0,
            modified: 0,
            nlinks: 1,
            blocks: [0u32; DIRECT_BLOCKS],
            _reserved: [0u8; 6],
        };
        let buf = disk.block_bytes();
        self.dev
            .write_block(INODE_TABLE_START + ino * INODE_BLOCK_SIZE, &buf)?;
        parent.add_entry(name, ino)?;
        self.record_inode_allocated(ino)?;
        BlkInode::load(&self.dev, ino)
    }

    /// Create a directory in a parent directory.
    pub fn create_directory(
        &self,
        parent: &mut BlkInode,
        name: &str,
    ) -> Result<BlkInode, FileError> {
        validate_entry_name(name)?;
        match parent.lookup(name) {
            Ok(_) => return Err(FileError::AlreadyExists),
            Err(FileError::NotFound) => {}
            Err(e) => return Err(e),
        }
        let ino = self.alloc_ino()?;
        let disk = DiskInode {
            ino: ino as u32,
            file_type: 2,
            mode: 0o755,
            size: 0,
            created: 0,
            modified: 0,
            nlinks: 1,
            blocks: [0u32; DIRECT_BLOCKS],
            _reserved: [0u8; 6],
        };
        let buf = disk.block_bytes();
        self.dev
            .write_block(INODE_TABLE_START + ino * INODE_BLOCK_SIZE, &buf)?;
        parent.add_entry(name, ino)?;
        self.record_inode_allocated(ino)?;
        BlkInode::load(&self.dev, ino)
    }

    /// Look up a child in a directory.
    pub fn lookup(&self, parent: &BlkInode, name: &str) -> Result<BlkInode, FileError> {
        let ino = parent.lookup(name)?;
        BlkInode::load(&self.dev, ino)
    }

    /// Open a regular file for reading/writing.
    pub fn open_file(&self, inode: BlkInode) -> Result<BlkFile, FileError> {
        if inode.file_type() != FileType::RegularFile {
            return Err(FileError::IsDirectory);
        }
        Ok(BlkFile::new(inode))
    }
}