1use alloc::borrow::ToOwned;
2use alloc::boxed::Box;
3use alloc::ffi::CString;
4use alloc::string::String;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7use core::ffi::CStr;
8use core::marker::PhantomData;
9use core::mem::MaybeUninit;
10use core::sync::atomic::{AtomicU64, Ordering};
11use core::task::Poll;
12use core::{future, slice};
13
14use async_lock::Mutex;
15use embedded_io::{ErrorType, Read, Write};
16use fuse_abi::linux::*;
17
18#[cfg(not(feature = "pci"))]
19use crate::arch::kernel::mmio::get_filesystem_driver;
20use crate::drivers::fs::VirtioFsDriver;
21#[cfg(feature = "pci")]
22use crate::drivers::pci::get_filesystem_driver;
23use crate::drivers::virtio::virtqueue::error::VirtqError;
24use crate::errno::Errno;
25use crate::executor::block_on;
26use crate::fd::{Fd, PollEvent};
27use crate::fs::virtio_fs::ops::SetAttrValidFields;
28use crate::fs::{
29 self, AccessPermission, DirectoryEntry, FileAttr, NodeKind, ObjectInterface, OpenOption,
30 SeekWhence, VfsNode,
31};
32use crate::mm::device_alloc::DeviceAlloc;
33use crate::syscalls::DirentFormat;
34use crate::time::{time_t, timespec};
35use crate::{arch, io};
36
37const MAX_READ_LEN: usize = 1024 * 64;
42const MAX_WRITE_LEN: usize = 1024 * 64;
43
44const U64_SIZE: usize = size_of::<u64>();
45
46static NEXT_UNIQUE: AtomicU64 = AtomicU64::new(1);
48
49const S_IFLNK: u32 = 0o120_000;
50const S_IFMT: u32 = 0o170_000;
51
52pub(crate) trait VirtioFsInterface {
53 fn get_mount_point(&self) -> String;
54}
55
56pub(crate) mod ops {
57 #![allow(clippy::type_complexity)]
58 use alloc::boxed::Box;
59 use alloc::ffi::CString;
60 use core::fmt;
61
62 use fuse_abi::linux::*;
63
64 use super::Cmd;
65 use crate::fd::PollEvent;
66 use crate::fs::{FileAttr, SeekWhence};
67
68 #[repr(C)]
69 #[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
70 pub(crate) struct CreateOut {
71 pub entry: fuse_entry_out,
72 pub open: fuse_open_out,
73 }
74
75 pub(crate) trait Op {
76 const OP_CODE: fuse_opcode;
77
78 type InStruct: fmt::Debug;
79 type InPayload: ?Sized;
80 type OutStruct: fmt::Debug;
81 type OutPayload: ?Sized;
82 }
83
84 #[derive(Debug)]
85 pub(crate) struct Init;
86
87 impl Op for Init {
88 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_INIT;
89 type InStruct = fuse_init_in;
90 type InPayload = ();
91 type OutStruct = fuse_init_out;
92 type OutPayload = ();
93 }
94
95 impl Init {
96 pub(crate) fn create() -> (Cmd<Self>, u32) {
97 let cmd = Cmd::new(
98 FUSE_ROOT_ID,
99 fuse_init_in {
100 major: 7,
101 minor: 31,
102 ..Default::default()
103 },
104 );
105 (cmd, 0)
106 }
107 }
108
109 #[derive(Debug)]
110 pub(crate) struct Create;
111
112 impl Op for Create {
113 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_CREATE;
114 type InStruct = fuse_create_in;
115 type InPayload = CString;
116 type OutStruct = CreateOut;
117 type OutPayload = ();
118 }
119
120 impl Create {
121 #[allow(clippy::self_named_constructors)]
122 pub(crate) fn create(
123 parent: u64,
124 name: CString,
125 flags: u32,
126 mode: u32,
127 ) -> (Cmd<Self>, u32) {
128 let cmd = Cmd::with_cstring(
129 parent,
130 fuse_create_in {
131 flags,
132 mode,
133 ..Default::default()
134 },
135 name,
136 );
137 (cmd, 0)
138 }
139 }
140
141 #[derive(Debug)]
142 pub(crate) struct Open;
143
144 impl Op for Open {
145 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_OPEN;
146 type InStruct = fuse_open_in;
147 type InPayload = ();
148 type OutStruct = fuse_open_out;
149 type OutPayload = ();
150 }
151
152 impl Open {
153 pub(crate) fn create(nid: u64, flags: u32) -> (Cmd<Self>, u32) {
154 let cmd = Cmd::new(
155 nid,
156 fuse_open_in {
157 flags,
158 ..Default::default()
159 },
160 );
161 (cmd, 0)
162 }
163 }
164
165 #[derive(Debug)]
166 pub(crate) struct Write;
167
168 impl Op for Write {
169 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_WRITE;
170 type InStruct = fuse_write_in;
171 type InPayload = [u8];
172 type OutStruct = fuse_write_out;
173 type OutPayload = ();
174 }
175
176 impl Write {
177 pub(crate) fn create(nid: u64, fh: u64, buf: Box<[u8]>, offset: u64) -> (Cmd<Self>, u32) {
178 let cmd = Cmd::with_boxed_slice(
179 nid,
180 fuse_write_in {
181 fh,
182 offset,
183 size: buf.len().try_into().unwrap(),
184 ..Default::default()
185 },
186 buf,
187 );
188 (cmd, 0)
189 }
190 }
191
192 #[derive(Debug)]
193 pub(crate) struct Read;
194
195 impl Op for Read {
196 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_READ;
197 type InStruct = fuse_read_in;
198 type InPayload = ();
199 type OutStruct = ();
200 type OutPayload = [u8];
201 }
202
203 impl Read {
204 pub(crate) fn create(nid: u64, fh: u64, size: u32, offset: u64) -> (Cmd<Self>, u32) {
205 let cmd = Cmd::new(
206 nid,
207 fuse_read_in {
208 fh,
209 offset,
210 size,
211 ..Default::default()
212 },
213 );
214 (cmd, size)
215 }
216 }
217
218 #[derive(Debug)]
219 pub(crate) struct Lseek;
220
221 impl Op for Lseek {
222 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_LSEEK;
223 type InStruct = fuse_lseek_in;
224 type InPayload = ();
225 type OutStruct = fuse_lseek_out;
226 type OutPayload = ();
227 }
228
229 impl Lseek {
230 pub(crate) fn create(
231 nid: u64,
232 fh: u64,
233 offset: isize,
234 whence: SeekWhence,
235 ) -> (Cmd<Self>, u32) {
236 let cmd = Cmd::new(
237 nid,
238 fuse_lseek_in {
239 fh,
240 offset: i64::try_from(offset).unwrap() as u64,
241 whence: u8::from(whence).into(),
242 ..Default::default()
243 },
244 );
245 (cmd, 0)
246 }
247 }
248
249 #[derive(Debug)]
250 pub(crate) struct Getattr;
251
252 impl Op for Getattr {
253 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_GETATTR;
254 type InStruct = fuse_getattr_in;
255 type InPayload = ();
256 type OutStruct = fuse_attr_out;
257 type OutPayload = ();
258 }
259
260 impl Getattr {
261 pub(crate) fn create(nid: u64, fh: u64, getattr_flags: u32) -> (Cmd<Self>, u32) {
262 let cmd = Cmd::new(
263 nid,
264 fuse_getattr_in {
265 getattr_flags,
266 fh,
267 ..Default::default()
268 },
269 );
270 (cmd, 0)
271 }
272 }
273
274 #[derive(Debug)]
275 pub(crate) struct Setattr;
276
277 impl Op for Setattr {
278 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_SETATTR;
279 type InStruct = fuse_setattr_in;
280 type InPayload = ();
281 type OutStruct = fuse_attr_out;
282 type OutPayload = ();
283 }
284
285 bitflags! {
286 #[derive(Debug, Copy, Clone, Default)]
287 pub struct SetAttrValidFields: u32 {
288 const FATTR_MODE = FATTR_MODE;
289 const FATTR_UID = FATTR_UID;
290 const FATTR_GID = FATTR_GID;
291 const FATTR_SIZE = FATTR_SIZE;
292 const FATTR_ATIME = FATTR_ATIME;
293 const FATTR_MTIME = FATTR_MTIME;
294 const FATTR_FH = FATTR_FH;
295 const FATTR_ATIME_NOW = FATTR_ATIME_NOW;
296 const FATTR_MTIME_NOW = FATTR_MTIME_NOW;
297 const FATTR_LOCKOWNER = FATTR_LOCKOWNER;
298 const FATTR_CTIME = FATTR_CTIME;
299 const FATTR_KILL_SUIDGID = FATTR_KILL_SUIDGID;
300 }
301 }
302
303 impl Setattr {
304 pub(crate) fn create(
305 nid: u64,
306 fh: u64,
307 attr: FileAttr,
308 valid_attr: SetAttrValidFields,
309 ) -> (Cmd<Self>, u32) {
310 let cmd = Cmd::new(
311 nid,
312 fuse_setattr_in {
313 valid: valid_attr
314 .difference(
315 SetAttrValidFields::FATTR_LOCKOWNER,
317 )
318 .bits(),
319 padding: 0,
320 fh,
321
322 size: attr.st_size as u64,
324 atime: attr.st_atim.tv_sec as u64,
325 atimensec: attr.st_atim.tv_nsec as u32,
326 mtime: attr.st_ctim.tv_sec as u64,
327 mtimensec: attr.st_ctim.tv_nsec as u32,
328 ctime: attr.st_ctim.tv_sec as u64,
329 ctimensec: attr.st_ctim.tv_nsec as u32,
330 mode: attr.st_mode.bits(),
331 unused4: 0,
332 uid: attr.st_uid,
333 gid: attr.st_gid,
334 unused5: 0,
335
336 lock_owner: 0, },
338 );
339
340 (cmd, 0)
341 }
342 }
343
344 #[derive(Debug)]
345 pub(crate) struct Readlink;
346
347 impl Op for Readlink {
348 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_READLINK;
349 type InStruct = ();
350 type InPayload = ();
351 type OutStruct = ();
352 type OutPayload = [u8];
353 }
354
355 impl Readlink {
356 pub(crate) fn create(nid: u64, size: u32) -> (Cmd<Self>, u32) {
357 let cmd = Cmd::new(nid, ());
358 (cmd, size)
359 }
360 }
361
362 #[derive(Debug)]
363 pub(crate) struct Release;
364
365 impl Op for Release {
366 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_RELEASE;
367 type InStruct = fuse_release_in;
368 type InPayload = ();
369 type OutStruct = ();
370 type OutPayload = ();
371 }
372
373 impl Release {
374 pub(crate) fn create(nid: u64, fh: u64) -> (Cmd<Self>, u32) {
375 let cmd = Cmd::new(
376 nid,
377 fuse_release_in {
378 fh,
379 ..Default::default()
380 },
381 );
382 (cmd, 0)
383 }
384 }
385
386 #[derive(Debug)]
387 pub(crate) struct Fsync;
388
389 impl Op for Fsync {
390 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_FSYNC;
391 type InStruct = fuse_fsync_in;
392 type InPayload = ();
393 type OutStruct = ();
394 type OutPayload = ();
395 }
396
397 impl Fsync {
398 pub(crate) fn create(nid: u64, fh: u64, datasync: bool) -> (Cmd<Self>, u32) {
400 let cmd = Cmd::new(
401 nid,
402 fuse_fsync_in {
403 fh,
404 fsync_flags: if datasync { FUSE_FSYNC_FDATASYNC } else { 0 },
405 ..Default::default()
406 },
407 );
408 (cmd, 0)
409 }
410 }
411
412 #[derive(Debug)]
413 pub(crate) struct Poll;
414
415 impl Op for Poll {
416 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_POLL;
417 type InStruct = fuse_poll_in;
418 type InPayload = ();
419 type OutStruct = fuse_poll_out;
420 type OutPayload = ();
421 }
422
423 impl Poll {
424 pub(crate) fn create(nid: u64, fh: u64, kh: u64, event: PollEvent) -> (Cmd<Self>, u32) {
425 let cmd = Cmd::new(
426 nid,
427 fuse_poll_in {
428 fh,
429 kh,
430 events: event.bits() as u32,
431 ..Default::default()
432 },
433 );
434 (cmd, 0)
435 }
436 }
437
438 #[derive(Debug)]
439 pub(crate) struct Mkdir;
440
441 impl Op for Mkdir {
442 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_MKDIR;
443 type InStruct = fuse_mkdir_in;
444 type InPayload = CString;
445 type OutStruct = fuse_entry_out;
446 type OutPayload = ();
447 }
448
449 impl Mkdir {
450 pub(crate) fn create(parent: u64, name: CString, mode: u32) -> (Cmd<Self>, u32) {
451 let cmd = Cmd::with_cstring(
452 parent,
453 fuse_mkdir_in {
454 mode,
455 ..Default::default()
456 },
457 name,
458 );
459 (cmd, 0)
460 }
461 }
462
463 #[derive(Debug)]
464 pub(crate) struct Unlink;
465
466 impl Op for Unlink {
467 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_UNLINK;
468 type InStruct = ();
469 type InPayload = CString;
470 type OutStruct = ();
471 type OutPayload = ();
472 }
473
474 impl Unlink {
475 pub(crate) fn create(parent: u64, name: CString) -> (Cmd<Self>, u32) {
476 let cmd = Cmd::with_cstring(parent, (), name);
477 (cmd, 0)
478 }
479 }
480
481 #[derive(Debug)]
482 pub(crate) struct Rmdir;
483
484 impl Op for Rmdir {
485 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_RMDIR;
486 type InStruct = ();
487 type InPayload = CString;
488 type OutStruct = ();
489 type OutPayload = ();
490 }
491
492 impl Rmdir {
493 pub(crate) fn create(parent: u64, name: CString) -> (Cmd<Self>, u32) {
494 let cmd = Cmd::with_cstring(parent, (), name);
495 (cmd, 0)
496 }
497 }
498
499 #[derive(Debug)]
500 pub(crate) struct Lookup;
501
502 impl Op for Lookup {
503 const OP_CODE: fuse_opcode = fuse_opcode::FUSE_LOOKUP;
504 type InStruct = ();
505 type InPayload = CString;
506 type OutStruct = fuse_entry_out;
507 type OutPayload = ();
508 }
509
510 impl Lookup {
511 pub(crate) fn create(parent: u64, name: CString) -> (Cmd<Self>, u32) {
512 let cmd = Cmd::with_cstring(parent, (), name);
513 (cmd, 0)
514 }
515 }
516}
517
518impl From<fuse_attr> for FileAttr {
519 fn from(attr: fuse_attr) -> FileAttr {
520 FileAttr {
521 st_ino: attr.ino,
522 st_nlink: attr.nlink.into(),
523 st_mode: AccessPermission::from_bits_retain(attr.mode),
524 st_uid: attr.uid,
525 st_gid: attr.gid,
526 st_rdev: attr.rdev.into(),
527 st_size: attr.size.try_into().unwrap(),
528 st_blksize: attr.blksize.into(),
529 st_blocks: attr.blocks.try_into().unwrap(),
530 st_atim: timespec {
531 tv_sec: attr.atime as time_t,
532 tv_nsec: attr.atimensec as i32,
533 },
534 st_mtim: timespec {
535 tv_sec: attr.mtime as time_t,
536 tv_nsec: attr.mtimensec as i32,
537 },
538 st_ctim: timespec {
539 tv_sec: attr.ctime as time_t,
540 tv_nsec: attr.ctimensec as i32,
541 },
542 ..Default::default()
543 }
544 }
545}
546
547#[repr(C)]
548#[derive(Debug)]
549pub(crate) struct CmdHeader<O: ops::Op> {
550 pub in_header: fuse_in_header,
551 op_header: O::InStruct,
552}
553
554impl<O: ops::Op> CmdHeader<O>
555where
556 O: ops::Op<InPayload = ()>,
557{
558 fn new(nodeid: u64, op_header: O::InStruct) -> Self {
559 Self::with_payload_size(nodeid, op_header, 0)
560 }
561}
562
563impl<O: ops::Op> CmdHeader<O> {
564 fn with_payload_size(nodeid: u64, op_header: O::InStruct, len: usize) -> CmdHeader<O> {
565 CmdHeader {
566 in_header: fuse_in_header {
567 len: (size_of::<fuse_in_header>() + size_of::<O::InStruct>() + len)
569 .try_into()
570 .expect("The command is too large"),
571 opcode: O::OP_CODE.into(),
572 nodeid,
573 unique: NEXT_UNIQUE.fetch_add(1, Ordering::Relaxed),
575 ..Default::default()
576 },
577 op_header,
578 }
579 }
580}
581
582pub(crate) struct Cmd<O: ops::Op> {
583 pub headers: Box<CmdHeader<O>, DeviceAlloc>,
584 pub payload: Option<Vec<u8, DeviceAlloc>>,
585}
586
587impl<O: ops::Op> Cmd<O>
588where
589 O: ops::Op<InPayload = ()>,
590{
591 fn new(nodeid: u64, op_header: O::InStruct) -> Self {
592 Self {
593 headers: Box::new_in(CmdHeader::new(nodeid, op_header), DeviceAlloc),
594 payload: None,
595 }
596 }
597}
598
599impl<O: ops::Op> Cmd<O>
600where
601 O: ops::Op<InPayload = CString>,
602{
603 fn with_cstring(nodeid: u64, op_header: O::InStruct, cstring: CString) -> Self {
604 let cstring_bytes = cstring.into_bytes_with_nul().to_vec_in(DeviceAlloc);
605 Self {
606 headers: Box::new_in(
607 CmdHeader::with_payload_size(nodeid, op_header, cstring_bytes.len()),
608 DeviceAlloc,
609 ),
610 payload: Some(cstring_bytes),
611 }
612 }
613}
614
615impl<O: ops::Op> Cmd<O>
616where
617 O: ops::Op<InPayload = [u8]>,
618{
619 fn with_boxed_slice(nodeid: u64, op_header: O::InStruct, slice: Box<[u8]>) -> Self {
620 let mut device_slice = Vec::with_capacity_in(slice.len(), DeviceAlloc);
621 device_slice.extend_from_slice(&slice);
622 Self {
623 headers: Box::new_in(
624 CmdHeader::with_payload_size(nodeid, op_header, slice.len()),
625 DeviceAlloc,
626 ),
627 payload: Some(device_slice),
628 }
629 }
630}
631
632#[repr(C)]
633#[derive(Debug)]
634pub(crate) struct RspHeader<O: ops::Op, H = <O as ops::Op>::OutStruct> {
638 pub out_header: fuse_out_header,
639 op_header: H,
640 _phantom: PhantomData<O::OutStruct>,
641}
642
643#[derive(Debug)]
644pub(crate) struct Rsp<O: ops::Op> {
645 pub headers: Box<RspHeader<O>, DeviceAlloc>,
646 pub payload: Option<Vec<u8, DeviceAlloc>>,
647}
648
649#[derive(Debug)]
650pub(crate) enum VirtioFsError {
651 VirtqError(VirtqError),
652 IOError(Errno),
653}
654
655impl From<VirtqError> for VirtioFsError {
656 fn from(value: VirtqError) -> Self {
657 Self::VirtqError(value)
658 }
659}
660
661impl From<VirtioFsError> for Errno {
662 fn from(value: VirtioFsError) -> Self {
663 match value {
664 VirtioFsError::VirtqError(virtq_error) => virtq_error.into(),
665 VirtioFsError::IOError(io_error) => io_error,
666 }
667 }
668}
669
670fn lookup_entry(path: &str) -> io::Result<Option<fuse_entry_out>> {
675 let mut entry: Option<fuse_entry_out> = None;
676 for component in path.split('/').filter(|component| !component.is_empty()) {
677 let parent = entry.as_ref().map_or(FUSE_ROOT_ID, |entry| entry.nodeid);
678 let component = CString::new(component).map_err(|_| Errno::Inval)?;
679 let (cmd, rsp_payload_len) = ops::Lookup::create(parent, component);
680 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
681 entry = Some(rsp.headers.op_header);
682 }
683 Ok(entry)
684}
685
686fn lookup(path: &CStr) -> io::Result<u64> {
687 let path = path.to_str().map_err(|_| Errno::Inval)?;
688 Ok(lookup_entry(path)?.map_or(FUSE_ROOT_ID, |entry| entry.nodeid))
689}
690
691fn lookup_attr(path: &CStr) -> io::Result<(u64, fuse_attr)> {
692 let path = path.to_str().map_err(|_| Errno::Inval)?;
693 if let Some(entry) = lookup_entry(path)? {
694 return Ok((entry.nodeid, entry.attr));
695 }
696
697 let (cmd, rsp_payload_len) = ops::Getattr::create(FUSE_ROOT_ID, 0, 0);
698 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
699 Ok((FUSE_ROOT_ID, rsp.headers.op_header.attr))
700}
701
702fn resolve_parent(path: &CStr) -> io::Result<(u64, CString)> {
709 let path = path.to_str().map_err(|_| Errno::Inval)?;
710 let path = path.trim_end_matches('/');
711 let (parent, name) = path.rsplit_once('/').unwrap_or(("", path));
712 if name.is_empty() {
713 return Err(Errno::Inval);
714 }
715
716 let parent = lookup_entry(parent)?.map_or(FUSE_ROOT_ID, |entry| entry.nodeid);
717 Ok((parent, CString::new(name).map_err(|_| Errno::Inval)?))
718}
719
720fn readlink(nid: u64) -> io::Result<String> {
721 let len = MAX_READ_LEN as u32;
722 let (cmd, rsp_payload_len) = ops::Readlink::create(nid, len);
723 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
724 let len: usize = if rsp.headers.out_header.len as usize - size_of::<fuse_out_header>()
725 >= usize::try_from(len).unwrap()
726 {
727 len.try_into().unwrap()
728 } else {
729 (rsp.headers.out_header.len as usize) - size_of::<fuse_out_header>()
730 };
731
732 Ok(String::from_utf8(rsp.payload.unwrap()[..len].to_vec()).unwrap())
733}
734
735#[derive(Debug)]
736struct VirtioFsFileHandleInner {
737 fuse_nid: Option<u64>,
738 fuse_fh: Option<u64>,
739 offset: usize,
740}
741
742impl VirtioFsFileHandleInner {
743 pub fn new() -> Self {
744 Self {
745 fuse_nid: None,
746 fuse_fh: None,
747 offset: 0,
748 }
749 }
750
751 async fn poll(&self, events: PollEvent) -> io::Result<PollEvent> {
752 static KH: AtomicU64 = AtomicU64::new(0);
753 let kh = KH.fetch_add(1, Ordering::SeqCst);
754
755 future::poll_fn(|cx| {
756 let Some(nid) = self.fuse_nid else {
757 return Poll::Ready(Ok(PollEvent::POLLERR));
758 };
759
760 let Some(fh) = self.fuse_fh else {
761 return Poll::Ready(Ok(PollEvent::POLLERR));
762 };
763
764 let (cmd, rsp_payload_len) = ops::Poll::create(nid, fh, kh, events);
765 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
766
767 if rsp.headers.out_header.error < 0 {
768 return Poll::Ready(Err(Errno::Io));
769 }
770
771 let revents =
772 PollEvent::from_bits(i16::try_from(rsp.headers.op_header.revents).unwrap())
773 .unwrap();
774 if !revents.intersects(events)
775 && !revents
776 .intersects(PollEvent::POLLERR | PollEvent::POLLNVAL | PollEvent::POLLHUP)
777 {
778 cx.waker().wake_by_ref();
781 }
782 Poll::Ready(Ok(revents))
783 })
784 .await
785 }
786
787 fn lseek(&mut self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
788 debug!("virtio-fs lseek: offset: {offset}, whence: {whence:?}");
789
790 match whence {
796 SeekWhence::End | SeekWhence::Data | SeekWhence::Hole => {
797 let nid = self.fuse_nid.ok_or(Errno::Io)?;
798 let fh = self.fuse_fh.ok_or(Errno::Io)?;
799
800 let (cmd, rsp_payload_len) = ops::Lseek::create(nid, fh, offset, whence);
801 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
802
803 if rsp.headers.out_header.error < 0 {
804 return Err(Errno::Io);
805 }
806
807 let rsp_offset = rsp.headers.op_header.offset;
808 self.offset = rsp.headers.op_header.offset.try_into().unwrap();
809
810 Ok(rsp_offset.try_into().unwrap())
811 }
812 SeekWhence::Set => {
813 self.offset = offset.try_into().map_err(|_e| Errno::Inval)?;
814 Ok(self.offset as isize)
815 }
816 SeekWhence::Cur => {
817 self.offset = (self.offset as isize + offset)
818 .try_into()
819 .map_err(|_e| Errno::Inval)?;
820 Ok(self.offset as isize)
821 }
822 }
823 }
824
825 fn fstat(&mut self) -> io::Result<FileAttr> {
826 debug!("virtio-fs getattr");
827
828 let nid = self.fuse_nid.ok_or(Errno::Io)?;
829 let fh = self.fuse_fh.ok_or(Errno::Io)?;
830
831 let (cmd, rsp_payload_len) = ops::Getattr::create(nid, fh, FUSE_GETATTR_FH);
832 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
833
834 if rsp.headers.out_header.error < 0 {
835 return Err(Errno::Io);
836 }
837
838 Ok(rsp.headers.op_header.attr.into())
839 }
840
841 fn set_attr(&mut self, attr: FileAttr, valid: SetAttrValidFields) -> io::Result<FileAttr> {
842 debug!("virtio-fs setattr");
843
844 let nid = self.fuse_nid.ok_or(Errno::Io)?;
845 let fh = self.fuse_fh.ok_or(Errno::Io)?;
846
847 let (cmd, rsp_payload_len) = ops::Setattr::create(nid, fh, attr, valid);
848 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
849
850 if rsp.headers.out_header.error < 0 {
851 return Err(Errno::Io);
852 }
853
854 Ok(rsp.headers.op_header.attr.into())
855 }
856
857 fn fsync(&mut self) -> io::Result<()> {
858 debug!("virtio-fs fsync");
859
860 let nid = self.fuse_nid.ok_or(Errno::Io)?;
861 let fh = self.fuse_fh.ok_or(Errno::Io)?;
862
863 let (cmd, rsp_payload_len) = ops::Fsync::create(nid, fh, false);
864 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
865
866 fsync_result(rsp.headers.out_header.error)
867 }
868}
869
870fn fsync_result(error: i32) -> io::Result<()> {
876 match error {
877 0 => Ok(()),
878 error if error == -i32::from(Errno::Nosys) => Ok(()),
879 error => Err(Errno::try_from(-error).unwrap_or(Errno::Io)),
880 }
881}
882
883impl ErrorType for VirtioFsFileHandleInner {
884 type Error = Errno;
885}
886
887impl Read for VirtioFsFileHandleInner {
888 fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
889 let mut len = buf.len();
890 if len > MAX_READ_LEN {
891 debug!("Reading longer than max_read_len: {len}");
892 len = MAX_READ_LEN;
893 }
894
895 let nid = self.fuse_nid.ok_or(Errno::Io)?;
896 let fh = self.fuse_fh.ok_or(Errno::Io)?;
897
898 let (cmd, rsp_payload_len) =
899 ops::Read::create(nid, fh, len.try_into().unwrap(), self.offset as u64);
900 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
901 let len: usize =
902 if (rsp.headers.out_header.len as usize) - size_of::<fuse_out_header>() >= len {
903 len
904 } else {
905 (rsp.headers.out_header.len as usize) - size_of::<fuse_out_header>()
906 };
907 self.offset += len;
908
909 buf[..len].copy_from_slice(&rsp.payload.unwrap()[..len]);
910
911 Ok(len)
912 }
913}
914
915impl Write for VirtioFsFileHandleInner {
916 fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
917 debug!("virtio-fs write!");
918 let mut truncated_len = buf.len();
919 if truncated_len > MAX_WRITE_LEN {
920 debug!(
921 "Writing longer than max_write_len: {} > {}",
922 buf.len(),
923 MAX_WRITE_LEN
924 );
925 truncated_len = MAX_WRITE_LEN;
926 }
927
928 let nid = self.fuse_nid.ok_or(Errno::Io)?;
929 let fh = self.fuse_fh.ok_or(Errno::Io)?;
930
931 let truncated_buf = Box::<[u8]>::from(&buf[..truncated_len]);
932 let (cmd, rsp_payload_len) = ops::Write::create(nid, fh, truncated_buf, self.offset as u64);
933 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
934
935 if rsp.headers.out_header.error < 0 {
936 return Err(Errno::Io);
937 }
938
939 let rsp_size = rsp.headers.op_header.size;
940 let rsp_len: usize = if rsp_size > u32::try_from(truncated_len).unwrap() {
941 truncated_len
942 } else {
943 rsp_size.try_into().unwrap()
944 };
945 self.offset += rsp_len;
946 Ok(rsp_len)
947 }
948
949 fn flush(&mut self) -> Result<(), Self::Error> {
950 Ok(())
951 }
952}
953
954impl Drop for VirtioFsFileHandleInner {
955 fn drop(&mut self) {
956 let Some(fuse_nid) = self.fuse_nid else {
957 return;
958 };
959
960 let Some(fuse_fh) = self.fuse_fh else {
961 return;
962 };
963
964 let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
965 VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
966 }
967}
968
969pub struct VirtioFsFileHandle(Arc<Mutex<VirtioFsFileHandleInner>>);
970
971impl VirtioFsFileHandle {
972 pub fn new() -> Self {
973 Self(Arc::new(Mutex::new(VirtioFsFileHandleInner::new())))
974 }
975}
976
977impl ObjectInterface for VirtioFsFileHandle {
978 async fn poll(&self, event: PollEvent) -> io::Result<PollEvent> {
979 self.0.lock().await.poll(event).await
980 }
981
982 async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
983 self.0.lock().await.read(buf)
984 }
985
986 async fn write(&self, buf: &[u8]) -> io::Result<usize> {
987 self.0.lock().await.write(buf)
988 }
989
990 async fn lseek(&self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
991 self.0.lock().await.lseek(offset, whence)
992 }
993
994 async fn fstat(&self) -> io::Result<FileAttr> {
995 self.0.lock().await.fstat()
996 }
997
998 async fn truncate(&self, size: usize) -> io::Result<()> {
999 let attr = FileAttr {
1000 st_size: size.try_into().unwrap(),
1001 ..FileAttr::default()
1002 };
1003
1004 self.0
1005 .lock()
1006 .await
1007 .set_attr(attr, SetAttrValidFields::FATTR_SIZE)
1008 .map(|_| ())
1009 }
1010
1011 async fn chmod(&self, access_permission: AccessPermission) -> io::Result<()> {
1012 let attr = FileAttr {
1013 st_mode: access_permission,
1014 ..FileAttr::default()
1015 };
1016
1017 self.0
1018 .lock()
1019 .await
1020 .set_attr(attr, SetAttrValidFields::FATTR_MODE)
1021 .map(|_| ())
1022 }
1023
1024 async fn fsync(&self) -> io::Result<()> {
1025 self.0.lock().await.fsync()
1026 }
1027}
1028
1029impl Clone for VirtioFsFileHandle {
1030 fn clone(&self) -> Self {
1031 warn!("VirtioFsFileHandle: clone not tested");
1032 Self(self.0.clone())
1033 }
1034}
1035
1036pub struct VirtioFsDirectoryHandle {
1037 name: String,
1038 read_position: Mutex<usize>,
1039}
1040
1041impl VirtioFsDirectoryHandle {
1042 pub fn new(name: String) -> Self {
1043 Self {
1044 name,
1045 read_position: Mutex::new(0),
1046 }
1047 }
1048}
1049
1050impl ObjectInterface for VirtioFsDirectoryHandle {
1051 async fn getdents(
1052 &self,
1053 buf: &mut [MaybeUninit<u8>],
1054 format: DirentFormat,
1055 ) -> io::Result<usize> {
1056 let path = if self.name.is_empty() {
1057 CString::new("/").unwrap()
1058 } else {
1059 let path = ["/", &self.name].join("");
1060 CString::new(path).unwrap()
1061 };
1062
1063 debug!("virtio-fs opendir: {path:#?}");
1064
1065 let fuse_nid = lookup(&path)?;
1066
1067 let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
1070 cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
1071 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1072 let fuse_fh = rsp.headers.op_header.fh;
1073
1074 debug!("virtio-fs readdir: {path:#?}");
1075
1076 let len = MAX_READ_LEN as u32;
1078 let rsp_offset: &mut usize = &mut *self.read_position.lock().await;
1079 let mut buf_offset: usize = 0;
1080
1081 let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
1083 cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
1084 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1085
1086 let len = usize::min(
1087 MAX_READ_LEN,
1088 rsp.headers.out_header.len as usize - size_of::<fuse_out_header>(),
1089 );
1090
1091 if len <= size_of::<fuse_dirent>() {
1092 debug!("virtio-fs no new dirs");
1093 return Err(Errno::Noent);
1094 }
1095
1096 while (rsp.headers.out_header.len as usize) - *rsp_offset > size_of::<fuse_dirent>() {
1097 let dirent = unsafe {
1098 &*rsp
1099 .payload
1100 .as_ref()
1101 .unwrap()
1102 .as_ptr()
1103 .byte_add(*rsp_offset)
1104 .cast::<fuse_dirent>()
1105 };
1106
1107 let name = unsafe {
1108 slice::from_raw_parts(dirent.name.as_ptr().cast::<u8>(), dirent.namelen as usize)
1109 };
1110 let Some(next_dirent) = format.write_entry(
1111 buf,
1112 buf_offset,
1113 dirent.ino,
1114 (dirent.type_ as u8).try_into().unwrap(),
1115 name,
1116 ) else {
1117 if buf_offset == 0 {
1118 return Err(Errno::Inval);
1120 }
1121 break;
1123 };
1124
1125 *rsp_offset += size_of::<fuse_dirent>() + dirent.namelen as usize;
1126 *rsp_offset = ((*rsp_offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));
1128 buf_offset = next_dirent;
1129 }
1130
1131 let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
1132 VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1133
1134 Ok(buf_offset)
1135 }
1136
1137 async fn fsync(&self) -> io::Result<()> {
1138 let path = if self.name.is_empty() {
1139 CString::new("/").unwrap()
1140 } else {
1141 CString::new(["/", &self.name].join("")).unwrap()
1142 };
1143
1144 debug!("virtio-fs fsyncdir: {path:#?}");
1145
1146 let fuse_nid = lookup(&path)?;
1147
1148 let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
1151 cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
1152 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1153 let fuse_fh = rsp.headers.op_header.fh;
1154
1155 let (mut cmd, rsp_payload_len) = ops::Fsync::create(fuse_nid, fuse_fh, false);
1156 cmd.headers.in_header.opcode = fuse_opcode::FUSE_FSYNCDIR as u32;
1157 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1158 let result = fsync_result(rsp.headers.out_header.error);
1159
1160 let (mut cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
1161 cmd.headers.in_header.opcode = fuse_opcode::FUSE_RELEASEDIR as u32;
1162 VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1163
1164 result
1165 }
1166
1167 async fn lseek(&self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
1172 if whence != SeekWhence::Set && offset != 0 {
1173 error!("Invalid offset for directory lseek ({offset})");
1174 return Err(Errno::Inval);
1175 }
1176 *self.read_position.lock().await = offset as usize;
1177 Ok(offset)
1178 }
1179}
1180
1181#[derive(Debug)]
1182pub(crate) struct VirtioFsDirectory {
1183 prefix: String,
1188 attr: FileAttr,
1189}
1190
1191impl VirtioFsDirectory {
1192 pub fn new(prefix: String) -> Self {
1193 let microseconds = arch::kernel::systemtime::now_micros();
1194 let t = timespec::from_usec(microseconds as i64);
1195
1196 VirtioFsDirectory {
1197 prefix,
1198 attr: FileAttr {
1199 st_mode: AccessPermission::from_bits(0o777).unwrap() | AccessPermission::S_IFDIR,
1200 st_atim: t,
1201 st_mtim: t,
1202 st_ctim: t,
1203 ..Default::default()
1204 },
1205 }
1206 }
1207
1208 fn traversal_path(&self, path: &str) -> CString {
1209 let prefix = self.prefix.as_str();
1210 let prefix = prefix.strip_suffix("/").unwrap_or(prefix);
1211 let path = [prefix, path].join("/");
1212 CString::new(path).unwrap()
1213 }
1214}
1215
1216impl VfsNode for VirtioFsDirectory {
1217 fn get_kind(&self) -> NodeKind {
1219 NodeKind::Directory
1220 }
1221
1222 fn get_file_attributes(&self) -> io::Result<FileAttr> {
1223 Ok(self.attr)
1224 }
1225
1226 fn get_object(&self) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
1227 Ok(Arc::new(async_lock::RwLock::new(
1228 VirtioFsDirectoryHandle::new(self.prefix.clone()).into(),
1229 )))
1230 }
1231
1232 fn traverse_readdir(&self, path: &str) -> io::Result<Vec<DirectoryEntry>> {
1233 let path = self.traversal_path(path);
1234
1235 debug!("virtio-fs opendir: {path:#?}");
1236
1237 let fuse_nid = lookup(&path)?;
1238
1239 let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
1242 cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
1243 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1244 let fuse_fh = rsp.headers.op_header.fh;
1245
1246 debug!("virtio-fs readdir: {path:#?}");
1247
1248 let len = MAX_READ_LEN as u32;
1250 let mut offset: usize = 0;
1251
1252 let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
1254 cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
1255 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1256
1257 let len: usize = if rsp.headers.out_header.len as usize - size_of::<fuse_out_header>()
1258 >= usize::try_from(len).unwrap()
1259 {
1260 len.try_into().unwrap()
1261 } else {
1262 (rsp.headers.out_header.len as usize) - size_of::<fuse_out_header>()
1263 };
1264
1265 if len <= size_of::<fuse_dirent>() {
1266 debug!("virtio-fs no new dirs");
1267 return Err(Errno::Noent);
1268 }
1269
1270 let mut entries: Vec<DirectoryEntry> = Vec::new();
1271 while (rsp.headers.out_header.len as usize) - offset > size_of::<fuse_dirent>() {
1272 let dirent = unsafe {
1273 &*rsp
1274 .payload
1275 .as_ref()
1276 .unwrap()
1277 .as_ptr()
1278 .byte_add(offset)
1279 .cast::<fuse_dirent>()
1280 };
1281
1282 offset += size_of::<fuse_dirent>() + dirent.namelen as usize;
1283 offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));
1285
1286 let name: &'static [u8] = unsafe {
1287 slice::from_raw_parts(
1288 dirent.name.as_ptr().cast(),
1289 dirent.namelen.try_into().unwrap(),
1290 )
1291 };
1292 entries.push(DirectoryEntry::new(unsafe {
1293 core::str::from_utf8_unchecked(name).to_owned()
1294 }));
1295 }
1296
1297 let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
1298 VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1299
1300 Ok(entries)
1301 }
1302
1303 fn traverse_stat(&self, path: &str) -> io::Result<FileAttr> {
1304 let path = self.traversal_path(path);
1305
1306 debug!("virtio-fs stat: {path:#?}");
1307
1308 let (nid, attr) = lookup_attr(&path)?;
1309 if attr.mode & S_IFMT != S_IFLNK {
1310 return Ok(FileAttr::from(attr));
1311 }
1312
1313 let path = readlink(nid)?;
1314 self.traverse_stat(&path)
1315 }
1316
1317 fn traverse_lstat(&self, path: &str) -> io::Result<FileAttr> {
1318 let path = self.traversal_path(path);
1319
1320 debug!("virtio-fs lstat: {path:#?}");
1321
1322 let (_, attr) = lookup_attr(&path)?;
1323 Ok(FileAttr::from(attr))
1324 }
1325
1326 fn traverse_open(
1327 &self,
1328 path: &str,
1329 opt: OpenOption,
1330 mode: AccessPermission,
1331 ) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
1332 let path = self.traversal_path(path);
1333
1334 debug!("virtio-fs open: {path:#?}, {opt:?} {mode:?}");
1335
1336 if opt.contains(OpenOption::O_DIRECTORY) {
1337 if opt.contains(OpenOption::O_CREAT) {
1338 warn!("O_DIRECTORY and O_CREAT are together invalid as open options.");
1340 return Err(Errno::Inval);
1341 }
1342
1343 let (_, attr) = lookup_attr(&path)?;
1344 let attr = FileAttr::from(attr);
1345 if !attr.st_mode.contains(AccessPermission::S_IFDIR) {
1346 return Err(Errno::Notdir);
1347 }
1348
1349 let mut path = path.into_string().unwrap();
1350 path.remove(0);
1351 return Ok(Arc::new(async_lock::RwLock::new(
1352 VirtioFsDirectoryHandle::new(path).into(),
1353 )));
1354 }
1355
1356 let file = VirtioFsFileHandle::new();
1357
1358 let mut file_guard = block_on(async { Ok(file.0.lock().await) }, None)?;
1361
1362 if opt.contains(OpenOption::O_CREAT) {
1364 let (parent, name) = resolve_parent(&path)?;
1366 let (cmd, rsp_payload_len) =
1367 ops::Create::create(parent, name, opt.bits().try_into().unwrap(), mode.bits());
1368 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1369
1370 let inner = rsp.headers.op_header;
1371 file_guard.fuse_nid = Some(inner.entry.nodeid);
1372 file_guard.fuse_fh = Some(inner.open.fh);
1373 } else {
1374 file_guard.fuse_nid = Some(lookup(&path)?);
1375
1376 let (cmd, rsp_payload_len) =
1378 ops::Open::create(file_guard.fuse_nid.unwrap(), opt.bits().try_into().unwrap());
1379 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1380 file_guard.fuse_fh = Some(rsp.headers.op_header.fh);
1381 }
1382
1383 drop(file_guard);
1384
1385 Ok(Arc::new(async_lock::RwLock::new(file.into())))
1386 }
1387
1388 fn traverse_unlink(&self, path: &str) -> io::Result<()> {
1389 let path = self.traversal_path(path);
1390
1391 let (parent, name) = resolve_parent(&path)?;
1392 let (cmd, rsp_payload_len) = ops::Unlink::create(parent, name);
1393 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1394 trace!("unlink answer {rsp:?}");
1395
1396 Ok(())
1397 }
1398
1399 fn traverse_rmdir(&self, path: &str) -> io::Result<()> {
1400 let path = self.traversal_path(path);
1401
1402 let (parent, name) = resolve_parent(&path)?;
1403 let (cmd, rsp_payload_len) = ops::Rmdir::create(parent, name);
1404 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1405 trace!("rmdir answer {rsp:?}");
1406
1407 Ok(())
1408 }
1409
1410 fn traverse_mkdir(&self, path: &str, mode: AccessPermission) -> io::Result<()> {
1411 let path = self.traversal_path(path);
1412 let (parent, name) = resolve_parent(&path)?;
1413 let (cmd, rsp_payload_len) = ops::Mkdir::create(parent, name, mode.bits());
1414
1415 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len)?;
1416 if rsp.headers.out_header.error != 0 {
1417 return Err(Errno::try_from(-rsp.headers.out_header.error).unwrap());
1418 }
1419
1420 Ok(())
1421 }
1422}
1423
1424pub(crate) fn init() {
1425 debug!("Try to initialize virtio-fs filesystem");
1426
1427 let Some(driver) = get_filesystem_driver() else {
1428 return;
1429 };
1430
1431 let (cmd, rsp_payload_len) = ops::Init::create();
1432 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
1433 trace!("virtio-fs init answer: {rsp:?}");
1434
1435 let mount_point = driver.lock().get_mount_point();
1436 if mount_point != "/" {
1437 let mount_point = if mount_point.starts_with('/') {
1438 mount_point
1439 } else {
1440 ["/", &mount_point].join("")
1441 };
1442
1443 info!("Mounting virtio-fs at {mount_point}");
1444 fs::FILESYSTEM
1445 .get()
1446 .unwrap()
1447 .mount(
1448 mount_point.as_str(),
1449 Box::new(VirtioFsDirectory::new("/".to_owned())),
1450 )
1451 .expect("Mount failed. Invalid mount_point?");
1452 return;
1453 }
1454
1455 let fuse_nid = FUSE_ROOT_ID;
1456 let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
1459 cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
1460 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
1461 let fuse_fh = rsp.headers.op_header.fh;
1462
1463 let len = MAX_READ_LEN as u32;
1465 let mut offset: usize = 0;
1466
1467 let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
1469 cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
1470 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
1471
1472 let len: usize = if rsp.headers.out_header.len as usize - size_of::<fuse_out_header>()
1473 >= usize::try_from(len).unwrap()
1474 {
1475 len.try_into().unwrap()
1476 } else {
1477 (rsp.headers.out_header.len as usize) - size_of::<fuse_out_header>()
1478 };
1479
1480 assert!(len > size_of::<fuse_dirent>(), "virtio-fs no new dirs");
1481
1482 let mut entries: Vec<String> = Vec::new();
1483 while (rsp.headers.out_header.len as usize) - offset > size_of::<fuse_dirent>() {
1484 let dirent = unsafe {
1485 &*rsp
1486 .payload
1487 .as_ref()
1488 .unwrap()
1489 .as_ptr()
1490 .byte_add(offset)
1491 .cast::<fuse_dirent>()
1492 };
1493
1494 offset += size_of::<fuse_dirent>() + dirent.namelen as usize;
1495 offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));
1497
1498 let name: &'static [u8] = unsafe {
1499 slice::from_raw_parts(
1500 dirent.name.as_ptr().cast(),
1501 dirent.namelen.try_into().unwrap(),
1502 )
1503 };
1504 entries.push(unsafe { core::str::from_utf8_unchecked(name).to_owned() });
1505 }
1506
1507 let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
1508 VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
1509
1510 entries.retain(|x| x != ".");
1512 entries.retain(|x| x != "..");
1513 entries.retain(|x| x != "tmp");
1514 entries.retain(|x| x != "proc");
1515 warn!(
1516 "virtio-fs don't mount the host directories 'tmp' and 'proc' into the guest file system!"
1517 );
1518
1519 for entry in entries {
1520 let i_cstr = CString::new(entry.as_str()).unwrap();
1521 let (cmd, rsp_payload_len) = ops::Lookup::create(FUSE_ROOT_ID, i_cstr);
1522 let rsp = VirtioFsDriver::send_command(cmd, rsp_payload_len).unwrap();
1523
1524 let attr = FileAttr::from(rsp.headers.op_header.attr);
1525 if attr.st_mode.contains(AccessPermission::S_IFDIR) {
1526 let path = ["/", &entry].join("");
1527 info!("virtio-fs mount {entry} to {path}");
1528 fs::FILESYSTEM
1529 .get()
1530 .unwrap()
1531 .mount(&path, Box::new(VirtioFsDirectory::new(path.clone())))
1532 .expect("Mount failed. Invalid mount_point?");
1533 } else {
1534 warn!("virtio-fs don't mount {entry}. It isn't a directory!");
1535 }
1536 }
1537}