1use crate::errno;
7use crate::serial_println;
8use crate::syscall::user_ptr;
9use alloc::string::String;
10use alloc::sync::Arc;
11use alloc::vec::Vec;
12use lazy_static::lazy_static;
13use spin::Mutex;
14
15use crate::fs::{
16 BlkFsMountMode, BlkFsMountOptions, BlockCache, BlockDeviceHandle, DummyBlockDev, File,
17 FS_MANAGER, GLOBAL_FD_TABLE,
18};
19
20pub mod open_flags {
23 pub const O_RDONLY: usize = 0;
24 pub const O_WRONLY: usize = 1;
25 pub const O_RDWR: usize = 2;
26 pub const O_CREAT: usize = 0x40;
27 pub const O_TRUNC: usize = 0x200;
28 pub const O_APPEND: usize = 0x400;
29}
30
31lazy_static! {
32 static ref SYSCALL_MOUNT_DEVICES: Mutex<Vec<MountDeviceSlot>> = Mutex::new(Vec::new());
33}
34
35const DEFAULT_DUMMY_MOUNT_BLOCKS: usize = crate::fs::BLKFS_MIN_BLOCKS * 2;
36const MAX_DUMMY_MOUNT_BLOCKS: usize = crate::fs::BLKFS_MIN_BLOCKS * 64;
37const MAX_SYSCALL_MOUNT_DEVICE_SLOTS: usize = 16;
38
39#[derive(Clone, Copy, PartialEq, Eq)]
40enum MountDeviceSelector {
41 Auto,
42 Virtio,
43 Dummy { blocks: usize },
44}
45
46struct MountRequest {
47 path: String,
48 device: MountDeviceSelector,
49 options: BlkFsMountOptions,
50}
51
52struct MountDeviceSlot {
53 mount_path: String,
54 selector: MountDeviceSelector,
55 virtio_backed: bool,
56 dev: BlockDeviceHandle,
57}
58
59enum MountDeviceSlotChange {
60 Unchanged,
61 Inserted {
62 mount_path: String,
63 },
64 Replaced {
65 mount_path: String,
66 selector: MountDeviceSelector,
67 virtio_backed: bool,
68 dev: BlockDeviceHandle,
69 },
70}
71
72fn parse_mount_request(raw: &str) -> Result<MountRequest, &'static str> {
73 let trimmed = raw.trim();
74 if trimmed.is_empty() {
75 return Err("Mount request is empty");
76 }
77
78 let (path_part, options_part) = match trimmed.split_once('?') {
79 Some((path, options)) => (path.trim(), Some(options)),
80 None => (trimmed, None),
81 };
82 if path_part.is_empty() {
83 return Err("Mount path is empty");
84 }
85 let mount_path = normalize_syscall_mount_path(path_part)?;
86
87 let mut device = MountDeviceSelector::Auto;
88 let mut dummy_blocks: Option<usize> = None;
89 let mut options = BlkFsMountOptions::default();
90
91 if let Some(option_text) = options_part {
92 for pair in option_text.split('&') {
93 if pair.is_empty() {
94 continue;
95 }
96 let (key, value) = pair
97 .split_once('=')
98 .ok_or("Mount option must be key=value")?;
99 match key {
100 "device" | "source" => {
101 device = match value {
102 "auto" => MountDeviceSelector::Auto,
103 "virtio" | "virtio-blk" => MountDeviceSelector::Virtio,
104 "dummy" | "ram" => MountDeviceSelector::Dummy {
105 blocks: DEFAULT_DUMMY_MOUNT_BLOCKS,
106 },
107 _ => return Err("Unsupported mount device"),
108 };
109 }
110 "blocks" => {
111 dummy_blocks = Some(parse_dummy_blocks(value)?);
112 }
113 "mode" => {
114 options.mode = parse_mount_mode(value)?;
115 }
116 "format" => {
117 options.mode = parse_format_option(value)?;
118 }
119 _ => return Err("Unsupported mount option"),
120 }
121 }
122 }
123
124 if let Some(blocks) = dummy_blocks {
125 device = match device {
126 MountDeviceSelector::Auto | MountDeviceSelector::Dummy { .. } => {
127 MountDeviceSelector::Dummy { blocks }
128 }
129 MountDeviceSelector::Virtio => {
130 return Err("blocks option requires dummy mount device");
131 }
132 };
133 }
134
135 Ok(MountRequest {
136 path: mount_path,
137 device,
138 options,
139 })
140}
141
142fn normalize_syscall_mount_path(path: &str) -> Result<String, &'static str> {
143 let trimmed = path.trim();
144 if !trimmed.starts_with('/') {
145 return Err("Mount path must be absolute");
146 }
147
148 let dir_name = trimmed.trim_matches('/');
149 if dir_name.is_empty() {
150 return Err("Cannot mount over root");
151 }
152 if dir_name.contains('/') {
153 return Err("Nested mount paths are not supported");
154 }
155
156 let mut mount_path = String::from("/");
157 mount_path.push_str(dir_name);
158 Ok(mount_path)
159}
160
161fn parse_dummy_blocks(raw: &str) -> Result<usize, &'static str> {
162 let blocks = raw
163 .parse::<usize>()
164 .map_err(|_| "Invalid dummy block count")?;
165 if blocks < crate::fs::BLKFS_MIN_BLOCKS {
166 return Err("Dummy block device is too small for BlkFS");
167 }
168 if blocks > MAX_DUMMY_MOUNT_BLOCKS {
169 return Err("Dummy block device is too large for teaching mount");
170 }
171 Ok(blocks)
172}
173
174fn parse_mount_mode(raw: &str) -> Result<BlkFsMountMode, &'static str> {
175 match raw {
176 "open-or-create" | "auto" => Ok(BlkFsMountMode::OpenOrCreate),
177 "open-only" | "open" | "ro-open" => Ok(BlkFsMountMode::OpenOnly),
178 "format" | "create" => Ok(BlkFsMountMode::Format),
179 _ => Err("Unsupported BlkFS mount mode"),
180 }
181}
182
183fn parse_format_option(raw: &str) -> Result<BlkFsMountMode, &'static str> {
184 match raw {
185 "always" | "true" | "1" => Ok(BlkFsMountMode::Format),
186 "never" | "false" | "0" => Ok(BlkFsMountMode::OpenOnly),
187 "auto" => Ok(BlkFsMountMode::OpenOrCreate),
188 _ => Err("Unsupported format policy"),
189 }
190}
191
192fn create_mount_device(
193 selector: MountDeviceSelector,
194) -> Result<(BlockDeviceHandle, bool), &'static str> {
195 let mut virtio_backed = false;
196 let raw: BlockDeviceHandle = match selector {
197 MountDeviceSelector::Auto => {
198 if let Some(virtio) = crate::block::VirtioBlkDev::probe() {
199 virtio_backed = true;
200 Arc::new(virtio)
201 } else {
202 Arc::new(DummyBlockDev::new(DEFAULT_DUMMY_MOUNT_BLOCKS))
203 }
204 }
205 MountDeviceSelector::Virtio => {
206 let virtio =
207 crate::block::VirtioBlkDev::probe().ok_or("VirtIO block device not found")?;
208 virtio_backed = true;
209 Arc::new(virtio)
210 }
211 MountDeviceSelector::Dummy { blocks } => Arc::new(DummyBlockDev::new(blocks)),
212 };
213 Ok((Arc::new(BlockCache::new(raw)), virtio_backed))
214}
215
216fn device_for_mount_request(
217 request: &MountRequest,
218) -> Result<(BlockDeviceHandle, bool, MountDeviceSlotChange), &'static str> {
219 {
220 let devices = SYSCALL_MOUNT_DEVICES.lock();
221 if let Some(slot) = devices.iter().find(|slot| slot.mount_path == request.path) {
222 if slot.selector == request.device {
223 return Ok((
224 Arc::clone(&slot.dev),
225 slot.virtio_backed,
226 MountDeviceSlotChange::Unchanged,
227 ));
228 }
229 } else if devices.len() >= MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
230 return Err("Too many syscall-managed mount devices");
231 }
232 }
233
234 let (dev, virtio_backed) = create_mount_device(request.device)?;
235
236 let mut devices = SYSCALL_MOUNT_DEVICES.lock();
237 if let Some(slot) = devices
238 .iter_mut()
239 .find(|slot| slot.mount_path == request.path)
240 {
241 if slot.selector == request.device {
242 return Ok((
243 Arc::clone(&slot.dev),
244 slot.virtio_backed,
245 MountDeviceSlotChange::Unchanged,
246 ));
247 }
248 let change = MountDeviceSlotChange::Replaced {
249 mount_path: request.path.clone(),
250 selector: slot.selector,
251 virtio_backed: slot.virtio_backed,
252 dev: Arc::clone(&slot.dev),
253 };
254 slot.selector = request.device;
255 slot.virtio_backed = virtio_backed;
256 slot.dev = Arc::clone(&dev);
257 return Ok((dev, virtio_backed, change));
258 }
259
260 if devices.len() >= MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
261 return Err("Too many syscall-managed mount devices");
262 }
263 devices.push(MountDeviceSlot {
264 mount_path: request.path.clone(),
265 selector: request.device,
266 virtio_backed,
267 dev: Arc::clone(&dev),
268 });
269 Ok((
270 dev,
271 virtio_backed,
272 MountDeviceSlotChange::Inserted {
273 mount_path: request.path.clone(),
274 },
275 ))
276}
277
278fn rollback_mount_device_slot(change: MountDeviceSlotChange) {
279 match change {
280 MountDeviceSlotChange::Unchanged => {}
281 MountDeviceSlotChange::Inserted { mount_path } => {
282 let mut devices = SYSCALL_MOUNT_DEVICES.lock();
283 devices.retain(|slot| slot.mount_path != mount_path);
284 }
285 MountDeviceSlotChange::Replaced {
286 mount_path,
287 selector,
288 virtio_backed,
289 dev,
290 } => {
291 let mut devices = SYSCALL_MOUNT_DEVICES.lock();
292 if let Some(slot) = devices
293 .iter_mut()
294 .find(|slot| slot.mount_path == mount_path)
295 {
296 slot.selector = selector;
297 slot.virtio_backed = virtio_backed;
298 slot.dev = dev;
299 } else if devices.len() < MAX_SYSCALL_MOUNT_DEVICE_SLOTS {
300 devices.push(MountDeviceSlot {
301 mount_path,
302 selector,
303 virtio_backed,
304 dev,
305 });
306 }
307 }
308 }
309}
310
311fn effective_mount_options(options: BlkFsMountOptions, virtio_backed: bool) -> BlkFsMountOptions {
312 if virtio_backed && options.mode != BlkFsMountMode::Format {
313 BlkFsMountOptions::open_only()
314 } else {
315 options
316 }
317}
318
319fn file_for_fd(fd: usize, syscall: &str) -> Result<Arc<Mutex<dyn File>>, errno::Errno> {
320 let fd_table = GLOBAL_FD_TABLE.lock();
321 match fd_table.get(fd) {
322 Some(file) => Ok(file),
323 None => {
324 serial_println!("[SYSCALL] {}: invalid fd={}", syscall, fd);
325 Err(errno::EBADF)
326 }
327 }
328}
329
330pub fn read_c_string(ptr: usize) -> Option<String> {
341 user_ptr::read_raw_c_string(ptr).ok()
342}
343
344pub fn sys_read(fd: usize, buf: usize, len: usize) -> isize {
347 serial_println!(
348 "[SYSCALL] sys_read: fd={}, buf=0x{:x}, len={}",
349 fd,
350 buf,
351 len
352 );
353
354 if len == 0 {
355 return 0;
356 }
357 if buf == 0 {
358 return errno::EINVAL;
359 }
360
361 if fd == 0 {
363 let ch = loop {
364 if let Some(c) = crate::task::keyboard::try_pop_char() {
365 break c;
366 }
367 let ret: isize;
368 unsafe {
369 core::arch::asm!(
370 "li a7, 2",
371 "ecall",
372 "mv {}, a0",
373 out(reg) ret,
374 options(nostack)
375 );
376 }
377 if ret >= 0 {
378 break ret as u8;
379 }
380 riscv::asm::wfi();
381 };
382 if user_ptr::raw_copy_to_user(buf, &[ch]).is_err() {
383 return errno::EFAULT;
384 }
385 return 1;
386 }
387
388 let file = match file_for_fd(fd, "sys_read") {
389 Ok(file) => file,
390 Err(errno) => return errno,
391 };
392
393 let capped = core::cmp::min(len, user_ptr::MAX_USER_COPY_LEN);
394 let mut kernel_buf = alloc::vec![0u8; capped];
395 let n = match file.lock().read(&mut kernel_buf) {
396 Ok(n) => n,
397 Err(e) => {
398 serial_println!("[SYSCALL] sys_read: read failed: {:?}", e);
399 return errno::from_file_error(e);
400 }
401 };
402
403 if user_ptr::raw_copy_to_user(buf, &kernel_buf[..n]).is_err() {
404 return errno::EFAULT;
405 }
406
407 serial_println!("[SYSCALL] sys_read: success, read {} bytes", n);
408 n as isize
409}
410
411pub fn sys_write(fd: usize, buf: *const u8, len: usize) -> isize {
412 serial_println!(
413 "[SYSCALL] sys_write: fd={}, buf=0x{:x}, len={}",
414 fd,
415 buf as usize,
416 len
417 );
418
419 if len == 0 {
420 return 0;
421 }
422 if buf.is_null() {
423 return errno::EINVAL;
424 }
425
426 if fd == 1 || fd == 2 {
428 let kernel_buf = match user_ptr::raw_copy_from_user(buf, len) {
429 Ok(bytes) => bytes,
430 Err(errno) => return errno,
431 };
432 crate::serial::write_bytes(&kernel_buf);
433 return kernel_buf.len() as isize;
434 }
435
436 let file = match file_for_fd(fd, "sys_write") {
437 Ok(file) => file,
438 Err(errno) => return errno,
439 };
440
441 let kernel_buf = match user_ptr::raw_copy_from_user(buf, len) {
442 Ok(bytes) => bytes,
443 Err(errno) => return errno,
444 };
445
446 let n = match file.lock().write(&kernel_buf) {
447 Ok(n) => n,
448 Err(e) => {
449 serial_println!("[SYSCALL] sys_write: write failed: {:?}", e);
450 return errno::from_file_error(e);
451 }
452 };
453
454 serial_println!("[SYSCALL] sys_write: success, wrote {} bytes", n);
455 n as isize
456}
457
458pub fn sys_open(path: usize, flags: usize) -> isize {
459 serial_println!("[SYSCALL] sys_open: path=0x{:x}, flags=0x{:x}", path, flags);
460
461 let path_str = match read_c_string(path) {
462 Some(s) => s,
463 None => {
464 serial_println!("[SYSCALL] sys_open: invalid path pointer");
465 return errno::EFAULT;
466 }
467 };
468 serial_println!("[SYSCALL] sys_open: resolved path='{}'", path_str);
469
470 let file: Arc<Mutex<dyn File>> = match crate::fs::vfs::open_file(&path_str) {
471 Ok(f) => f,
472 Err(_) if (flags & open_flags::O_CREAT) != 0 => {
473 match crate::fs::vfs::create_file(&path_str) {
474 Ok(f) => f,
475 Err(e) => {
476 serial_println!("[SYSCALL] sys_open: create failed: {:?}", e);
477 return errno::from_file_error(e);
478 }
479 }
480 }
481 Err(e) => {
482 serial_println!("[SYSCALL] sys_open: open failed: {:?}", e);
483 return errno::from_file_error(e);
484 }
485 };
486
487 let fd = match GLOBAL_FD_TABLE.lock().alloc(file) {
488 Some(fd) => fd,
489 None => {
490 serial_println!("[SYSCALL] sys_open: no free fd");
491 return errno::ENFILE;
492 }
493 };
494
495 serial_println!("[SYSCALL] sys_open: success, fd={}, path={}", fd, path_str);
496 fd as isize
497}
498
499pub fn sys_close(fd: usize) -> isize {
500 serial_println!("[SYSCALL] sys_close: fd={}", fd);
501
502 if GLOBAL_FD_TABLE.lock().dealloc(fd) {
503 serial_println!("[SYSCALL] sys_close: success");
504 0
505 } else {
506 serial_println!("[SYSCALL] sys_close: invalid fd={}", fd);
507 errno::EBADF
508 }
509}
510
511pub fn sys_mkdir(path: usize) -> isize {
512 serial_println!("[SYSCALL] sys_mkdir: path=0x{:x}", path);
513
514 let path_str = match read_c_string(path) {
515 Some(s) => s,
516 None => {
517 serial_println!("[SYSCALL] sys_mkdir: invalid path pointer");
518 return -1;
519 }
520 };
521
522 match crate::fs::vfs::create_dir(&path_str) {
523 Ok(()) => {
524 serial_println!("[SYSCALL] sys_mkdir: success, created '{}'", path_str);
525 0
526 }
527 Err(e) => {
528 serial_println!("[SYSCALL] sys_mkdir: failed: {:?}", e);
529 errno::from_file_error(e)
530 }
531 }
532}
533
534pub fn sys_exit(exit_code: i32) -> isize {
537 let _ = exit_code;
538 sys_process_requires_trap_frame("exit")
539}
540
541pub fn sys_getpid() -> isize {
542 1
543}
544
545pub fn sys_process_requires_trap_frame(name: &str) -> isize {
555 serial_println!(
556 "[SYSCALL] sys_{} requires trap-frame process path; direct dispatcher is unsupported",
557 name
558 );
559 errno::ENOSYS
560}
561
562pub fn sys_fork() -> isize {
563 sys_process_requires_trap_frame("fork")
564}
565
566pub fn sys_exec(path: usize) -> isize {
567 let _ = path;
568 sys_process_requires_trap_frame("exec")
569}
570
571pub fn sys_wait(exit_code_ptr: usize) -> isize {
572 let _ = exit_code_ptr;
573 sys_process_requires_trap_frame("wait")
574}
575
576pub fn sys_mount(path: usize) -> isize {
579 let path_str = match read_c_string(path) {
580 Some(s) => s,
581 None => return -1,
582 };
583 serial_println!("[SYSCALL] mount: path={}", path_str);
584 let request = match parse_mount_request(&path_str) {
585 Ok(request) => request,
586 Err(e) => {
587 serial_println!("[SYSCALL] mount: invalid request - {}", e);
588 return errno::EINVAL;
589 }
590 };
591 let (dev, virtio_backed, slot_change) = match device_for_mount_request(&request) {
592 Ok(device) => device,
593 Err(e) => {
594 serial_println!("[SYSCALL] mount: device selection failed - {}", e);
595 return errno::EINVAL;
596 }
597 };
598 let options = effective_mount_options(request.options, virtio_backed);
599 let mut mgr = FS_MANAGER.lock();
600 match mgr.mount_blkfs_with_options(&request.path, dev, options) {
601 Ok(()) => {
602 serial_println!("[SYSCALL] mount: {} mounted", request.path);
603 0
604 }
605 Err(e) => {
606 rollback_mount_device_slot(slot_change);
607 serial_println!("[SYSCALL] mount: failed - {}", e);
608 errno::EINVAL
609 }
610 }
611}
612
613pub fn sys_umount(path: usize) -> isize {
614 let path_str = match read_c_string(path) {
615 Some(s) => s,
616 None => return -1,
617 };
618 serial_println!("[SYSCALL] umount: path={}", path_str);
619 let mut mgr = FS_MANAGER.lock();
620 match mgr.umount(&path_str) {
621 Ok(()) => {
622 drop(mgr);
623 serial_println!("[SYSCALL] umount: {} unmounted", path_str);
624 0
625 }
626 Err(e) => {
627 serial_println!("[SYSCALL] umount: failed - {}", e);
628 -1
629 }
630 }
631}
632
633use crate::fs::SeekFrom;
636
637pub fn sys_lseek(fd: usize, offset: isize, whence: usize) -> isize {
638 let pos = match whence {
639 0 => SeekFrom::Start(offset as usize),
640 1 => SeekFrom::Current(offset),
641 2 => SeekFrom::End(offset),
642 _ => return -1,
643 };
644 let file = match file_for_fd(fd, "sys_lseek") {
645 Ok(file) => file,
646 Err(_) => return -1,
647 };
648 let result = file.lock().seek(pos);
649 match result {
650 Ok(new_offset) => new_offset as isize,
651 Err(_) => -1,
652 }
653}
654
655pub fn sys_unlink(path: usize) -> isize {
656 let path_str = match read_c_string(path) {
657 Some(s) => s,
658 None => return -1,
659 };
660 serial_println!("[SYSCALL] unlink: path={}", path_str);
661 match crate::fs::remove_file(&path_str) {
662 Ok(()) => 0,
663 Err(e) => {
664 serial_println!("[SYSCALL] unlink: failed - {}", e);
665 -1
666 }
667 }
668}
669
670pub fn sys_stat(path: usize, buf: usize) -> isize {
671 let path_str = match read_c_string(path) {
672 Some(s) => s,
673 None => return -1,
674 };
675 let meta = match crate::fs::stat_path(&path_str) {
676 Ok(m) => m,
677 Err(e) => {
678 serial_println!("[SYSCALL] stat: failed for {} - {}", path_str, e);
679 return -1;
680 }
681 };
682 if buf == 0 {
683 return -1;
684 }
685 let st = Stat {
686 st_dev: 0,
687 st_ino: 0,
688 st_mode: meta.mode,
689 st_nlink: 1,
690 st_uid: 0,
691 st_gid: 0,
692 st_rdev: 0,
693 __pad1: 0,
694 st_size: meta.size as u64,
695 st_blksize: 512,
696 __pad2: 0,
697 st_blocks: (meta.size as u64).div_ceil(512),
698 };
699 if user_ptr::raw_write_value(buf, st).is_err() {
700 return -1;
701 }
702 0
703}
704
705pub fn sys_getdents(fd_or_path: usize, buf: usize, len: usize) -> isize {
706 if buf == 0 || len == 0 {
707 return -1;
708 }
709 let path_str = match read_c_string(fd_or_path) {
710 Some(s) => s,
711 None => return -1,
712 };
713 let entries = match crate::fs::readdir_path(&path_str) {
714 Ok(v) => v,
715 Err(e) => {
716 serial_println!("[SYSCALL] getdents: failed for {} - {}", path_str, e);
717 return -1;
718 }
719 };
720 let mut out = alloc::vec::Vec::new();
721 for name in &entries {
722 let line = name.as_bytes();
723 if out.len() + line.len() + 1 > len {
724 break;
725 }
726 out.extend_from_slice(line);
727 out.push(b'\n');
728 }
729 if user_ptr::raw_copy_to_user(buf, &out).is_err() {
730 return -1;
731 }
732 out.len() as isize
733}
734
735pub fn sys_dup2(old_fd: usize, new_fd: usize) -> isize {
736 let mut fd_table = GLOBAL_FD_TABLE.lock();
737 match fd_table.dup2(old_fd, new_fd) {
738 Some(fd) => fd as isize,
739 None => -1,
740 }
741}
742
743use crate::fs::pipe::make_pipe;
746
747pub fn sys_pipe(fds_ptr: usize) -> isize {
748 if fds_ptr == 0 {
749 return -1;
750 }
751 let (read_end, write_end) = make_pipe();
752 let read_arc = alloc::sync::Arc::new(spin::Mutex::new(read_end));
753 let write_arc = alloc::sync::Arc::new(spin::Mutex::new(write_end));
754 let mut fd_table = GLOBAL_FD_TABLE.lock();
755 let fd0 = match fd_table.alloc(read_arc) {
756 Some(fd) => fd as i32,
757 None => return -1,
758 };
759 let fd1 = match fd_table.alloc(write_arc) {
760 Some(fd) => fd as i32,
761 None => {
762 fd_table.dealloc(fd0 as usize);
763 return -1;
764 }
765 };
766 drop(fd_table);
767 if user_ptr::raw_write_values(fds_ptr, &[fd0, fd1]).is_err() {
768 let mut fd_table = GLOBAL_FD_TABLE.lock();
769 fd_table.dealloc(fd0 as usize);
770 fd_table.dealloc(fd1 as usize);
771 return -1;
772 }
773 0
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 fn clear_mount_devices() {
781 SYSCALL_MOUNT_DEVICES.lock().clear();
782 }
783
784 fn slot_count() -> usize {
785 SYSCALL_MOUNT_DEVICES.lock().len()
786 }
787
788 #[test_case]
789 fn mount_request_normalizes_slot_path_before_device_selection() {
790 let request = parse_mount_request(" ///mnt/?device=dummy&blocks=512&mode=open-only")
791 .expect("normalized mount request");
792 assert_eq!(request.path.as_str(), "/mnt");
793 assert!(request.device == MountDeviceSelector::Dummy { blocks: 512 });
794 assert_eq!(request.options.mode, BlkFsMountMode::OpenOnly);
795
796 assert_eq!(
797 parse_mount_request("/mnt/data").err(),
798 Some("Nested mount paths are not supported")
799 );
800 assert_eq!(
801 parse_mount_request("/").err(),
802 Some("Cannot mount over root")
803 );
804 }
805
806 #[test_case]
807 fn mount_request_blocks_option_is_dummy_only_and_order_independent() {
808 assert_eq!(
809 parse_mount_request("/mnt?device=virtio&blocks=512").err(),
810 Some("blocks option requires dummy mount device")
811 );
812 assert_eq!(
813 parse_mount_request("/mnt?blocks=512&device=virtio").err(),
814 Some("blocks option requires dummy mount device")
815 );
816
817 let request = parse_mount_request("/mnt?blocks=512&device=dummy").expect("dummy request");
818 assert!(request.device == MountDeviceSelector::Dummy { blocks: 512 });
819
820 let request = parse_mount_request("/mnt?blocks=640").expect("implicit dummy request");
821 assert!(request.device == MountDeviceSelector::Dummy { blocks: 640 });
822 }
823
824 #[test_case]
825 fn virtio_backed_mounts_do_not_open_or_create_unless_format_is_explicit() {
826 assert_eq!(
827 effective_mount_options(BlkFsMountOptions::open_or_create(), true).mode,
828 BlkFsMountMode::OpenOnly
829 );
830 assert_eq!(
831 effective_mount_options(BlkFsMountOptions::open_only(), true).mode,
832 BlkFsMountMode::OpenOnly
833 );
834 assert_eq!(
835 effective_mount_options(BlkFsMountOptions::format(), true).mode,
836 BlkFsMountMode::Format
837 );
838 assert_eq!(
839 effective_mount_options(BlkFsMountOptions::open_or_create(), false).mode,
840 BlkFsMountMode::OpenOrCreate
841 );
842 }
843
844 #[test_case]
845 fn mount_device_slot_insert_and_replace_changes_can_be_rolled_back() {
846 clear_mount_devices();
847 let original =
848 parse_mount_request("/slot?device=dummy&blocks=512").expect("original request");
849 let replacement =
850 parse_mount_request("/slot/?device=dummy&blocks=640").expect("replacement request");
851
852 let (_, _, inserted) = device_for_mount_request(&original).expect("insert slot");
853 assert_eq!(slot_count(), 1);
854
855 let (_, _, replaced) = device_for_mount_request(&replacement).expect("replace slot");
856 assert_eq!(slot_count(), 1);
857 {
858 let devices = SYSCALL_MOUNT_DEVICES.lock();
859 let slot = devices
860 .iter()
861 .find(|slot| slot.mount_path == "/slot")
862 .expect("slot after replacement");
863 assert!(slot.selector == replacement.device);
864 }
865
866 rollback_mount_device_slot(replaced);
867 {
868 let devices = SYSCALL_MOUNT_DEVICES.lock();
869 let slot = devices
870 .iter()
871 .find(|slot| slot.mount_path == "/slot")
872 .expect("slot after rollback");
873 assert!(slot.selector == original.device);
874 }
875
876 rollback_mount_device_slot(inserted);
877 assert_eq!(slot_count(), 0);
878 clear_mount_devices();
879 }
880
881 #[test_case]
882 fn mount_device_slots_are_retained_for_remount_and_rollback_is_explicit() {
883 clear_mount_devices();
884 let request = parse_mount_request("/norm?device=dummy&blocks=512").expect("request");
885 let (_, _, inserted) = device_for_mount_request(&request).expect("insert slot");
886 assert_eq!(slot_count(), 1);
887
888 let (_, _, unchanged) = device_for_mount_request(&request).expect("reuse retained slot");
891 assert_eq!(slot_count(), 1);
892 assert!(matches!(unchanged, MountDeviceSlotChange::Unchanged));
893
894 rollback_mount_device_slot(inserted);
895 clear_mount_devices();
896 }
897}
898
899#[derive(Clone, Copy)]
901#[repr(C, packed)]
902struct Stat {
903 st_dev: u64,
904 st_ino: u64,
905 st_mode: u32,
906 st_nlink: u32,
907 st_uid: u32,
908 st_gid: u32,
909 st_rdev: u64,
910 __pad1: u64,
911 st_size: u64,
912 st_blksize: u32,
913 __pad2: u32,
914 st_blocks: u64,
915}