Skip to main content

hermit/fs/
vfat.rs

1use alloc::boxed::Box;
2use alloc::string::{String, ToString};
3use alloc::sync::Arc;
4use alloc::vec;
5use alloc::vec::Vec;
6use core::mem::MaybeUninit;
7use core::sync::atomic::{AtomicU64, Ordering};
8
9use hadris_fat::r#async::read::FileReader;
10use hadris_fat::r#async::write::FileWriter;
11use hadris_fat::r#async::{
12	Error as IoError, FatDir, FatVolume, FatVolumeReadExt, FatVolumeWriteExt, FileEntry, Read,
13	Seek, SeekFrom, Write,
14};
15use hadris_fat::time::{FatDateTime, TimeProvider};
16use hermit_sync::OnceCell;
17use time::OffsetDateTime;
18
19#[cfg(not(feature = "pci"))]
20use crate::arch::kernel::mmio::get_block_driver;
21use crate::drivers::blk::{SECTOR_SIZE, driver, with_driver};
22#[cfg(feature = "pci")]
23use crate::drivers::pci::get_block_driver;
24use crate::errno::Errno;
25use crate::executor::block_on;
26use crate::fd::{AccessPermission, Fd, ObjectInterface, OpenOption};
27use crate::fs::{self, DirectoryEntry, FileAttr, FileType, NodeKind, SeekWhence, VfsNode};
28use crate::io;
29use crate::syscalls::DirentFormat;
30use crate::time::SystemTime;
31
32/// Number of sectors `FatStream` keeps in memory.
33///
34/// Several times [`RUN_SECTORS`], so that a read-ahead does not evict the
35/// FAT and directory sectors in use.
36const CACHE_SECTORS: usize = 256;
37
38/// Sectors fetched per cache miss and maximum length of a merged write.
39const RUN_SECTORS: usize = 64;
40
41/// One cached device sector.
42struct CachedSector {
43	/// Sector index on the device.
44	sector: usize,
45	/// Sector content.
46	data: [u8; SECTOR_SIZE],
47	/// Modified, but not yet written back.
48	dirty: bool,
49	/// Last access time for LRU eviction.
50	used: u64,
51}
52
53/// Sector cache providing byte-wise `Read`/`Write`/`Seek` on the block
54/// device for `hadris-fat`. Writes reach the device on eviction or flush.
55struct FatStream {
56	cache: Vec<CachedSector>,
57	/// Access counter for LRU eviction.
58	clock: u64,
59	/// Byte position on the device.
60	pos: usize,
61}
62
63impl FatStream {
64	pub fn new() -> Self {
65		Self {
66			cache: Vec::with_capacity(CACHE_SECTORS),
67			clock: 0,
68			pos: 0,
69		}
70	}
71
72	/// The number of sectors the device holds.
73	fn capacity(&self) -> Result<usize, Errno> {
74		with_driver(|drv| drv.capacity()).ok_or(Errno::Nodev)
75	}
76
77	/// Returns the slot holding `sector` and loads it on a miss.
78	///
79	/// With `fill == false` the sector is not read, because the caller
80	/// overwrites it completely.
81	async fn slot(&mut self, sector: usize, fill: bool) -> Result<usize, Errno> {
82		self.clock += 1;
83
84		if let Some(slot) = self.find(sector) {
85			self.cache[slot].used = self.clock;
86			return Ok(slot);
87		}
88
89		if !fill {
90			return self.install(sector, &[0u8; SECTOR_SIZE]).await;
91		}
92
93		// Read ahead, bounded by the device.
94		let sectors = RUN_SECTORS.min(self.capacity()? - sector);
95
96		let mut run = vec![0; sectors * SECTOR_SIZE];
97		self.fill_run(sector, &mut run).await
98	}
99
100	/// Reads a run of sectors into the cache and returns the slot holding
101	/// `sector`.
102	async fn fill_run(&mut self, sector: usize, run: &mut [u8]) -> Result<usize, Errno> {
103		driver().ok_or(Errno::Nodev)?.read(sector, run).await?;
104
105		let mut requested = None;
106		for (index, data) in run.as_chunks::<SECTOR_SIZE>().0.iter().enumerate() {
107			// Keep cached copies, they may be dirty.
108			if self
109				.cache
110				.iter()
111				.any(|entry| entry.sector == sector + index)
112			{
113				continue;
114			}
115
116			let slot = self.install(sector + index, data).await?;
117			if index == 0 {
118				requested = Some(slot);
119			}
120		}
121
122		match requested {
123			Some(slot) => Ok(slot),
124			None => self.find(sector).ok_or(Errno::Io),
125		}
126	}
127
128	/// Returns the slot holding `sector`, if it is cached.
129	fn find(&self, sector: usize) -> Option<usize> {
130		self.cache.iter().position(|entry| entry.sector == sector)
131	}
132
133	/// Puts `data` into a free or freshly evicted slot and returns it.
134	async fn install(&mut self, sector: usize, data: &[u8]) -> Result<usize, Errno> {
135		let entry = CachedSector {
136			sector,
137			data: data.try_into().unwrap(),
138			dirty: false,
139			used: self.clock,
140		};
141
142		if self.cache.len() < CACHE_SECTORS {
143			self.cache.push(entry);
144			return Ok(self.cache.len() - 1);
145		}
146
147		// LRU eviction; sectors of the current run are never chosen.
148		let victim = self
149			.cache
150			.iter()
151			.enumerate()
152			.min_by_key(|(_, entry)| entry.used)
153			.map(|(slot, _)| slot)
154			.unwrap();
155
156		// Flush all dirty sectors at once, so that adjacent ones are merged.
157		if self.cache[victim].dirty {
158			self.flush_all().await?;
159		}
160
161		self.cache[victim] = entry;
162
163		Ok(victim)
164	}
165
166	/// Writes all dirty sectors back and merges adjacent ones into one request.
167	async fn flush_all(&mut self) -> Result<(), Errno> {
168		let mut dirty: Vec<usize> = (0..self.cache.len())
169			.filter(|&slot| self.cache[slot].dirty)
170			.collect();
171		if dirty.is_empty() {
172			return Ok(());
173		}
174		dirty.sort_unstable_by_key(|&slot| self.cache[slot].sector);
175
176		// `Batch::write` copies the data, so one buffer serves every run.
177		let mut run = vec![0; RUN_SECTORS * SECTOR_SIZE];
178
179		let mut batch = driver().ok_or(Errno::Nodev)?.batch().await;
180		let mut submitted = Ok(());
181
182		let mut rest = dirty.as_slice();
183		while let Some((&first, _)) = rest.split_first() {
184			// Longest run of consecutive sectors that fits the buffer.
185			let len = rest
186				.iter()
187				.enumerate()
188				.take(RUN_SECTORS)
189				.take_while(|&(index, &slot)| {
190					self.cache[slot].sector == self.cache[first].sector + index
191				})
192				.count();
193			let (group, tail) = rest.split_at(len);
194			rest = tail;
195
196			for (index, &slot) in group.iter().enumerate() {
197				run[index * SECTOR_SIZE..(index + 1) * SECTOR_SIZE]
198					.copy_from_slice(&self.cache[slot].data);
199			}
200
201			submitted = batch.write(self.cache[first].sector, &run[..len * SECTOR_SIZE]);
202			if submitted.is_err() {
203				break;
204			}
205		}
206
207		// Keep the sectors dirty until the device has acknowledged them.
208		batch.finish().await?;
209		submitted?;
210
211		for &slot in &dirty {
212			self.cache[slot].dirty = false;
213		}
214
215		Ok(())
216	}
217}
218
219impl From<Errno> for IoError<Errno> {
220	fn from(e: Errno) -> Self {
221		IoError::from_source(e)
222	}
223}
224
225impl Read for FatStream {
226	type Error = Errno;
227
228	async fn read(&mut self, buf: &mut [u8]) -> Result<usize, IoError<Errno>> {
229		let capacity = self.capacity()?;
230		let mut done = 0;
231
232		while done < buf.len() {
233			let sector = self.pos / SECTOR_SIZE;
234			let offset = self.pos % SECTOR_SIZE;
235
236			if sector >= capacity {
237				break;
238			}
239
240			let slot = match self.slot(sector, true).await {
241				Ok(slot) => slot,
242				Err(err) if done == 0 => return Err(err.into()),
243				Err(_) => break,
244			};
245
246			let n = usize::min(buf.len() - done, SECTOR_SIZE - offset);
247			buf[done..done + n].copy_from_slice(&self.cache[slot].data[offset..offset + n]);
248			self.pos += n;
249			done += n;
250		}
251
252		Ok(done)
253	}
254}
255
256impl Write for FatStream {
257	type Error = Errno;
258
259	async fn write(&mut self, buf: &[u8]) -> Result<usize, IoError<Errno>> {
260		let capacity = self.capacity()?;
261		let mut done = 0;
262
263		while done < buf.len() {
264			let sector = self.pos / SECTOR_SIZE;
265			let offset = self.pos % SECTOR_SIZE;
266
267			if sector >= capacity {
268				if done == 0 {
269					return Err(IoError::from_source(Errno::Nospc));
270				}
271				break;
272			}
273
274			let n = usize::min(buf.len() - done, SECTOR_SIZE - offset);
275
276			// Only a partial sector has to be read first.
277			let slot = match self.slot(sector, n != SECTOR_SIZE).await {
278				Ok(slot) => slot,
279				Err(err) if done == 0 => return Err(err.into()),
280				Err(_) => break,
281			};
282
283			self.cache[slot].data[offset..offset + n].copy_from_slice(&buf[done..done + n]);
284			self.cache[slot].dirty = true;
285			self.pos += n;
286			done += n;
287		}
288
289		Ok(done)
290	}
291
292	async fn flush(&mut self) -> Result<(), IoError<Errno>> {
293		self.flush_all().await?;
294		driver().ok_or(Errno::Nodev)?.flush().await?;
295
296		Ok(())
297	}
298}
299
300impl Seek for FatStream {
301	type Error = Errno;
302
303	async fn seek(&mut self, pos: SeekFrom) -> Result<u64, IoError<Errno>> {
304		let end = i64::try_from(self.capacity()? * SECTOR_SIZE).unwrap();
305		let cur = i64::try_from(self.pos).unwrap();
306
307		let new = match pos {
308			SeekFrom::Start(n) => i64::try_from(n).ok(),
309			SeekFrom::Current(offset) => cur.checked_add(offset),
310			SeekFrom::End(offset) => end.checked_add(offset),
311		};
312
313		// Seeking past the end is allowed, accessing it is not.
314		let new = new.filter(|new| *new >= 0).ok_or(Errno::Inval)?;
315
316		self.pos = usize::try_from(new).unwrap();
317
318		Ok(new as u64)
319	}
320}
321
322fn format_file_size(size: u64) -> String {
323	const KIB: u64 = 1024;
324	const MIB: u64 = 1024 * KIB;
325	const GIB: u64 = 1024 * MIB;
326	if size < KIB {
327		format!("{size} B")
328	} else if size < MIB {
329		format!("{} KiB", size / KIB)
330	} else if size < GIB {
331		format!("{} MiB", size / MIB)
332	} else {
333		format!("{} GiB", size / GIB)
334	}
335}
336
337pub(crate) fn init() {
338	debug!("Try to initialize vfat filesystem");
339
340	if get_block_driver().is_none() {
341		return;
342	};
343
344	let stream = FatStream::new();
345	debug!(
346		"Found block device with a capacity of {}",
347		format_file_size(
348			(stream.capacity().unwrap() * SECTOR_SIZE)
349				.try_into()
350				.unwrap()
351		)
352	);
353
354	match block_on(
355		async {
356			FatVolume::builder(stream)
357				.time_provider(&TIME_PROVIDER)
358				.open()
359				.await
360				.map_err(map_err)
361		},
362		None,
363	) {
364		Ok(volume) => {
365			info!("Mounting {} volume at {MOUNT_POINT}", volume.fat_type());
366
367			if VFAT.set(SharedVolume(volume)).is_err() {
368				error!("Unable to mount block device at {MOUNT_POINT}");
369				return;
370			}
371
372			if let Err(err) = fs::FILESYSTEM
373				.get()
374				.unwrap()
375				.mount(MOUNT_POINT, Box::new(VfatDirectory::new(String::new())))
376			{
377				error!("Unable to mount block device at {MOUNT_POINT}: {err:?}");
378			}
379		}
380		Err(_) => {
381			warn!("Unable to create FAT volume");
382		}
383	}
384}
385
386/// Stamps directory entries with the system's wall-clock time.
387#[derive(Debug)]
388struct FatTimeProvider;
389
390impl FatTimeProvider {
391	pub const fn new() -> Self {
392		Self {}
393	}
394}
395
396impl TimeProvider for FatTimeProvider {
397	fn now(&self) -> FatDateTime {
398		let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH);
399		let Ok(now) = OffsetDateTime::from_unix_timestamp_nanos(now.as_nanos().cast_signed())
400		else {
401			return FatDateTime::EPOCH;
402		};
403
404		let mut date_time = FatDateTime::new(
405			u16::try_from(now.year()).unwrap_or(1980),
406			now.month() as u8,
407			now.day(),
408			now.hour(),
409			now.minute(),
410			now.second(),
411		);
412
413		// `time_tenth` holds the odd second and the 10 ms units.
414		date_time.time_tenth =
415			u8::try_from((u16::from(now.second() % 2) * 100 + now.millisecond() / 10).min(199))
416				.unwrap();
417
418		date_time
419	}
420}
421
422static TIME_PROVIDER: FatTimeProvider = FatTimeProvider::new();
423
424// ---------------------------------------------------------------------------
425// VFS integration
426// ---------------------------------------------------------------------------
427
428/// `FatVolume` is not `Sync`, because it keeps counters in `Cell`s.
429struct SharedVolume(FatVolume<FatStream>);
430
431// SAFETY: the volume is only accessed while `VFAT_LOCK` is held, see `volume`.
432unsafe impl Sync for SharedVolume {}
433
434static VFAT: OnceCell<SharedVolume> = OnceCell::new();
435
436/// Serializes file system operations, see [`volume`].
437static VFAT_LOCK: async_lock::Mutex<()> = async_lock::Mutex::new(());
438
439/// Incremented on every modification, invalidates cached readers.
440static GENERATION: AtomicU64 = AtomicU64::new(0);
441
442fn modified() {
443	GENERATION.fetch_add(1, Ordering::Relaxed);
444}
445
446/// Where the FAT file system is attached in the VFS.
447const MOUNT_POINT: &str = "/root";
448
449/// Translates a `hadris-fat` error into the kernel's error number.
450fn map_err(err: hadris_fat::error::Error) -> Errno {
451	use hadris_fat::error::Error;
452
453	match err {
454		Error::EntryNotFound => Errno::Noent,
455		Error::NotADirectory => Errno::Notdir,
456		Error::NotAFile => Errno::Isdir,
457		Error::NoFreeSpace => Errno::Nospc,
458		Error::InvalidPath | Error::InvalidShortFilename => Errno::Inval,
459		_ => Errno::Io,
460	}
461}
462
463/// Locks the volume for one complete file system operation.
464///
465/// `hadris-fat` locks only single accesses, so a lookup and the following
466/// write could otherwise race on another core.
467async fn volume() -> io::Result<Volume> {
468	let fs = &VFAT.get().ok_or(Errno::Nodev)?.0;
469	let _guard = VFAT_LOCK.lock().await;
470
471	Ok(Volume { fs, _guard })
472}
473
474/// The mounted volume, locked for one operation.
475struct Volume {
476	fs: &'static FatVolume<FatStream>,
477	_guard: async_lock::MutexGuard<'static, ()>,
478}
479
480impl core::ops::Deref for Volume {
481	type Target = FatVolume<FatStream>;
482
483	fn deref(&self) -> &Self::Target {
484		self.fs
485	}
486}
487
488/// Joins the directory's own path with a path relative to it.
489fn join(prefix: &str, path: &str) -> String {
490	match (prefix.trim_matches('/'), path.trim_matches('/')) {
491		("", rest) => rest.to_string(),
492		(base, "") => base.to_string(),
493		(base, rest) => [base, rest].join("/"),
494	}
495}
496
497/// Finds the entry called `name` directly below `dir`.
498async fn find(dir: &FatDir<'_, FatStream>, name: &str) -> io::Result<Option<FileEntry>> {
499	let mut entries = dir.entries();
500	while let Some(entry) = entries.next_entry().await {
501		let entry = entry.map_err(map_err)?;
502		if entry.name() == name
503			&& let Some(entry) = entry.as_entry()
504		{
505			return Ok(Some(entry.clone()));
506		}
507	}
508
509	Ok(None)
510}
511
512/// Walks `path` and returns the directory holding its last component together
513/// with that component's entry, if it exists.
514async fn resolve<'a>(
515	volume: &'a FatVolume<FatStream>,
516	path: &str,
517) -> io::Result<(FatDir<'a, FatStream>, Option<FileEntry>)> {
518	let mut dir = volume.root_dir();
519
520	let mut components = path.split('/').filter(|part| !part.is_empty()).peekable();
521
522	while let Some(component) = components.next() {
523		let entry = find(&dir, component).await?;
524
525		if components.peek().is_none() {
526			return Ok((dir, entry));
527		}
528
529		let entry = entry.ok_or(Errno::Noent)?;
530		dir = dir.open_entry(&entry).map_err(map_err)?;
531	}
532
533	Ok((dir, None))
534}
535
536/// Resolves `path` to a directory.
537async fn resolve_dir<'a>(
538	volume: &'a FatVolume<FatStream>,
539	path: &str,
540) -> io::Result<FatDir<'a, FatStream>> {
541	let (parent, entry) = resolve(volume, path).await?;
542
543	match entry {
544		Some(entry) => parent.open_entry(&entry).map_err(map_err),
545		None if is_root(path) => Ok(parent),
546		None => Err(Errno::Noent),
547	}
548}
549
550/// Whether `path` names the root of the volume.
551fn is_root(path: &str) -> bool {
552	path.split('/').all(str::is_empty)
553}
554
555/// Resolves `path` to an existing file entry.
556async fn resolve_file(volume: &FatVolume<FatStream>, path: &str) -> io::Result<FileEntry> {
557	let (_, entry) = resolve(volume, path).await?;
558	let entry = entry.ok_or(Errno::Noent)?;
559
560	if entry.is_directory() {
561		return Err(Errno::Isdir);
562	}
563
564	Ok(entry)
565}
566
567/// Builds a `FileAttr`; FAT has no ownership or link count.
568fn file_attr(size: u64, kind: NodeKind) -> FileAttr {
569	let mode = match kind {
570		NodeKind::Directory => {
571			AccessPermission::from_bits(0o755).unwrap() | AccessPermission::S_IFDIR
572		}
573		NodeKind::File => AccessPermission::from_bits(0o644).unwrap() | AccessPermission::S_IFREG,
574	};
575
576	FileAttr {
577		st_size: i64::try_from(size).unwrap_or(i64::MAX),
578		st_mode: mode,
579		st_blksize: i64::try_from(SECTOR_SIZE).unwrap(),
580		st_blocks: i64::try_from(size.div_ceil(SECTOR_SIZE as u64)).unwrap_or(i64::MAX),
581		st_nlink: 1,
582		..Default::default()
583	}
584}
585
586/// Lists the entries of the directory at `path`, relative to the FAT root.
587async fn readdir_at(
588	volume: &FatVolume<FatStream>,
589	path: String,
590) -> io::Result<Vec<DirectoryEntry>> {
591	let dir = resolve_dir(volume, &path).await?;
592
593	let mut result = Vec::new();
594	let mut entries = dir.entries();
595	while let Some(entry) = entries.next_entry().await {
596		let entry = entry.map_err(map_err)?;
597		result.push(DirectoryEntry::new(entry.name().into_owned()));
598	}
599
600	Ok(result)
601}
602
603/// A directory of the FAT file system, as seen by the VFS.
604#[derive(Debug)]
605pub(crate) struct VfatDirectory {
606	/// Path of this directory relative to the FAT root, without leading slash.
607	prefix: String,
608}
609
610impl VfatDirectory {
611	pub fn new(prefix: String) -> Self {
612		Self { prefix }
613	}
614}
615
616impl VfsNode for VfatDirectory {
617	fn get_kind(&self) -> NodeKind {
618		NodeKind::Directory
619	}
620
621	fn get_file_attributes(&self) -> io::Result<FileAttr> {
622		Ok(file_attr(0, NodeKind::Directory))
623	}
624
625	fn get_object(&self) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
626		Ok(Arc::new(async_lock::RwLock::new(
627			VfatDirectoryHandle::new(self.prefix.clone()).into(),
628		)))
629	}
630
631	fn traverse_readdir(&self, path: &str) -> io::Result<Vec<DirectoryEntry>> {
632		let path = join(&self.prefix, path);
633
634		block_on(
635			async {
636				let volume = volume().await?;
637
638				readdir_at(&volume, path).await
639			},
640			None,
641		)
642	}
643
644	fn traverse_stat(&self, path: &str) -> io::Result<FileAttr> {
645		let path = join(&self.prefix, path);
646
647		block_on(
648			async {
649				let volume = volume().await?;
650
651				let (_, entry) = resolve(&volume, &path).await?;
652				let Some(entry) = entry else {
653					return if is_root(&path) {
654						Ok(file_attr(0, NodeKind::Directory))
655					} else {
656						Err(Errno::Noent)
657					};
658				};
659
660				if entry.is_directory() {
661					Ok(file_attr(0, NodeKind::Directory))
662				} else {
663					Ok(file_attr(entry.len(), NodeKind::File))
664				}
665			},
666			None,
667		)
668	}
669
670	fn traverse_lstat(&self, path: &str) -> io::Result<FileAttr> {
671		// FAT has no symbolic links.
672		self.traverse_stat(path)
673	}
674
675	fn traverse_mkdir(&self, path: &str, _mode: AccessPermission) -> io::Result<()> {
676		let path = join(&self.prefix, path);
677		let name = path.rsplit('/').next().ok_or(Errno::Inval)?;
678
679		block_on(
680			async {
681				let volume = volume().await?;
682
683				let (parent, entry) = resolve(&volume, &path).await?;
684				if entry.is_some() {
685					return Err(Errno::Exist);
686				}
687
688				volume.create_dir(&parent, name).await.map_err(map_err)?;
689
690				Ok(())
691			},
692			None,
693		)
694	}
695
696	fn traverse_rmdir(&self, path: &str) -> io::Result<()> {
697		block_on(
698			async {
699				let volume = volume().await?;
700
701				let entry = resolve(&volume, &join(&self.prefix, path))
702					.await?
703					.1
704					.ok_or(Errno::Noent)?;
705				if !entry.is_directory() {
706					return Err(Errno::Notdir);
707				}
708
709				modified();
710				volume.delete(&entry).await.map_err(map_err)
711			},
712			None,
713		)
714	}
715
716	fn traverse_unlink(&self, path: &str) -> io::Result<()> {
717		block_on(
718			async {
719				let volume = volume().await?;
720
721				let entry = resolve_file(&volume, &join(&self.prefix, path)).await?;
722
723				modified();
724				volume.delete(&entry).await.map_err(map_err)
725			},
726			None,
727		)
728	}
729
730	fn traverse_open(
731		&self,
732		path: &str,
733		opt: OpenOption,
734		_mode: AccessPermission,
735	) -> io::Result<Arc<async_lock::RwLock<Fd>>> {
736		let full = join(&self.prefix, path);
737
738		block_on(
739			async {
740				let volume = volume().await?;
741
742				let (parent, entry) = resolve(&volume, &full).await?;
743
744				// Directories are always opened as directory handle.
745				if entry
746					.as_ref()
747					.map_or(is_root(&full), FileEntry::is_directory)
748				{
749					return Ok(Arc::new(async_lock::RwLock::new(
750						VfatDirectoryHandle::new(full.clone()).into(),
751					)));
752				}
753
754				let entry = match entry {
755					Some(entry) => {
756						if opt.contains(OpenOption::O_CREAT | OpenOption::O_EXCL) {
757							return Err(Errno::Exist);
758						}
759						if opt.contains(OpenOption::O_TRUNC) {
760							modified();
761							volume.truncate(&entry, 0).await.map_err(map_err)?;
762						}
763						entry
764					}
765					None => {
766						if !opt.contains(OpenOption::O_CREAT) {
767							return Err(Errno::Noent);
768						}
769						let name = full.rsplit('/').next().ok_or(Errno::Inval)?;
770						volume.create_file(&parent, name).await.map_err(map_err)?
771					}
772				};
773
774				let pos = if opt.contains(OpenOption::O_APPEND) {
775					entry.len()
776				} else {
777					0
778				};
779
780				Ok(Arc::new(async_lock::RwLock::new(
781					VfatFileHandle::new(full.clone(), pos).into(),
782				)))
783			},
784			None,
785		)
786	}
787}
788
789/// An open file of the FAT file system.
790///
791/// Keeps the reader of the last `read`, so that sequential reads continue
792/// at the current cluster instead of resolving the path and walking the
793/// FAT chain again.
794pub(crate) struct VfatFileHandle {
795	path: String,
796	state: async_lock::Mutex<FileState>,
797}
798
799struct FileState {
800	pos: u64,
801	/// Reader and the [`GENERATION`] it was created in.
802	reader: Option<(u64, FileReader<'static, FatStream>)>,
803}
804
805// SAFETY: the reader borrows the volume, but is only used in
806// `VfatFileHandle::read` while `VFAT_LOCK` is held, and has no `Drop`.
807unsafe impl Send for FileState {}
808
809impl core::fmt::Debug for VfatFileHandle {
810	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
811		f.debug_struct("VfatFileHandle")
812			.field("path", &self.path)
813			.finish_non_exhaustive()
814	}
815}
816
817impl VfatFileHandle {
818	pub fn new(path: String, pos: u64) -> Self {
819		Self {
820			path,
821			state: async_lock::Mutex::new(FileState { pos, reader: None }),
822		}
823	}
824}
825
826impl ObjectInterface for VfatFileHandle {
827	async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
828		let volume = volume().await?;
829		let mut state = self.state.lock().await;
830		let generation = GENERATION.load(Ordering::Relaxed);
831
832		let mut reader = match state.reader.take() {
833			Some((created, reader)) if created == generation && reader.position() == state.pos => {
834				reader
835			}
836			_ => {
837				let entry = resolve_file(volume.fs, &self.path).await?;
838				let mut reader = volume
839					.fs
840					.read_file(&entry)
841					.map_err(map_err)?
842					.with_cached_chain()
843					.await
844					.map_err(map_err)?;
845				reader
846					.seek(SeekFrom::Start(state.pos))
847					.await
848					.map_err(map_err)?;
849				reader
850			}
851		};
852
853		let read = reader.read(buf).await.map_err(map_err)?;
854		state.pos += u64::try_from(read).unwrap();
855		state.reader = Some((generation, reader));
856
857		Ok(read)
858	}
859
860	async fn write(&self, buf: &[u8]) -> io::Result<usize> {
861		if buf.is_empty() {
862			return Ok(0);
863		}
864
865		let volume = volume().await?;
866		let mut entry = resolve_file(&volume, &self.path).await?;
867		let mut state = self.state.lock().await;
868		state.reader = None;
869		modified();
870
871		let start = usize::try_from(state.pos).map_err(|_| Errno::Fbig)?;
872		let end = start.checked_add(buf.len()).ok_or(Errno::Fbig)?;
873		let old_len = usize::try_from(entry.len()).map_err(|_| Errno::Fbig)?;
874
875		// `FileWriter` only appends, so data behind `start` is cut off and
876		// written again after `buf`.
877		let mut tail = Vec::new();
878		let mut gap = Vec::new();
879		if start < old_len {
880			if end < old_len {
881				let mut reader = volume.read_file(&entry).map_err(map_err)?;
882				reader
883					.seek(SeekFrom::Start(u64::try_from(end).unwrap()))
884					.await
885					.map_err(map_err)?;
886				tail = reader.read_to_vec().await.map_err(map_err)?;
887			}
888
889			volume.truncate(&entry, start).await.map_err(map_err)?;
890			entry = resolve_file(&volume, &self.path).await?;
891		} else {
892			gap.resize(start - old_len, 0);
893		}
894
895		let mut writer = FileWriter::new_append(&volume, &entry)
896			.await
897			.map_err(map_err)?;
898		for part in [gap.as_slice(), buf, tail.as_slice()] {
899			if !part.is_empty() {
900				writer.write(part).await.map_err(map_err)?;
901			}
902		}
903		writer.finish().await.map_err(map_err)?;
904
905		state.pos = u64::try_from(end).unwrap();
906
907		Ok(buf.len())
908	}
909
910	async fn lseek(&self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
911		let volume = volume().await?;
912		let mut state = self.state.lock().await;
913		let offset = i64::try_from(offset).unwrap();
914
915		let new = match whence {
916			SeekWhence::Set => offset,
917			SeekWhence::Cur => i64::try_from(state.pos).unwrap() + offset,
918			SeekWhence::End => {
919				let entry = resolve_file(&volume, &self.path).await?;
920				i64::try_from(entry.len()).unwrap() + offset
921			}
922			_ => return Err(Errno::Inval),
923		};
924
925		if new < 0 {
926			return Err(Errno::Inval);
927		}
928
929		state.pos = u64::try_from(new).unwrap();
930
931		Ok(isize::try_from(new).unwrap())
932	}
933
934	async fn fstat(&self) -> io::Result<FileAttr> {
935		let volume = volume().await?;
936		let entry = resolve_file(&volume, &self.path).await?;
937
938		Ok(file_attr(entry.len(), NodeKind::File))
939	}
940
941	async fn truncate(&self, size: usize) -> io::Result<()> {
942		let volume = volume().await?;
943		let entry = resolve_file(&volume, &self.path).await?;
944
945		modified();
946		volume.truncate(&entry, size).await.map_err(map_err)
947	}
948
949	async fn isatty(&self) -> io::Result<bool> {
950		Ok(false)
951	}
952
953	async fn fsync(&self) -> io::Result<()> {
954		volume().await?.sync().await.map_err(map_err)
955	}
956}
957
958/// An open directory of the FAT file system.
959#[derive(Debug)]
960pub(crate) struct VfatDirectoryHandle {
961	prefix: String,
962	/// Index of the next entry `getdents` will report.
963	next: async_lock::Mutex<usize>,
964}
965
966impl VfatDirectoryHandle {
967	pub fn new(prefix: String) -> Self {
968		Self {
969			prefix,
970			next: async_lock::Mutex::new(0),
971		}
972	}
973}
974
975impl ObjectInterface for VfatDirectoryHandle {
976	async fn getdents(
977		&self,
978		buf: &mut [MaybeUninit<u8>],
979		format: DirentFormat,
980	) -> io::Result<usize> {
981		let entries = {
982			let volume = volume().await?;
983			readdir_at(&volume, self.prefix.clone()).await?
984		};
985
986		let mut next = self.next.lock().await;
987		let mut offset = 0;
988
989		while let Some(entry) = entries.get(*next) {
990			let Some(next_offset) =
991				format.write_entry(buf, offset, 0, FileType::Unknown, entry.name.as_bytes())
992			else {
993				if offset == 0 {
994					return Err(Errno::Inval);
995				}
996				break;
997			};
998
999			offset = next_offset;
1000			*next += 1;
1001		}
1002
1003		Ok(offset)
1004	}
1005
1006	async fn lseek(&self, offset: isize, whence: SeekWhence) -> io::Result<isize> {
1007		if whence != SeekWhence::Set || offset != 0 {
1008			return Err(Errno::Inval);
1009		}
1010		*self.next.lock().await = 0;
1011
1012		Ok(0)
1013	}
1014
1015	async fn fstat(&self) -> io::Result<FileAttr> {
1016		Ok(file_attr(0, NodeKind::Directory))
1017	}
1018
1019	async fn fsync(&self) -> io::Result<()> {
1020		volume().await?.sync().await.map_err(map_err)
1021	}
1022}
1023
1024pub(crate) fn sync() -> io::Result<()> {
1025	block_on(
1026		async {
1027			match volume().await {
1028				Ok(v) => v.sync().await.map_err(map_err),
1029				Err(_) => Ok(()),
1030			}
1031		},
1032		None,
1033	)
1034}