hermit/fs/
fuse.rs

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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::ffi::CString;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::future;
use core::sync::atomic::{AtomicU64, Ordering};
use core::task::Poll;

use async_lock::Mutex;
use async_trait::async_trait;
use fuse_abi::linux::*;
use num_traits::FromPrimitive;
use zerocopy::FromBytes;

use crate::alloc::string::ToString;
#[cfg(not(feature = "pci"))]
use crate::arch::kernel::mmio::get_filesystem_driver;
#[cfg(feature = "pci")]
use crate::drivers::pci::get_filesystem_driver;
use crate::drivers::virtio::virtqueue::error::VirtqError;
use crate::executor::block_on;
use crate::fd::PollEvent;
use crate::fs::{
	self, AccessPermission, DirectoryEntry, FileAttr, NodeKind, ObjectInterface, OpenOption,
	SeekWhence, VfsNode,
};
use crate::mm::device_alloc::DeviceAlloc;
use crate::time::{time_t, timespec};
use crate::{arch, io};

// response out layout eg @ https://github.com/zargony/fuse-rs/blob/bf6d1cf03f3277e35b580f3c7b9999255d72ecf3/src/ll/request.rs#L44
// op in/out sizes/layout: https://github.com/hanwen/go-fuse/blob/204b45dba899dfa147235c255908236d5fde2d32/fuse/opcode.go#L439
// possible responses for command: qemu/tools/virtiofsd/fuse_lowlevel.h

const MAX_READ_LEN: usize = 1024 * 64;
const MAX_WRITE_LEN: usize = 1024 * 64;

const U64_SIZE: usize = ::core::mem::size_of::<u64>();

const S_IFLNK: u32 = 40960;
const S_IFMT: u32 = 61440;

pub(crate) trait FuseInterface {
	fn send_command<O: ops::Op + 'static>(
		&mut self,
		cmd: Cmd<O>,
		rsp_payload_len: u32,
	) -> Result<Rsp<O>, VirtqError>
	where
		<O as ops::Op>::InStruct: Send,
		<O as ops::Op>::OutStruct: Send;

	fn get_mount_point(&self) -> String;
}

pub(crate) mod ops {
	#![allow(clippy::type_complexity)]
	use alloc::boxed::Box;
	use alloc::ffi::CString;

	use fuse_abi::linux::*;

	use super::Cmd;
	use crate::fd::PollEvent;
	use crate::fs::SeekWhence;

	#[repr(C)]
	#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
	pub(crate) struct CreateOut {
		pub entry: fuse_entry_out,
		pub open: fuse_open_out,
	}

	pub(crate) trait Op {
		const OP_CODE: fuse_opcode;

		type InStruct: core::fmt::Debug;
		type InPayload: ?Sized;
		type OutStruct: core::fmt::Debug;
		type OutPayload: ?Sized;
	}

	#[derive(Debug)]
	pub(crate) struct Init;

	impl Op for Init {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_INIT;
		type InStruct = fuse_init_in;
		type InPayload = ();
		type OutStruct = fuse_init_out;
		type OutPayload = ();
	}

	impl Init {
		pub(crate) fn create() -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				FUSE_ROOT_ID,
				fuse_init_in {
					major: 7,
					minor: 31,
					..Default::default()
				},
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Create;

	impl Op for Create {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_CREATE;
		type InStruct = fuse_create_in;
		type InPayload = CString;
		type OutStruct = CreateOut;
		type OutPayload = ();
	}

	impl Create {
		#[allow(clippy::self_named_constructors)]
		pub(crate) fn create(path: CString, flags: u32, mode: u32) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_cstring(
				FUSE_ROOT_ID,
				fuse_create_in {
					flags,
					mode,
					..Default::default()
				},
				path,
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Open;

	impl Op for Open {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_OPEN;
		type InStruct = fuse_open_in;
		type InPayload = ();
		type OutStruct = fuse_open_out;
		type OutPayload = ();
	}

	impl Open {
		pub(crate) fn create(nid: u64, flags: u32) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				nid,
				fuse_open_in {
					flags,
					..Default::default()
				},
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Write;

	impl Op for Write {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_WRITE;
		type InStruct = fuse_write_in;
		type InPayload = [u8];
		type OutStruct = fuse_write_out;
		type OutPayload = ();
	}

	impl Write {
		pub(crate) fn create(nid: u64, fh: u64, buf: Box<[u8]>, offset: u64) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_boxed_slice(
				nid,
				fuse_write_in {
					fh,
					offset,
					size: buf.len().try_into().unwrap(),
					..Default::default()
				},
				buf,
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Read;

	impl Op for Read {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_READ;
		type InStruct = fuse_read_in;
		type InPayload = ();
		type OutStruct = ();
		type OutPayload = [u8];
	}

	impl Read {
		pub(crate) fn create(nid: u64, fh: u64, size: u32, offset: u64) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				nid,
				fuse_read_in {
					fh,
					offset,
					size,
					..Default::default()
				},
			);
			(cmd, size)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Lseek;

	impl Op for Lseek {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_LSEEK;
		type InStruct = fuse_lseek_in;
		type InPayload = ();
		type OutStruct = fuse_lseek_out;
		type OutPayload = ();
	}

	impl Lseek {
		pub(crate) fn create(
			nid: u64,
			fh: u64,
			offset: isize,
			whence: SeekWhence,
		) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				nid,
				fuse_lseek_in {
					fh,
					offset: offset.try_into().unwrap(),
					whence: num::ToPrimitive::to_u32(&whence).unwrap(),
					..Default::default()
				},
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Readlink;

	impl Op for Readlink {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_READLINK;
		type InStruct = ();
		type InPayload = ();
		type OutStruct = ();
		type OutPayload = [u8];
	}

	impl Readlink {
		pub(crate) fn create(nid: u64, size: u32) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(nid, ());
			(cmd, size)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Release;

	impl Op for Release {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_RELEASE;
		type InStruct = fuse_release_in;
		type InPayload = ();
		type OutStruct = ();
		type OutPayload = ();
	}

	impl Release {
		pub(crate) fn create(nid: u64, fh: u64) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				nid,
				fuse_release_in {
					fh,
					..Default::default()
				},
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Poll;

	impl Op for Poll {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_POLL;
		type InStruct = fuse_poll_in;
		type InPayload = ();
		type OutStruct = fuse_poll_out;
		type OutPayload = ();
	}

	impl Poll {
		pub(crate) fn create(nid: u64, fh: u64, kh: u64, event: PollEvent) -> (Cmd<Self>, u32) {
			let cmd = Cmd::new(
				nid,
				fuse_poll_in {
					fh,
					kh,
					events: event.bits() as u32,
					..Default::default()
				},
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Mkdir;

	impl Op for Mkdir {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_MKDIR;
		type InStruct = fuse_mkdir_in;
		type InPayload = CString;
		type OutStruct = fuse_entry_out;
		type OutPayload = ();
	}

	impl Mkdir {
		pub(crate) fn create(path: CString, mode: u32) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_cstring(
				FUSE_ROOT_ID,
				fuse_mkdir_in {
					mode,
					..Default::default()
				},
				path,
			);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Unlink;

	impl Op for Unlink {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_UNLINK;
		type InStruct = ();
		type InPayload = CString;
		type OutStruct = ();
		type OutPayload = ();
	}

	impl Unlink {
		pub(crate) fn create(name: CString) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_cstring(FUSE_ROOT_ID, (), name);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Rmdir;

	impl Op for Rmdir {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_RMDIR;
		type InStruct = ();
		type InPayload = CString;
		type OutStruct = ();
		type OutPayload = ();
	}

	impl Rmdir {
		pub(crate) fn create(name: CString) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_cstring(FUSE_ROOT_ID, (), name);
			(cmd, 0)
		}
	}

	#[derive(Debug)]
	pub(crate) struct Lookup;

	impl Op for Lookup {
		const OP_CODE: fuse_opcode = fuse_opcode::FUSE_LOOKUP;
		type InStruct = ();
		type InPayload = CString;
		type OutStruct = ();
		// Lookups return [fuse_entry_out] only when there actually is a result. For this reason,
		// it is not part of the header (since all other headers are always there).
		type OutPayload = [u8];
	}

	impl Lookup {
		pub(crate) fn create(name: CString) -> (Cmd<Self>, u32) {
			let cmd = Cmd::with_cstring(FUSE_ROOT_ID, (), name);
			(cmd, size_of::<fuse_entry_out>().try_into().unwrap())
		}
	}
}

impl From<fuse_attr> for FileAttr {
	fn from(attr: fuse_attr) -> FileAttr {
		FileAttr {
			st_ino: attr.ino,
			st_nlink: attr.nlink as u64,
			st_mode: AccessPermission::from_bits_retain(attr.mode),
			st_uid: attr.uid,
			st_gid: attr.gid,
			st_rdev: attr.rdev as u64,
			st_size: attr.size,
			st_blksize: attr.blksize as i64,
			st_blocks: attr.blocks.try_into().unwrap(),
			st_atim: timespec {
				tv_sec: attr.atime as time_t,
				tv_nsec: attr.atimensec as i32,
			},
			st_mtim: timespec {
				tv_sec: attr.mtime as time_t,
				tv_nsec: attr.mtimensec as i32,
			},
			st_ctim: timespec {
				tv_sec: attr.ctime as time_t,
				tv_nsec: attr.ctimensec as i32,
			},
			..Default::default()
		}
	}
}

#[repr(C)]
#[derive(Debug)]
pub(crate) struct CmdHeader<O: ops::Op> {
	pub in_header: fuse_in_header,
	op_header: O::InStruct,
}

impl<O: ops::Op> CmdHeader<O>
where
	O: ops::Op<InPayload = ()>,
{
	fn new(nodeid: u64, op_header: O::InStruct) -> Self {
		Self::with_payload_size(nodeid, op_header, 0)
	}
}

impl<O: ops::Op> CmdHeader<O> {
	fn with_payload_size(nodeid: u64, op_header: O::InStruct, len: usize) -> CmdHeader<O> {
		CmdHeader {
			in_header: fuse_in_header {
				// The length we need the provide in the header is not the same as the size of the struct because of padding, so we need to calculate it manually.
				len: (core::mem::size_of::<fuse_in_header>()
					+ core::mem::size_of::<O::InStruct>()
					+ len)
					.try_into()
					.expect("The command is too large"),
				opcode: O::OP_CODE.into(),
				nodeid,
				unique: 1,
				..Default::default()
			},
			op_header,
		}
	}
}

pub(crate) struct Cmd<O: ops::Op> {
	pub headers: Box<CmdHeader<O>, DeviceAlloc>,
	pub payload: Option<Vec<u8, DeviceAlloc>>,
}

impl<O: ops::Op> Cmd<O>
where
	O: ops::Op<InPayload = ()>,
{
	fn new(nodeid: u64, op_header: O::InStruct) -> Self {
		Self {
			headers: Box::new_in(CmdHeader::new(nodeid, op_header), DeviceAlloc),
			payload: None,
		}
	}
}

impl<O: ops::Op> Cmd<O>
where
	O: ops::Op<InPayload = CString>,
{
	fn with_cstring(nodeid: u64, op_header: O::InStruct, cstring: CString) -> Self {
		let cstring_bytes = cstring.into_bytes_with_nul().to_vec_in(DeviceAlloc);
		Self {
			headers: Box::new_in(
				CmdHeader::with_payload_size(nodeid, op_header, cstring_bytes.len()),
				DeviceAlloc,
			),
			payload: Some(cstring_bytes),
		}
	}
}

impl<O: ops::Op> Cmd<O>
where
	O: ops::Op<InPayload = [u8]>,
{
	fn with_boxed_slice(nodeid: u64, op_header: O::InStruct, slice: Box<[u8]>) -> Self {
		let mut device_slice = Vec::with_capacity_in(slice.len(), DeviceAlloc);
		device_slice.extend_from_slice(&slice);
		Self {
			headers: Box::new_in(
				CmdHeader::with_payload_size(nodeid, op_header, slice.len()),
				DeviceAlloc,
			),
			payload: Some(device_slice),
		}
	}
}

#[repr(C)]
#[derive(Debug)]
pub(crate) struct RspHeader<O: ops::Op> {
	out_header: fuse_out_header,
	op_header: O::OutStruct,
}

#[derive(Debug)]
pub(crate) struct Rsp<O: ops::Op> {
	pub headers: Box<RspHeader<O>, DeviceAlloc>,
	pub payload: Option<Vec<u8, DeviceAlloc>>,
}

fn lookup(name: CString) -> Option<u64> {
	let (cmd, rsp_payload_len) = ops::Lookup::create(name);
	let rsp = get_filesystem_driver()
		.unwrap()
		.lock()
		.send_command(cmd, rsp_payload_len)
		.ok()?;
	if rsp.headers.out_header.error == 0 {
		let entry_out = fuse_entry_out::ref_from_bytes(rsp.payload.as_ref().unwrap()).unwrap();
		Some(entry_out.nodeid)
	} else {
		None
	}
}

fn readlink(nid: u64) -> io::Result<String> {
	let len = MAX_READ_LEN as u32;
	let (cmd, rsp_payload_len) = ops::Readlink::create(nid, len);
	let rsp = get_filesystem_driver()
		.unwrap()
		.lock()
		.send_command(cmd, rsp_payload_len)?;
	let len: usize = if rsp.headers.out_header.len as usize
		- ::core::mem::size_of::<fuse_out_header>()
		>= len.try_into().unwrap()
	{
		len.try_into().unwrap()
	} else {
		(rsp.headers.out_header.len as usize) - ::core::mem::size_of::<fuse_out_header>()
	};

	Ok(String::from_utf8(rsp.payload.unwrap()[..len].to_vec()).unwrap())
}

#[derive(Debug)]
struct FuseFileHandleInner {
	fuse_nid: Option<u64>,
	fuse_fh: Option<u64>,
	offset: usize,
}

impl FuseFileHandleInner {
	pub fn new() -> Self {
		Self {
			fuse_nid: None,
			fuse_fh: None,
			offset: 0,
		}
	}

	async fn poll(&self, events: PollEvent) -> io::Result<PollEvent> {
		static KH: AtomicU64 = AtomicU64::new(0);
		let kh = KH.fetch_add(1, Ordering::SeqCst);

		future::poll_fn(|cx| {
			if let (Some(nid), Some(fh)) = (self.fuse_nid, self.fuse_fh) {
				let (cmd, rsp_payload_len) = ops::Poll::create(nid, fh, kh, events);
				let rsp = get_filesystem_driver()
					.ok_or(io::Error::ENOSYS)?
					.lock()
					.send_command(cmd, rsp_payload_len)?;

				if rsp.headers.out_header.error < 0 {
					Poll::Ready(Err(io::Error::EIO))
				} else {
					let revents =
						PollEvent::from_bits(i16::try_from(rsp.headers.op_header.revents).unwrap())
							.unwrap();
					if !revents.intersects(events)
						&& !revents.intersects(
							PollEvent::POLLERR | PollEvent::POLLNVAL | PollEvent::POLLHUP,
						) {
						// the current implementation use polling to wait for an event
						// consequently, we have to wakeup the waker, if the the event doesn't arrive
						cx.waker().wake_by_ref();
					}
					Poll::Ready(Ok(revents))
				}
			} else {
				Poll::Ready(Ok(PollEvent::POLLERR))
			}
		})
		.await
	}

	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		let mut len = buf.len();
		if len > MAX_READ_LEN {
			debug!("Reading longer than max_read_len: {}", len);
			len = MAX_READ_LEN;
		}
		if let (Some(nid), Some(fh)) = (self.fuse_nid, self.fuse_fh) {
			let (cmd, rsp_payload_len) =
				ops::Read::create(nid, fh, len.try_into().unwrap(), self.offset as u64);
			let rsp = get_filesystem_driver()
				.ok_or(io::Error::ENOSYS)?
				.lock()
				.send_command(cmd, rsp_payload_len)?;
			let len: usize = if (rsp.headers.out_header.len as usize)
				- ::core::mem::size_of::<fuse_out_header>()
				>= len
			{
				len
			} else {
				(rsp.headers.out_header.len as usize) - ::core::mem::size_of::<fuse_out_header>()
			};
			self.offset += len;

			buf[..len].copy_from_slice(&rsp.payload.unwrap()[..len]);

			Ok(len)
		} else {
			debug!("File not open, cannot read!");
			Err(io::Error::ENOENT)
		}
	}

	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
		debug!("FUSE write!");
		let mut truncated_len = buf.len();
		if truncated_len > MAX_WRITE_LEN {
			debug!(
				"Writing longer than max_write_len: {} > {}",
				buf.len(),
				MAX_WRITE_LEN
			);
			truncated_len = MAX_WRITE_LEN;
		}
		if let (Some(nid), Some(fh)) = (self.fuse_nid, self.fuse_fh) {
			let truncated_buf = Box::<[u8]>::from(&buf[..truncated_len]);
			let (cmd, rsp_payload_len) =
				ops::Write::create(nid, fh, truncated_buf, self.offset as u64);
			let rsp = get_filesystem_driver()
				.ok_or(io::Error::ENOSYS)?
				.lock()
				.send_command(cmd, rsp_payload_len)?;

			if rsp.headers.out_header.error < 0 {
				return Err(io::Error::EIO);
			}

			let rsp_size = rsp.headers.op_header.size;
			let rsp_len: usize = if rsp_size > truncated_len.try_into().unwrap() {
				truncated_len
			} else {
				rsp_size.try_into().unwrap()
			};
			self.offset += rsp_len;
			Ok(rsp_len)
		} else {
			warn!("File not open, cannot read!");
			Err(io::Error::ENOENT)
		}
	}

	fn lseek(&mut self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
		debug!("FUSE lseek");

		if let (Some(nid), Some(fh)) = (self.fuse_nid, self.fuse_fh) {
			let (cmd, rsp_payload_len) = ops::Lseek::create(nid, fh, offset, whence);
			let rsp = get_filesystem_driver()
				.ok_or(io::Error::ENOSYS)?
				.lock()
				.send_command(cmd, rsp_payload_len)?;

			if rsp.headers.out_header.error < 0 {
				return Err(io::Error::EIO);
			}

			let rsp_offset = rsp.headers.op_header.offset;

			Ok(rsp_offset.try_into().unwrap())
		} else {
			Err(io::Error::EIO)
		}
	}
}

impl Drop for FuseFileHandleInner {
	fn drop(&mut self) {
		if self.fuse_nid.is_some() && self.fuse_fh.is_some() {
			let (cmd, rsp_payload_len) =
				ops::Release::create(self.fuse_nid.unwrap(), self.fuse_fh.unwrap());
			get_filesystem_driver()
				.unwrap()
				.lock()
				.send_command(cmd, rsp_payload_len)
				.unwrap();
		}
	}
}

#[derive(Debug)]
struct FuseFileHandle(pub Arc<Mutex<FuseFileHandleInner>>);

impl FuseFileHandle {
	pub fn new() -> Self {
		Self(Arc::new(Mutex::new(FuseFileHandleInner::new())))
	}
}

#[async_trait]
impl ObjectInterface for FuseFileHandle {
	async fn poll(&self, event: PollEvent) -> io::Result<PollEvent> {
		self.0.lock().await.poll(event).await
	}

	async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
		self.0.lock().await.read(buf)
	}

	async fn write(&self, buf: &[u8]) -> io::Result<usize> {
		self.0.lock().await.write(buf)
	}

	async fn lseek(&self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
		self.0.lock().await.lseek(offset, whence)
	}
}

impl Clone for FuseFileHandle {
	fn clone(&self) -> Self {
		warn!("FuseFileHandle: clone not tested");
		Self(self.0.clone())
	}
}

#[derive(Debug, Clone)]
pub struct FuseDirectoryHandle {
	name: Option<String>,
}

impl FuseDirectoryHandle {
	pub fn new(name: Option<String>) -> Self {
		Self { name }
	}
}

#[async_trait]
impl ObjectInterface for FuseDirectoryHandle {
	async fn readdir(&self) -> io::Result<Vec<DirectoryEntry>> {
		let path: CString = if let Some(name) = &self.name {
			CString::new("/".to_string() + name).unwrap()
		} else {
			CString::new("/".to_string()).unwrap()
		};

		debug!("FUSE opendir: {path:#?}");

		let fuse_nid = lookup(path.clone()).ok_or(io::Error::ENOENT)?;

		// Opendir
		// Flag 0x10000 for O_DIRECTORY might not be necessary
		let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
		cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;
		let fuse_fh = rsp.headers.op_header.fh;

		debug!("FUSE readdir: {path:#?}");

		// Linux seems to allocate a single page to store the dirfile
		let len = MAX_READ_LEN as u32;
		let mut offset: usize = 0;

		// read content of the directory
		let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
		cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		let len: usize = if rsp.headers.out_header.len as usize
			- ::core::mem::size_of::<fuse_out_header>()
			>= len.try_into().unwrap()
		{
			len.try_into().unwrap()
		} else {
			(rsp.headers.out_header.len as usize) - ::core::mem::size_of::<fuse_out_header>()
		};

		if len <= core::mem::size_of::<fuse_dirent>() {
			debug!("FUSE no new dirs");
			return Err(io::Error::ENOENT);
		}

		let mut entries: Vec<DirectoryEntry> = Vec::new();
		while (rsp.headers.out_header.len as usize) - offset > core::mem::size_of::<fuse_dirent>() {
			let dirent = unsafe {
				&*(rsp.payload.as_ref().unwrap().as_ptr().byte_add(offset) as *const fuse_dirent)
			};

			offset += core::mem::size_of::<fuse_dirent>() + dirent.namelen as usize;
			// Align to dirent struct
			offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));

			let name: &'static [u8] = unsafe {
				core::slice::from_raw_parts(
					dirent.name.as_ptr().cast(),
					dirent.namelen.try_into().unwrap(),
				)
			};
			entries.push(DirectoryEntry::new(unsafe {
				core::str::from_utf8_unchecked(name).to_string()
			}));
		}

		let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
		get_filesystem_driver()
			.unwrap()
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		Ok(entries)
	}
}

#[derive(Debug)]
pub(crate) struct FuseDirectory {
	prefix: Option<String>,
	attr: FileAttr,
}

impl FuseDirectory {
	pub fn new(prefix: Option<String>) -> Self {
		let microseconds = arch::kernel::systemtime::now_micros();
		let t = timespec::from_usec(microseconds as i64);

		FuseDirectory {
			prefix,
			attr: FileAttr {
				st_mode: AccessPermission::from_bits(0o777).unwrap() | AccessPermission::S_IFDIR,
				st_atim: t,
				st_mtim: t,
				st_ctim: t,
				..Default::default()
			},
		}
	}

	fn traversal_path(&self, components: &[&str]) -> CString {
		let prefix_deref = self.prefix.as_deref();
		let components_with_prefix = prefix_deref.iter().chain(components.iter().rev());
		let path: String = components_with_prefix
			.flat_map(|component| ["/", component])
			.collect();
		if path.is_empty() {
			CString::new("/").unwrap()
		} else {
			CString::new(path).unwrap()
		}
	}
}

impl VfsNode for FuseDirectory {
	/// Returns the node type
	fn get_kind(&self) -> NodeKind {
		NodeKind::Directory
	}

	fn get_file_attributes(&self) -> io::Result<FileAttr> {
		Ok(self.attr)
	}

	fn get_object(&self) -> io::Result<Arc<dyn ObjectInterface>> {
		Ok(Arc::new(FuseDirectoryHandle::new(self.prefix.clone())))
	}

	fn traverse_readdir(&self, components: &mut Vec<&str>) -> io::Result<Vec<DirectoryEntry>> {
		let path = self.traversal_path(components);

		debug!("FUSE opendir: {path:#?}");

		let fuse_nid = lookup(path.clone()).ok_or(io::Error::ENOENT)?;

		// Opendir
		// Flag 0x10000 for O_DIRECTORY might not be necessary
		let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
		cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;
		let fuse_fh = rsp.headers.op_header.fh;

		debug!("FUSE readdir: {path:#?}");

		// Linux seems to allocate a single page to store the dirfile
		let len = MAX_READ_LEN as u32;
		let mut offset: usize = 0;

		// read content of the directory
		let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
		cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		let len: usize = if rsp.headers.out_header.len as usize
			- ::core::mem::size_of::<fuse_out_header>()
			>= len.try_into().unwrap()
		{
			len.try_into().unwrap()
		} else {
			(rsp.headers.out_header.len as usize) - ::core::mem::size_of::<fuse_out_header>()
		};

		if len <= core::mem::size_of::<fuse_dirent>() {
			debug!("FUSE no new dirs");
			return Err(io::Error::ENOENT);
		}

		let mut entries: Vec<DirectoryEntry> = Vec::new();
		while (rsp.headers.out_header.len as usize) - offset > core::mem::size_of::<fuse_dirent>() {
			let dirent = unsafe {
				&*(rsp.payload.as_ref().unwrap().as_ptr().byte_add(offset) as *const fuse_dirent)
			};

			offset += core::mem::size_of::<fuse_dirent>() + dirent.namelen as usize;
			// Align to dirent struct
			offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));

			let name: &'static [u8] = unsafe {
				core::slice::from_raw_parts(
					dirent.name.as_ptr().cast(),
					dirent.namelen.try_into().unwrap(),
				)
			};
			entries.push(DirectoryEntry::new(unsafe {
				core::str::from_utf8_unchecked(name).to_string()
			}));
		}

		let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
		get_filesystem_driver()
			.unwrap()
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		Ok(entries)
	}

	fn traverse_stat(&self, components: &mut Vec<&str>) -> io::Result<FileAttr> {
		let path = self.traversal_path(components);

		debug!("FUSE stat: {path:#?}");

		// Is there a better way to implement this?
		let (cmd, rsp_payload_len) = ops::Lookup::create(path);
		let rsp = get_filesystem_driver()
			.unwrap()
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		if rsp.headers.out_header.error != 0 {
			Err(io::Error::from_i32(-rsp.headers.out_header.error).unwrap())
		} else {
			let entry_out = fuse_entry_out::ref_from_bytes(rsp.payload.as_ref().unwrap()).unwrap();
			let attr = entry_out.attr;

			if attr.mode & S_IFMT != S_IFLNK {
				Ok(FileAttr::from(attr))
			} else {
				let path = readlink(entry_out.nodeid)?;
				let mut components: Vec<&str> = path.split('/').collect();
				self.traverse_stat(&mut components)
			}
		}
	}

	fn traverse_lstat(&self, components: &mut Vec<&str>) -> io::Result<FileAttr> {
		let path = self.traversal_path(components);

		debug!("FUSE lstat: {path:#?}");

		let (cmd, rsp_payload_len) = ops::Lookup::create(path);
		let rsp = get_filesystem_driver()
			.unwrap()
			.lock()
			.send_command(cmd, rsp_payload_len)?;

		if rsp.headers.out_header.error != 0 {
			Err(io::Error::from_i32(-rsp.headers.out_header.error).unwrap())
		} else {
			let entry_out = fuse_entry_out::ref_from_bytes(rsp.payload.as_ref().unwrap()).unwrap();
			Ok(FileAttr::from(entry_out.attr))
		}
	}

	fn traverse_open(
		&self,
		components: &mut Vec<&str>,
		opt: OpenOption,
		mode: AccessPermission,
	) -> io::Result<Arc<dyn ObjectInterface>> {
		let path = self.traversal_path(components);

		debug!("FUSE open: {path:#?}, {opt:?} {mode:?}");

		if opt.contains(OpenOption::O_DIRECTORY) {
			if opt.contains(OpenOption::O_CREAT) {
				// See https://lwn.net/Articles/926782/
				warn!("O_DIRECTORY and O_CREAT are together invalid as open options.");
				return Err(io::Error::EINVAL);
			}

			let (cmd, rsp_payload_len) = ops::Lookup::create(path.clone());
			let rsp = get_filesystem_driver()
				.unwrap()
				.lock()
				.send_command(cmd, rsp_payload_len)?;

			if rsp.headers.out_header.error == 0 {
				let entry_out =
					fuse_entry_out::ref_from_bytes(rsp.payload.as_ref().unwrap()).unwrap();
				let attr = FileAttr::from(entry_out.attr);
				if attr.st_mode.contains(AccessPermission::S_IFDIR) {
					let mut path = path.into_string().unwrap();
					path.remove(0);
					Ok(Arc::new(FuseDirectoryHandle::new(Some(path))))
				} else {
					Err(io::Error::ENOTDIR)
				}
			} else {
				Err(io::Error::from_i32(-rsp.headers.out_header.error).unwrap())
			}
		} else {
			let file = FuseFileHandle::new();

			// 1.FUSE_INIT to create session
			// Already done
			let mut file_guard = block_on(async { Ok(file.0.lock().await) }, None)?;

			// Differentiate between opening and creating new file, since fuse does not support O_CREAT on open.
			if !opt.contains(OpenOption::O_CREAT) {
				// 2.FUSE_LOOKUP(FUSE_ROOT_ID, “foo”) -> nodeid
				file_guard.fuse_nid = lookup(path);

				if file_guard.fuse_nid.is_none() {
					warn!("Fuse lookup seems to have failed!");
					return Err(io::Error::ENOENT);
				}

				// 3.FUSE_OPEN(nodeid, O_RDONLY) -> fh
				let (cmd, rsp_payload_len) =
					ops::Open::create(file_guard.fuse_nid.unwrap(), opt.bits().try_into().unwrap());
				let rsp = get_filesystem_driver()
					.ok_or(io::Error::ENOSYS)?
					.lock()
					.send_command(cmd, rsp_payload_len)?;
				file_guard.fuse_fh = Some(rsp.headers.op_header.fh);
			} else {
				// Create file (opens implicitly, returns results from both lookup and open calls)
				let (cmd, rsp_payload_len) =
					ops::Create::create(path, opt.bits().try_into().unwrap(), mode.bits());
				let rsp = get_filesystem_driver()
					.ok_or(io::Error::ENOSYS)?
					.lock()
					.send_command(cmd, rsp_payload_len)?;

				let inner = rsp.headers.op_header;
				file_guard.fuse_nid = Some(inner.entry.nodeid);
				file_guard.fuse_fh = Some(inner.open.fh);
			}

			drop(file_guard);

			Ok(Arc::new(file))
		}
	}

	fn traverse_unlink(&self, components: &mut Vec<&str>) -> io::Result<()> {
		let path = self.traversal_path(components);

		let (cmd, rsp_payload_len) = ops::Unlink::create(path);
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;
		trace!("unlink answer {:?}", rsp);

		Ok(())
	}

	fn traverse_rmdir(&self, components: &mut Vec<&str>) -> io::Result<()> {
		let path = self.traversal_path(components);

		let (cmd, rsp_payload_len) = ops::Rmdir::create(path);
		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;
		trace!("rmdir answer {:?}", rsp);

		Ok(())
	}

	fn traverse_mkdir(&self, components: &mut Vec<&str>, mode: AccessPermission) -> io::Result<()> {
		let path = self.traversal_path(components);
		let (cmd, rsp_payload_len) = ops::Mkdir::create(path, mode.bits());

		let rsp = get_filesystem_driver()
			.ok_or(io::Error::ENOSYS)?
			.lock()
			.send_command(cmd, rsp_payload_len)?;
		if rsp.headers.out_header.error == 0 {
			Ok(())
		} else {
			Err(num::FromPrimitive::from_i32(-rsp.headers.out_header.error).unwrap())
		}
	}
}

pub(crate) fn init() {
	debug!("Try to initialize fuse filesystem");

	if let Some(driver) = get_filesystem_driver() {
		let (cmd, rsp_payload_len) = ops::Init::create();
		let rsp = driver.lock().send_command(cmd, rsp_payload_len).unwrap();
		trace!("fuse init answer: {:?}", rsp);

		let mount_point = driver.lock().get_mount_point().to_string();
		if mount_point == "/" {
			let fuse_nid = lookup(c"/".to_owned()).unwrap();
			// Opendir
			// Flag 0x10000 for O_DIRECTORY might not be necessary
			let (mut cmd, rsp_payload_len) = ops::Open::create(fuse_nid, 0x10000);
			cmd.headers.in_header.opcode = fuse_opcode::FUSE_OPENDIR as u32;
			let rsp = get_filesystem_driver()
				.unwrap()
				.lock()
				.send_command(cmd, rsp_payload_len)
				.unwrap();
			let fuse_fh = rsp.headers.op_header.fh;

			// Linux seems to allocate a single page to store the dirfile
			let len = MAX_READ_LEN as u32;
			let mut offset: usize = 0;

			// read content of the directory
			let (mut cmd, rsp_payload_len) = ops::Read::create(fuse_nid, fuse_fh, len, 0);
			cmd.headers.in_header.opcode = fuse_opcode::FUSE_READDIR as u32;
			let rsp = get_filesystem_driver()
				.unwrap()
				.lock()
				.send_command(cmd, rsp_payload_len)
				.unwrap();

			let len: usize = if rsp.headers.out_header.len as usize
				- ::core::mem::size_of::<fuse_out_header>()
				>= len.try_into().unwrap()
			{
				len.try_into().unwrap()
			} else {
				(rsp.headers.out_header.len as usize) - ::core::mem::size_of::<fuse_out_header>()
			};

			if len <= core::mem::size_of::<fuse_dirent>() {
				panic!("FUSE no new dirs");
			}

			let mut entries: Vec<String> = Vec::new();
			while (rsp.headers.out_header.len as usize) - offset
				> core::mem::size_of::<fuse_dirent>()
			{
				let dirent = unsafe {
					&*(rsp.payload.as_ref().unwrap().as_ptr().byte_add(offset)
						as *const fuse_dirent)
				};

				offset += core::mem::size_of::<fuse_dirent>() + dirent.namelen as usize;
				// Align to dirent struct
				offset = ((offset) + U64_SIZE - 1) & (!(U64_SIZE - 1));

				let name: &'static [u8] = unsafe {
					core::slice::from_raw_parts(
						dirent.name.as_ptr().cast(),
						dirent.namelen.try_into().unwrap(),
					)
				};
				entries.push(unsafe { core::str::from_utf8_unchecked(name).to_string() });
			}

			let (cmd, rsp_payload_len) = ops::Release::create(fuse_nid, fuse_fh);
			get_filesystem_driver()
				.unwrap()
				.lock()
				.send_command(cmd, rsp_payload_len)
				.unwrap();

			// remove predefined directories
			entries.retain(|x| x != ".");
			entries.retain(|x| x != "..");
			entries.retain(|x| x != "tmp");
			entries.retain(|x| x != "proc");
			warn!("Fuse don't mount the host directories 'tmp' and 'proc' into the guest file system!");

			for i in entries {
				let i_cstr = CString::new(i.clone()).unwrap();
				let (cmd, rsp_payload_len) = ops::Lookup::create(i_cstr);
				let rsp = get_filesystem_driver()
					.unwrap()
					.lock()
					.send_command(cmd, rsp_payload_len)
					.unwrap();

				assert_eq!(rsp.headers.out_header.error, 0);
				let entry_out =
					fuse_entry_out::ref_from_bytes(rsp.payload.as_ref().unwrap()).unwrap();
				let attr = entry_out.attr;
				let attr = FileAttr::from(attr);

				if attr.st_mode.contains(AccessPermission::S_IFDIR) {
					info!("Fuse mount {} to /{}", i, i);
					fs::FILESYSTEM
						.get()
						.unwrap()
						.mount(
							&("/".to_owned() + i.as_str()),
							Box::new(FuseDirectory::new(Some(i))),
						)
						.expect("Mount failed. Invalid mount_point?");
				} else {
					warn!("Fuse don't mount {}. It isn't a directory!", i);
				}
			}
		} else {
			let mount_point = if mount_point.starts_with('/') {
				mount_point
			} else {
				"/".to_owned() + &mount_point
			};

			info!("Mounting virtio-fs at {}", mount_point);
			fs::FILESYSTEM
				.get()
				.unwrap()
				.mount(mount_point.as_str(), Box::new(FuseDirectory::new(None)))
				.expect("Mount failed. Invalid mount_point?");
		}
	}
}