1use super::block_dev::{BlockDeviceHandle, BLOCK_SIZE};
10use super::file::{File, FileError, FileType, SeekFrom};
11use super::inode::Inode;
12use alloc::string::String;
13use alloc::sync::Arc;
14use alloc::vec::Vec;
15use spin::Mutex;
16
17const BLKFS_MAGIC: u32 = 0x424C4B46; const MAX_INODES: usize = 128;
23const DIRECT_BLOCKS: usize = 12;
25const MAX_FILE_SIZE: usize = DIRECT_BLOCKS * BLOCK_SIZE;
27const DIR_ENTRY_SIZE: usize = 256;
29const DIR_ENTRY_NAME_BYTES: usize = 250;
31const SUPERBLOCK_BLOCK: usize = 0;
33const INODE_TABLE_START: usize = 1;
35const INODE_BLOCK_SIZE: usize = 1;
37const DATA_BLOCK_START: usize = INODE_TABLE_START + MAX_INODES * INODE_BLOCK_SIZE;
39
40pub const BLKFS_MAX_INODES: usize = MAX_INODES;
42pub const BLKFS_MAX_FILE_SIZE: usize = MAX_FILE_SIZE;
44pub const BLKFS_MAX_NAME_BYTES: usize = DIR_ENTRY_NAME_BYTES;
46pub const BLKFS_MIN_BLOCKS: usize = DATA_BLOCK_START + 1;
48
49#[repr(C, packed)]
53#[derive(Clone, Copy)]
54struct Superblock {
55 magic: u32,
56 total_blocks: u32,
57 free_blocks: u32,
58 inode_count: u32,
59 root_inode: u32, _reserved: [u8; 488],
61}
62
63impl Superblock {
64 fn new(total_blocks: usize) -> Self {
65 let free_blocks = total_blocks.saturating_sub(DATA_BLOCK_START);
66 Superblock {
67 magic: BLKFS_MAGIC,
68 total_blocks: total_blocks as u32,
69 free_blocks: free_blocks as u32,
70 inode_count: 0,
71 root_inode: 0,
72 _reserved: [0u8; 488],
73 }
74 }
75
76 fn data_start_block(&self) -> usize {
77 DATA_BLOCK_START
78 }
79}
80
81#[repr(C, packed)]
84#[derive(Clone, Copy)]
85struct DiskInode {
86 ino: u32,
87 file_type: u8, mode: u32,
89 size: u32,
90 created: u64,
91 modified: u64,
92 nlinks: u32,
93 blocks: [u32; DIRECT_BLOCKS], _reserved: [u8; 6],
95}
96
97impl DiskInode {
98 fn zero() -> Self {
99 DiskInode {
100 ino: 0,
101 file_type: 0,
102 mode: 0,
103 size: 0,
104 created: 0,
105 modified: 0,
106 nlinks: 0,
107 blocks: [0u32; DIRECT_BLOCKS],
108 _reserved: [0u8; 6],
109 }
110 }
111
112 fn block_bytes(&self) -> [u8; BLOCK_SIZE] {
113 let mut buf = [0u8; BLOCK_SIZE];
114 let src = unsafe {
115 core::slice::from_raw_parts(
116 self as *const DiskInode as *const u8,
117 core::mem::size_of::<DiskInode>(),
118 )
119 };
120 buf[..src.len()].copy_from_slice(src);
121 buf
122 }
123
124 fn from_bytes(bytes: &[u8; BLOCK_SIZE]) -> Self {
125 unsafe { core::ptr::read(bytes.as_ptr() as *const DiskInode) }
126 }
127}
128
129pub struct BlkInode {
133 ino: usize,
134 disk: DiskInode,
135 dev: BlockDeviceHandle,
136}
137
138impl BlkInode {
139 fn load(dev: &BlockDeviceHandle, ino: usize) -> Result<Self, FileError> {
140 if ino >= MAX_INODES {
141 return Err(FileError::NotFound);
142 }
143 let block_no = INODE_TABLE_START + ino * INODE_BLOCK_SIZE;
144 let mut buf = [0u8; BLOCK_SIZE];
145 dev.read_block(block_no, &mut buf)?;
146 let disk = DiskInode::from_bytes(&buf);
147 if disk.ino as usize != ino || disk.file_type == 0 {
148 return Err(FileError::NotFound);
149 }
150 Ok(BlkInode {
151 ino,
152 disk,
153 dev: Arc::clone(dev),
154 })
155 }
156
157 fn store(&self) -> Result<(), FileError> {
158 let block_no = INODE_TABLE_START + self.ino * INODE_BLOCK_SIZE;
159 let buf = self.disk.block_bytes();
160 self.dev.write_block(block_no, &buf)
161 }
162
163 fn alloc_block(&mut self) -> Result<usize, FileError> {
164 for i in 0..DIRECT_BLOCKS {
165 if self.disk.blocks[i] == 0 {
166 let sb = Self::read_superblock(&self.dev)?;
167 let data_start = sb.data_start_block();
168 if sb.free_blocks == 0 {
169 return Err(FileError::IoError);
170 }
171 let used_data_blocks =
173 (sb.total_blocks as usize).saturating_sub(data_start + sb.free_blocks as usize);
174 let new_block = data_start + used_data_blocks;
175 if new_block >= sb.total_blocks as usize {
176 return Err(FileError::IoError);
177 }
178 self.disk.blocks[i] = new_block as u32;
179 let mut sb = sb;
181 sb.free_blocks -= 1;
182 Self::write_superblock(&self.dev, &sb)?;
183 self.store()?;
184 return Ok(new_block);
185 }
186 }
187 Err(FileError::IoError)
188 }
189
190 fn read_superblock(dev: &BlockDeviceHandle) -> Result<Superblock, FileError> {
191 let mut buf = [0u8; BLOCK_SIZE];
192 dev.read_block(SUPERBLOCK_BLOCK, &mut buf)?;
193 Ok(unsafe { core::ptr::read(buf.as_ptr() as *const Superblock) })
194 }
195
196 fn write_superblock(dev: &BlockDeviceHandle, sb: &Superblock) -> Result<(), FileError> {
197 let mut buf = [0u8; BLOCK_SIZE];
198 let src = unsafe {
199 core::slice::from_raw_parts(
200 sb as *const Superblock as *const u8,
201 core::mem::size_of::<Superblock>(),
202 )
203 };
204 buf[..src.len()].copy_from_slice(src);
205 dev.write_block(SUPERBLOCK_BLOCK, &buf)
206 }
207
208 pub fn read_at(&self, offset: usize, buf: &mut [u8]) -> Result<usize, FileError> {
210 if self.disk.file_type != 1 && self.disk.file_type != 2 {
211 return Err(FileError::IsDirectory);
212 }
213 let size = self.disk.size as usize;
214 if offset >= size {
215 return Ok(0);
216 }
217 let end = core::cmp::min(offset.saturating_add(buf.len()), size);
218 let mut read_total = 0usize;
219 let mut pos = offset;
220 while pos < end {
221 let block_idx = pos / BLOCK_SIZE;
222 if block_idx >= DIRECT_BLOCKS {
223 break;
224 }
225 let block_off = pos % BLOCK_SIZE;
226 let disk_block = self.disk.blocks[block_idx] as usize;
227 if disk_block == 0 {
228 break;
229 }
230 let mut block_buf = [0u8; BLOCK_SIZE];
231 self.dev.read_block(disk_block, &mut block_buf)?;
232 let chunk = core::cmp::min(BLOCK_SIZE - block_off, end - pos);
233 buf[read_total..read_total + chunk]
234 .copy_from_slice(&block_buf[block_off..block_off + chunk]);
235 read_total += chunk;
236 pos += chunk;
237 }
238 Ok(read_total)
239 }
240
241 pub fn write_at(&mut self, offset: usize, buf: &[u8]) -> Result<usize, FileError> {
243 if self.disk.file_type != 1 && self.disk.file_type != 2 {
244 return Err(FileError::IsDirectory);
245 }
246 let write_end = offset
247 .checked_add(buf.len())
248 .ok_or(FileError::InvalidOperation)?;
249 if write_end > MAX_FILE_SIZE {
250 return Err(FileError::InvalidOperation);
251 }
252 let needed_blocks = if write_end == 0 {
254 0
255 } else {
256 (write_end - 1) / BLOCK_SIZE + 1
257 };
258 for i in 0..needed_blocks.min(DIRECT_BLOCKS) {
259 if self.disk.blocks[i] == 0 {
260 self.alloc_block()?;
261 }
262 }
263 let mut written = 0usize;
264 let mut pos = offset;
265 while pos < write_end {
266 let block_idx = pos / BLOCK_SIZE;
267 let block_off = pos % BLOCK_SIZE;
268 if block_idx >= DIRECT_BLOCKS || self.disk.blocks[block_idx] == 0 {
269 break;
270 }
271 let disk_block = self.disk.blocks[block_idx] as usize;
272 let mut block_buf = [0u8; BLOCK_SIZE];
273 self.dev.read_block(disk_block, &mut block_buf)?;
274 let chunk = core::cmp::min(BLOCK_SIZE - block_off, write_end - pos);
275 block_buf[block_off..block_off + chunk].copy_from_slice(&buf[written..written + chunk]);
276 self.dev.write_block(disk_block, &block_buf)?;
277 written += chunk;
278 pos += chunk;
279 }
280 if pos > self.disk.size as usize {
281 self.disk.size = pos as u32;
282 }
283 self.disk.modified += 1;
284 self.store()?;
285 Ok(written)
286 }
287
288 pub fn add_entry(&mut self, name: &str, child_ino: usize) -> Result<(), FileError> {
292 if self.disk.file_type != 2 {
293 return Err(FileError::NotDirectory);
294 }
295 validate_entry_name(name)?;
296 if child_ino >= MAX_INODES {
297 return Err(FileError::InvalidOperation);
298 }
299 match self.lookup(name) {
301 Ok(_) => return Err(FileError::AlreadyExists),
302 Err(FileError::NotFound) => {}
303 Err(e) => return Err(e),
304 }
305 let mut entry = [0u8; DIR_ENTRY_SIZE];
307 let name_bytes = name.as_bytes();
308 let name_len = name_bytes.len();
309 entry[..name_len].copy_from_slice(&name_bytes[..name_len]);
310 entry[name_len] = 0; entry[252..256].copy_from_slice(&(child_ino as u32).to_le_bytes());
312
313 let offset = self.disk.size as usize;
314 self.write_at(offset, &entry)?;
315 self.disk.modified += 1;
316 self.store()?;
317 Ok(())
318 }
319
320 pub fn lookup(&self, name: &str) -> Result<usize, FileError> {
322 if self.disk.file_type != 2 {
323 return Err(FileError::NotDirectory);
324 }
325 validate_entry_name(name)?;
326 let size = self.disk.size as usize;
327 let mut offset = 0usize;
328 while offset < size {
329 let mut entry = [0u8; DIR_ENTRY_SIZE];
330 let n = self.read_at(offset, &mut entry)?;
331 if n < DIR_ENTRY_SIZE {
332 break;
333 }
334 let entry_name_len = entry[..252].iter().position(|&b| b == 0).unwrap_or(252);
336 let entry_name = core::str::from_utf8(&entry[..entry_name_len]).unwrap_or("");
337 let child_ino =
338 u32::from_le_bytes([entry[252], entry[253], entry[254], entry[255]]) as usize;
339 if entry_name == name {
340 return Ok(child_ino);
341 }
342 offset += DIR_ENTRY_SIZE;
343 }
344 Err(FileError::NotFound)
345 }
346
347 pub fn remove_entry(&mut self, name: &str) -> Result<(), FileError> {
349 if self.disk.file_type != 2 {
350 return Err(FileError::NotDirectory);
351 }
352 validate_entry_name(name)?;
353 let _ino = self.lookup(name)?; let mut entry = [0u8; DIR_ENTRY_SIZE];
356 entry[0] = 0; let size = self.disk.size as usize;
358 let mut offset = 0usize;
359 while offset < size {
360 let mut buf = [0u8; DIR_ENTRY_SIZE];
361 let n = self.read_at(offset, &mut buf)?;
362 if n < DIR_ENTRY_SIZE {
363 break;
364 }
365 let entry_name_len = buf[..252].iter().position(|&b| b == 0).unwrap_or(252);
366 let entry_name = core::str::from_utf8(&buf[..entry_name_len]).unwrap_or("");
367 if entry_name == name {
368 self.write_at(offset, &entry)?;
369 return Ok(());
370 }
371 offset += DIR_ENTRY_SIZE;
372 }
373 Err(FileError::NotFound)
374 }
375
376 pub fn list_entries(&self) -> Result<Vec<String>, FileError> {
378 if self.disk.file_type != 2 {
379 return Err(FileError::NotDirectory);
380 }
381 let mut names = Vec::new();
382 let size = self.disk.size as usize;
383 let mut offset = 0usize;
384 while offset < size {
385 let mut buf = [0u8; DIR_ENTRY_SIZE];
386 let n = self.read_at(offset, &mut buf)?;
387 if n < DIR_ENTRY_SIZE {
388 break;
389 }
390 if buf[0] == 0 {
391 offset += DIR_ENTRY_SIZE;
392 continue; }
394 let entry_name_len = buf[..252].iter().position(|&b| b == 0).unwrap_or(252);
395 if entry_name_len > 0 {
396 if let Ok(name) = core::str::from_utf8(&buf[..entry_name_len]) {
397 names.push(String::from(name));
398 }
399 }
400 offset += DIR_ENTRY_SIZE;
401 }
402 Ok(names)
403 }
404}
405
406fn validate_entry_name(name: &str) -> Result<(), FileError> {
407 let bytes = name.as_bytes();
408 if bytes.is_empty()
409 || bytes.len() > DIR_ENTRY_NAME_BYTES
410 || bytes.iter().any(|&b| b == b'/' || b == 0)
411 {
412 return Err(FileError::InvalidOperation);
413 }
414 Ok(())
415}
416
417impl Inode for BlkInode {
420 fn ino(&self) -> usize {
421 self.ino
422 }
423 fn file_type(&self) -> FileType {
424 match self.disk.file_type {
425 1 => FileType::RegularFile,
426 2 => FileType::Directory,
427 _ => FileType::RegularFile,
428 }
429 }
430 fn size(&self) -> usize {
431 self.disk.size as usize
432 }
433 fn mode(&self) -> u32 {
434 self.disk.mode
435 }
436}
437
438pub struct BlkFile {
442 inode: BlkInode,
443 offset: usize,
444}
445
446impl BlkFile {
447 pub fn new(inode: BlkInode) -> Self {
448 BlkFile { inode, offset: 0 }
449 }
450}
451
452impl File for BlkFile {
453 fn read(&mut self, buf: &mut [u8]) -> Result<usize, FileError> {
454 let n = self.inode.read_at(self.offset, buf)?;
455 self.offset += n;
456 Ok(n)
457 }
458
459 fn write(&mut self, buf: &[u8]) -> Result<usize, FileError> {
460 let n = self.inode.write_at(self.offset, buf)?;
461 self.offset += n;
462 Ok(n)
463 }
464
465 fn seek(&mut self, pos: SeekFrom) -> Result<usize, FileError> {
466 let size = self.inode.size();
467 let new_offset = match pos {
468 SeekFrom::Start(o) => o,
469 SeekFrom::Current(delta) => {
470 if delta >= 0 {
471 self.offset.saturating_add(delta as usize)
472 } else {
473 self.offset.saturating_sub((-delta) as usize)
474 }
475 }
476 SeekFrom::End(delta) => {
477 if delta >= 0 {
478 size.saturating_add(delta as usize)
479 } else {
480 size.saturating_sub((-delta) as usize)
481 }
482 }
483 };
484 self.offset = new_offset;
485 Ok(self.offset)
486 }
487}
488
489pub struct BlkFS {
493 dev: BlockDeviceHandle,
494 next_ino: Mutex<usize>,
495}
496
497impl BlkFS {
498 pub fn create(dev: BlockDeviceHandle) -> Result<Self, FileError> {
500 let total_blocks = dev.block_count();
501 if total_blocks < BLKFS_MIN_BLOCKS {
502 return Err(FileError::InvalidOperation);
503 }
504 let sb = Superblock::new(total_blocks);
506 let mut sb_buf = [0u8; BLOCK_SIZE];
507 let src = unsafe {
508 core::slice::from_raw_parts(
509 &sb as *const Superblock as *const u8,
510 core::mem::size_of::<Superblock>(),
511 )
512 };
513 sb_buf[..src.len()].copy_from_slice(src);
514 dev.write_block(SUPERBLOCK_BLOCK, &sb_buf)?;
515
516 let zero_block = DiskInode::zero().block_bytes();
518 for i in 0..MAX_INODES {
519 dev.write_block(INODE_TABLE_START + i * INODE_BLOCK_SIZE, &zero_block)?;
520 }
521
522 let root_disk = DiskInode {
524 ino: 0,
525 file_type: 2, mode: 0o755,
527 size: 0,
528 created: 0,
529 modified: 1,
530 nlinks: 1,
531 blocks: [0u32; DIRECT_BLOCKS],
532 _reserved: [0u8; 6],
533 };
534 let root_buf = root_disk.block_bytes();
535 dev.write_block(INODE_TABLE_START, &root_buf)?;
536
537 let mut sb = sb;
539 sb.root_inode = 0;
540 sb.inode_count = 1;
541 let mut sb_buf2 = [0u8; BLOCK_SIZE];
542 let src2 = unsafe {
543 core::slice::from_raw_parts(
544 &sb as *const Superblock as *const u8,
545 core::mem::size_of::<Superblock>(),
546 )
547 };
548 sb_buf2[..src2.len()].copy_from_slice(src2);
549 dev.write_block(SUPERBLOCK_BLOCK, &sb_buf2)?;
550
551 Ok(BlkFS {
552 dev,
553 next_ino: Mutex::new(1),
554 })
555 }
556
557 pub fn open(dev: BlockDeviceHandle) -> Result<Self, FileError> {
559 let mut sb_buf = [0u8; BLOCK_SIZE];
560 dev.read_block(SUPERBLOCK_BLOCK, &mut sb_buf)?;
561 let sb: Superblock = unsafe { core::ptr::read(sb_buf.as_ptr() as *const Superblock) };
562 let total_blocks = sb.total_blocks as usize;
563 let inode_count = sb.inode_count as usize;
564 if sb.magic != BLKFS_MAGIC
565 || total_blocks < BLKFS_MIN_BLOCKS
566 || total_blocks > dev.block_count()
567 || inode_count == 0
568 || inode_count > MAX_INODES
569 || sb.root_inode != 0
570 {
571 return Err(FileError::InvalidOperation);
572 }
573 let next_ino = inode_count;
574 Ok(BlkFS {
575 dev,
576 next_ino: Mutex::new(next_ino),
577 })
578 }
579
580 fn alloc_ino(&self) -> Result<usize, FileError> {
581 let mut next = self.next_ino.lock();
582 if *next >= MAX_INODES {
583 return Err(FileError::IoError);
584 }
585 let ino = *next;
586 *next += 1;
587 Ok(ino)
588 }
589
590 fn record_inode_allocated(&self, ino: usize) -> Result<(), FileError> {
591 if ino >= MAX_INODES {
592 return Err(FileError::InvalidOperation);
593 }
594 let mut sb = BlkInode::read_superblock(&self.dev)?;
595 let needed = ino + 1;
596 if sb.inode_count as usize >= needed {
597 return Ok(());
598 }
599 sb.inode_count = needed as u32;
600 BlkInode::write_superblock(&self.dev, &sb)
601 }
602
603 pub fn device(&self) -> BlockDeviceHandle {
604 Arc::clone(&self.dev)
605 }
606
607 pub fn sync(&self) -> Result<(), FileError> {
608 self.dev.flush()
609 }
610
611 pub fn root_inode(&self) -> Result<BlkInode, FileError> {
613 BlkInode::load(&self.dev, 0)
614 }
615
616 pub fn create_file(&self, parent: &mut BlkInode, name: &str) -> Result<BlkInode, FileError> {
618 validate_entry_name(name)?;
619 match parent.lookup(name) {
620 Ok(_) => return Err(FileError::AlreadyExists),
621 Err(FileError::NotFound) => {}
622 Err(e) => return Err(e),
623 }
624 let ino = self.alloc_ino()?;
625 let disk = DiskInode {
626 ino: ino as u32,
627 file_type: 1,
628 mode: 0o644,
629 size: 0,
630 created: 0,
631 modified: 0,
632 nlinks: 1,
633 blocks: [0u32; DIRECT_BLOCKS],
634 _reserved: [0u8; 6],
635 };
636 let buf = disk.block_bytes();
637 self.dev
638 .write_block(INODE_TABLE_START + ino * INODE_BLOCK_SIZE, &buf)?;
639 parent.add_entry(name, ino)?;
640 self.record_inode_allocated(ino)?;
641 BlkInode::load(&self.dev, ino)
642 }
643
644 pub fn create_directory(
646 &self,
647 parent: &mut BlkInode,
648 name: &str,
649 ) -> Result<BlkInode, FileError> {
650 validate_entry_name(name)?;
651 match parent.lookup(name) {
652 Ok(_) => return Err(FileError::AlreadyExists),
653 Err(FileError::NotFound) => {}
654 Err(e) => return Err(e),
655 }
656 let ino = self.alloc_ino()?;
657 let disk = DiskInode {
658 ino: ino as u32,
659 file_type: 2,
660 mode: 0o755,
661 size: 0,
662 created: 0,
663 modified: 0,
664 nlinks: 1,
665 blocks: [0u32; DIRECT_BLOCKS],
666 _reserved: [0u8; 6],
667 };
668 let buf = disk.block_bytes();
669 self.dev
670 .write_block(INODE_TABLE_START + ino * INODE_BLOCK_SIZE, &buf)?;
671 parent.add_entry(name, ino)?;
672 self.record_inode_allocated(ino)?;
673 BlkInode::load(&self.dev, ino)
674 }
675
676 pub fn lookup(&self, parent: &BlkInode, name: &str) -> Result<BlkInode, FileError> {
678 let ino = parent.lookup(name)?;
679 BlkInode::load(&self.dev, ino)
680 }
681
682 pub fn open_file(&self, inode: BlkInode) -> Result<BlkFile, FileError> {
684 if inode.file_type() != FileType::RegularFile {
685 return Err(FileError::IsDirectory);
686 }
687 Ok(BlkFile::new(inode))
688 }
689}