diff options
| author | Manuel Bott <manuel.bott@ost.ch> | 2026-11-12 12:41:56 +0100 |
|---|---|---|
| committer | Manuel Bott <manuel.bott@ost.ch> | 2026-11-12 12:41:56 +0100 |
| commit | b343039cfd1227a1493aef1e773ce07204763d07 (patch) | |
| tree | deaebf06e5d1b13577e4ebd1c9d79bb6ea8c672e | |
| parent | acddd90e000a69470b6aafb1e74acb2caca4af58 (diff) | |
| parent | f3df6fe2537b31bb9b86d13bf02f9d01e903a524 (diff) | |
| download | kernel-b343039cfd1227a1493aef1e773ce07204763d07.tar.xz kernel-b343039cfd1227a1493aef1e773ce07204763d07.zip | |
Merge branch 'feature/writeFiles' into 'fa26/develop'
kernel/filesystems: implement fat32 write files
See merge request teachos/kernel!73
| -rw-r--r-- | kernel/kapi/filesystem.tests.cpp | 14 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/driver_state.hpp | 9 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/error.cpp | 16 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/error.hpp | 2 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/file_allocation_table.cpp | 243 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/file_allocation_table.hpp | 47 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/file_allocation_table.tests.cpp | 103 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/filesystem.cpp | 39 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/fs_info.hpp | 48 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/inode.cpp | 134 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/inode.hpp | 13 | ||||
| -rw-r--r-- | kernel/kernel/filesystems/fat32/inode.tests.cpp | 321 |
12 files changed, 981 insertions, 8 deletions
diff --git a/kernel/kapi/filesystem.tests.cpp b/kernel/kapi/filesystem.tests.cpp index f46c6bb8..f71eead0 100644 --- a/kernel/kapi/filesystem.tests.cpp +++ b/kernel/kapi/filesystem.tests.cpp @@ -12,6 +12,7 @@ #include <cstddef> #include <filesystem> #include <ranges> +#include <span> #include <string> #include <string_view> #include <utility> @@ -414,14 +415,21 @@ SCENARIO_METHOD(kernel::tests::vfs::storage_boot_module_vfs_fixture, "Kapi files REQUIRE(kapi::filesystem::read_directory(*directory, buffer) == 0); } - THEN("writing to a file fails because the filesystem is read only") + THEN("a file can be overwritten and extended through its file descriptor") { auto const fd = kapi::filesystem::open("/information/hello.txt"); REQUIRE(fd); - auto const buffer = std::vector<std::byte>{std::byte{'X'}}; - REQUIRE(kapi::filesystem::write(*fd, buffer).error() == kstd::errc::read_only_file_system); + auto const text = std::string_view{"Hello Peter! Goodbye"}; + REQUIRE(kapi::filesystem::seek(*fd, 6_B_off, kapi::filesystem::seek_origin::beginning) == 6_B); + REQUIRE(kapi::filesystem::write(*fd, std::as_bytes(std::span{text}.subspan(6))) == 14_B); REQUIRE(kapi::filesystem::close(*fd)); + + auto const reopened = kapi::filesystem::open("/information/hello.txt"); + REQUIRE(reopened); + REQUIRE(read_text(*reopened, 7) == text); + REQUIRE(kapi::filesystem::close(*reopened)); + REQUIRE(kapi::filesystem::status("/information/hello.txt")->size == 20_B); } THEN("opening a missing file fails") diff --git a/kernel/kernel/filesystems/fat32/driver_state.hpp b/kernel/kernel/filesystems/fat32/driver_state.hpp index 09e2fed2..0f25f759 100644 --- a/kernel/kernel/filesystems/fat32/driver_state.hpp +++ b/kernel/kernel/filesystems/fat32/driver_state.hpp @@ -2,6 +2,7 @@ #define TEACHOS_KERNEL_FILESYSTEMS_FAT32_DRIVER_STATE_HPP #include <kernel/filesystems/fat32/boot_sector.hpp> +#include <kernel/filesystems/fat32/fs_info.hpp> #include <kernel/vfs/driver_state.hpp> #include <kernel/vfs/inode.hpp> @@ -11,6 +12,7 @@ #include <kstd/units.hpp> #include <cstdint> +#include <optional> namespace kernel::filesystems::fat32 { @@ -26,6 +28,13 @@ namespace kernel::filesystems::fat32 std::uint32_t data_start_sector{}; std::uint32_t cluster_count{}; + //! The offset of the filesystem information sector, @c std::nullopt if the volume has no valid one. + std::optional<kstd::bytes> fs_info_offset{}; + //! The number of free clusters, @c constants::fs_info_unknown if not known. + std::uint32_t free_cluster_count{constants::fs_info_unknown}; + //! The cluster to start searching for a free cluster at, @c constants::fs_info_unknown if not known. + std::uint32_t next_free_cluster{constants::fs_info_unknown}; + mutable kapi::tracked_mutex lock{}; }; diff --git a/kernel/kernel/filesystems/fat32/error.cpp b/kernel/kernel/filesystems/fat32/error.cpp index 7ac8931e..1795107e 100644 --- a/kernel/kernel/filesystems/fat32/error.cpp +++ b/kernel/kernel/filesystems/fat32/error.cpp @@ -32,6 +32,10 @@ namespace kernel::filesystems::fat32 return "invalid cluster"; case errc::corrupted_cluster_chain: return "corrupted cluster chain"; + case errc::no_free_clusters: + return "no free clusters"; + case errc::file_too_large: + return "file too large"; default: return "unknown fat32 error"; }; @@ -56,6 +60,18 @@ namespace kernel::filesystems::fat32 return condition.value() == static_cast<int>(kstd::errc::invalid_argument); } break; + case errc::no_free_clusters: + if (condition.category() == kstd::generic_category()) + { + return condition.value() == static_cast<int>(kstd::errc::no_space_on_device); + } + break; + case errc::file_too_large: + if (condition.category() == kstd::generic_category()) + { + return condition.value() == static_cast<int>(kstd::errc::file_too_large); + } + break; } return kstd::error_category::equivalent(code, condition); } diff --git a/kernel/kernel/filesystems/fat32/error.hpp b/kernel/kernel/filesystems/fat32/error.hpp index 6b3164cc..1cc6d584 100644 --- a/kernel/kernel/filesystems/fat32/error.hpp +++ b/kernel/kernel/filesystems/fat32/error.hpp @@ -16,6 +16,8 @@ namespace kernel::filesystems::fat32 unsupported_fat_fs, invalid_cluster, corrupted_cluster_chain, + no_free_clusters, + file_too_large, }; [[nodiscard]] auto category() noexcept -> kstd::error_category const &; diff --git a/kernel/kernel/filesystems/fat32/file_allocation_table.cpp b/kernel/kernel/filesystems/fat32/file_allocation_table.cpp index 3e9b0b4a..2390c22a 100644 --- a/kernel/kernel/filesystems/fat32/file_allocation_table.cpp +++ b/kernel/kernel/filesystems/fat32/file_allocation_table.cpp @@ -2,6 +2,7 @@ #include <kernel/filesystems/fat32/driver_state.hpp> #include <kernel/filesystems/fat32/error.hpp> +#include <kernel/filesystems/fat32/fs_info.hpp> #include <kstd/result.hpp> #include <kstd/span.hpp> @@ -9,6 +10,7 @@ #include <kstd/vector.hpp> #include <algorithm> +#include <array> #include <cstddef> #include <cstdint> #include <optional> @@ -18,6 +20,46 @@ using namespace kstd::units_literals; namespace kernel::filesystems::fat32 { + //! Hidden implementation details. + namespace + { + //! The reserved upper four bits of a file allocation table entry. + constexpr auto reserved_entry_bits = ~constants::cluster_mask; + + //! Get the offset of a cluster's entry in one of the file allocation tables on the backing inode. + //! + //! @param cluster The cluster whose entry to locate. + //! @param fat_index The index of the file allocation table, 0 being the primary one. + //! @param state The driver state to operate on. + [[nodiscard]] auto fat_entry_offset(std::uint32_t cluster, std::uint32_t fat_index, driver_state const & state) + -> kstd::bytes + { + auto const fat_start_sector = state.fat_start_sector + fat_index * state.boot_sector.fat_size_32; + return fat_start_sector * state.sector_size + cluster * constants::fat_entry_size; + } + + //! Write the free cluster hints of the driver state to the filesystem information sector, if the volume has one. + //! + //! @param state The driver state to operate on. + //! @return Nothing on success, an error otherwise. + [[nodiscard]] auto write_fs_info_hints(driver_state const & state) -> kstd::result<void> + { + if (!state.fs_info_offset) + { + return {}; + } + + auto const hints = std::array{state.free_cluster_count, state.next_free_cluster}; + auto const hints_offset = *state.fs_info_offset + kstd::bytes{offsetof(fs_info, free_cluster_count)}; + if (auto const write_result = state.backing_inode->write(kstd::raw_bytes(hints), hints_offset); !write_result) + { + return kstd::failure(write_result.error()); + } + + return {}; + } + } // namespace + auto is_valid_cluster(std::uint32_t cluster, driver_state const & state) -> bool { return cluster >= constants::first_data_cluster && cluster - constants::first_data_cluster < state.cluster_count; @@ -186,4 +228,205 @@ namespace kernel::filesystems::fat32 return bytes_read; } + + auto write_fat_entry(std::uint32_t cluster, std::uint32_t value, driver_state const & state) -> kstd::result<void> + { + if (!is_valid_cluster(cluster, state)) + { + return kstd::failure(errc::invalid_cluster); + } + + for (auto fat_index = std::uint32_t{}; fat_index < state.boot_sector.number_of_fats; ++fat_index) + { + auto const entry_offset = fat_entry_offset(cluster, fat_index, state); + + auto raw_entry = std::uint32_t{}; + if (auto const read_result = state.backing_inode->read(kstd::raw_bytes(raw_entry), entry_offset); !read_result) + { + return kstd::failure(read_result.error()); + } + + raw_entry = (raw_entry & reserved_entry_bits) | (value & constants::cluster_mask); + if (auto const write_result = state.backing_inode->write(kstd::raw_bytes(raw_entry), entry_offset); !write_result) + { + return kstd::failure(write_result.error()); + } + } + + return {}; + } + + auto allocate_cluster(std::optional<std::uint32_t> previous_cluster, driver_state & state) + -> kstd::result<std::uint32_t> + { + if (previous_cluster && !is_valid_cluster(*previous_cluster, state)) + { + return kstd::failure(errc::invalid_cluster); + } + + // The hint is only a suggestion where to start searching, so an out of range hint is ignored. + auto const start_cluster = + is_valid_cluster(state.next_free_cluster, state) ? state.next_free_cluster : constants::first_data_cluster; + + for (auto offset = std::uint32_t{}; offset < state.cluster_count; ++offset) + { + auto const cluster = constants::first_data_cluster + + (start_cluster - constants::first_data_cluster + offset) % state.cluster_count; + + auto const entry = read_fat_entry(cluster, state); + if (!entry) + { + return kstd::failure(entry.error()); + } + + if (entry->type != fat_entry_type::free) + { + continue; + } + + // Terminate the new cluster before linking it, so that the chain is never left pointing into a free cluster. + if (auto const write_result = write_fat_entry(cluster, constants::end_of_chain, state); !write_result) + { + return kstd::failure(write_result.error()); + } + + if (previous_cluster) + { + if (auto const write_result = write_fat_entry(*previous_cluster, cluster, state); !write_result) + { + return kstd::failure(write_result.error()); + } + } + + state.next_free_cluster = cluster; + if (state.free_cluster_count != constants::fs_info_unknown && state.free_cluster_count > 0) + { + --state.free_cluster_count; + } + + if (auto const write_result = write_fs_info_hints(state); !write_result) + { + return kstd::failure(write_result.error()); + } + + return cluster; + } + + return kstd::failure(errc::no_free_clusters); + } + + auto ensure_clusters_allocated(std::uint32_t first_cluster, std::size_t cluster_count, driver_state & state) + -> kstd::result<void> + { + if (!is_valid_cluster(first_cluster, state)) + { + return kstd::failure(errc::invalid_cluster); + } + + if (cluster_count > state.cluster_count) + { + return kstd::failure(errc::no_free_clusters); + } + + auto current = first_cluster; + for (auto index = 1uz; index < cluster_count; ++index) + { + auto const next = next_cluster(current, state); + if (!next) + { + return kstd::failure(next.error()); + } + + if (*next) + { + current = **next; + continue; + } + + auto const allocated = allocate_cluster(current, state); + if (!allocated) + { + return kstd::failure(allocated.error()); + } + + current = *allocated; + } + + return {}; + } + + auto write_cluster_chain(std::uint32_t first_cluster, std::span<std::byte const> buffer, kstd::bytes offset, + driver_state const & state) -> kstd::result<kstd::bytes> + { + if (!is_valid_cluster(first_cluster, state)) + { + return kstd::failure(errc::invalid_cluster); + } + + // The chain was allocated up front, so running out of clusters means the chain is inconsistent. + auto const advance = [&state](std::uint32_t cluster) -> kstd::result<std::uint32_t> { + auto const next = next_cluster(cluster, state); + if (!next) + { + return kstd::failure(next.error()); + } + + if (!*next) + { + return kstd::failure(errc::corrupted_cluster_chain); + } + + return **next; + }; + + auto current = first_cluster; + for (auto clusters_to_skip = offset / state.cluster_size; clusters_to_skip > 0; --clusters_to_skip) + { + auto const next = advance(current); + if (!next) + { + return kstd::failure(next.error()); + } + + current = *next; + } + + auto const requested_size = kstd::bytes{buffer.size()}; + auto in_cluster_offset = offset % state.cluster_size; + auto bytes_written = 0_B; + + while (bytes_written < requested_size) + { + auto const bytes_to_write = std::min(requested_size - bytes_written, state.cluster_size - in_cluster_offset); + auto const write_offset = cluster_offset(current, state) + in_cluster_offset; + + auto const write_result = + state.backing_inode->write(buffer.subspan(bytes_written.value, bytes_to_write.value), write_offset); + if (!write_result) + { + return kstd::failure(write_result.error()); + } + + bytes_written += *write_result; + in_cluster_offset = 0_B; + + if (*write_result < bytes_to_write) + { + break; + } + + if (bytes_written < requested_size) + { + auto const next = advance(current); + if (!next) + { + return kstd::failure(next.error()); + } + + current = *next; + } + } + + return bytes_written; + } } // namespace kernel::filesystems::fat32 diff --git a/kernel/kernel/filesystems/fat32/file_allocation_table.hpp b/kernel/kernel/filesystems/fat32/file_allocation_table.hpp index 9601db1b..43cf2de5 100644 --- a/kernel/kernel/filesystems/fat32/file_allocation_table.hpp +++ b/kernel/kernel/filesystems/fat32/file_allocation_table.hpp @@ -89,6 +89,53 @@ namespace kernel::filesystems::fat32 //! @return The number of bytes read on success, an error otherwise. [[nodiscard]] auto read_cluster_chain(std::uint32_t first_cluster, std::span<std::byte> buffer, kstd::bytes offset, driver_state const & state) -> kstd::result<kstd::bytes>; + + //! Write the file allocation table entry of a cluster. + //! + //! The entry is written to every file allocation table of the volume. The reserved upper four bits of the entry are + //! preserved, as required by the specification. + //! + //! @param cluster The cluster whose entry to write. + //! @param value The value to store in the entry. + //! @param state The driver state to operate on. + //! @return Nothing on success, an error otherwise. + [[nodiscard]] auto write_fat_entry(std::uint32_t cluster, std::uint32_t value, driver_state const & state) + -> kstd::result<void>; + + //! Allocate a free cluster and mark it as the end of a chain. + //! + //! The search starts at the next free cluster hint of the filesystem information sector. The hints of the sector are + //! updated to reflect the allocation. + //! + //! @param previous_cluster The last cluster of the chain to append the new cluster to, @c std::nullopt to start a new + //! chain. + //! @param state The driver state to operate on. + //! @return The allocated cluster on success, an error otherwise. + [[nodiscard]] auto allocate_cluster(std::optional<std::uint32_t> previous_cluster, driver_state & state) + -> kstd::result<std::uint32_t>; + + //! Make sure that the cluster chain starting at a given cluster holds at least a given number of clusters. + //! + //! Missing clusters are allocated and appended to the end of the chain. + //! + //! @param first_cluster The first cluster of the chain. + //! @param cluster_count The number of clusters the chain must hold. + //! @param state The driver state to operate on. + //! @return Nothing on success, an error otherwise. + [[nodiscard]] auto ensure_clusters_allocated(std::uint32_t first_cluster, std::size_t cluster_count, + driver_state & state) -> kstd::result<void>; + + //! Write data into the cluster chain starting at a given cluster. + //! + //! The chain must already hold enough clusters for the whole buffer, see @p ensure_clusters_allocated(). + //! + //! @param first_cluster The first cluster of the chain. + //! @param buffer The data to write. + //! @param offset The offset inside the chain's data to start at. + //! @param state The driver state to operate on. + //! @return The number of bytes written on success, an error otherwise. + [[nodiscard]] auto write_cluster_chain(std::uint32_t first_cluster, std::span<std::byte const> buffer, + kstd::bytes offset, driver_state const & state) -> kstd::result<kstd::bytes>; } // namespace kernel::filesystems::fat32 #endif diff --git a/kernel/kernel/filesystems/fat32/file_allocation_table.tests.cpp b/kernel/kernel/filesystems/fat32/file_allocation_table.tests.cpp index 5b8add68..e6f56728 100644 --- a/kernel/kernel/filesystems/fat32/file_allocation_table.tests.cpp +++ b/kernel/kernel/filesystems/fat32/file_allocation_table.tests.cpp @@ -368,4 +368,107 @@ SCENARIO("Fat32 cluster chain reading", "[filesystem][fat32][fat]") } } +SCENARIO("Fat32 cluster allocation on a mock layout", "[filesystem][fat32][fat][write]") +{ + auto const block_size = 512_B; + + GIVEN("a mounted minimal fat32 layout") + { + auto device = kstd::make_shared<kernel::tests::devices::block_device>("mock", block_size, 18 * block_size); + kernel::tests::filesystems::fat32::setup_mock_fat32_layout(*device); + + auto dev_inode = kstd::make_shared<kernel::vfs::device_inode>(device); + auto fs = kstd::make_shared<kernel::filesystems::fat32::filesystem>(); + auto mount = fs->mount(dev_inode); + REQUIRE(mount); + auto driver_state = static_pointer_cast<kernel::filesystems::fat32::driver_state>(mount->second); + REQUIRE(driver_state); + + using namespace kernel::filesystems::fat32; + using kernel::tests::filesystems::fat32::write_fat_entry; + + THEN("writing an entry preserves its reserved upper bits") + { + write_fat_entry(*device, 3, 0xF000'0000); + REQUIRE(kernel::filesystems::fat32::write_fat_entry(3, 0xFFFF'FFF8, *driver_state)); + + auto raw_entry = std::uint32_t{}; + REQUIRE(dev_inode->read(kstd::raw_bytes(raw_entry), 512_B + 3 * constants::fat_entry_size)); + REQUIRE(raw_entry == 0xFFFF'FFF8); + } + + THEN("writing the entry of an invalid cluster fails") + { + REQUIRE(kernel::filesystems::fat32::write_fat_entry(1, 0, *driver_state).error() == errc::invalid_cluster); + } + + THEN("a new chain starts at the first free cluster") + { + auto const cluster = allocate_cluster(std::nullopt, *driver_state); + REQUIRE(cluster == 3u); + REQUIRE(next_cluster(3, *driver_state) == std::nullopt); + REQUIRE(driver_state->next_free_cluster == 3); + } + + THEN("an allocated cluster is appended to the given chain") + { + auto const cluster = allocate_cluster(2u, *driver_state); + REQUIRE(cluster == 3u); + REQUIRE(next_cluster(2, *driver_state) == 3u); + REQUIRE(next_cluster(3, *driver_state) == std::nullopt); + } + + THEN("the search starts at the next free cluster hint and wraps around") + { + driver_state->cluster_count = 8; + driver_state->next_free_cluster = 8; + write_fat_entry(*device, 8, 0x0FFF'FFFF); + write_fat_entry(*device, 9, 0x0FFF'FFFF); + + REQUIRE(allocate_cluster(std::nullopt, *driver_state) == 3u); + } + + THEN("the free cluster count is decremented if it is known") + { + driver_state->free_cluster_count = 10; + REQUIRE(allocate_cluster(std::nullopt, *driver_state)); + REQUIRE(driver_state->free_cluster_count == 9); + } + + THEN("allocation fails if no cluster is free") + { + driver_state->cluster_count = 2; + write_fat_entry(*device, 3, 0x0FFF'FFFF); + REQUIRE(allocate_cluster(std::nullopt, *driver_state).error() == errc::no_free_clusters); + } + + THEN("a chain is extended to the requested number of clusters") + { + REQUIRE(ensure_clusters_allocated(2, 3, *driver_state)); + auto const chain = cluster_chain(2, *driver_state); + REQUIRE(chain); + REQUIRE(chain->size() == 3); + } + + THEN("data written across clusters can be read back") + { + REQUIRE(ensure_clusters_allocated(2, 2, *driver_state)); + + auto data = std::array<std::byte, 600>{}; + std::ranges::fill(data, std::byte{0x5A}); + REQUIRE(write_cluster_chain(2, data, 100_B, *driver_state) == 600_B); + + auto buffer = std::array<std::byte, 600>{}; + REQUIRE(read_cluster_chain(2, buffer, 100_B, *driver_state) == 600_B); + REQUIRE(buffer == data); + } + + THEN("writing past the end of an unextended chain reports a corrupted chain") + { + auto data = std::array<std::byte, 600>{}; + REQUIRE(write_cluster_chain(2, data, 0_B, *driver_state).error() == errc::corrupted_cluster_chain); + } + } +} + // NOLINTEND(readability-magic-numbers) diff --git a/kernel/kernel/filesystems/fat32/filesystem.cpp b/kernel/kernel/filesystems/fat32/filesystem.cpp index 51f0d63e..be104f20 100644 --- a/kernel/kernel/filesystems/fat32/filesystem.cpp +++ b/kernel/kernel/filesystems/fat32/filesystem.cpp @@ -6,6 +6,7 @@ #include <kernel/filesystems/fat32/driver_state.hpp> #include <kernel/filesystems/fat32/error.hpp> #include <kernel/filesystems/fat32/file_allocation_table.hpp> +#include <kernel/filesystems/fat32/fs_info.hpp> #include <kernel/filesystems/fat32/inode.hpp> #include <kernel/vfs/error.hpp> #include <kernel/vfs/filesystem.hpp> @@ -199,6 +200,39 @@ namespace kernel::filesystems::fat32 state.data_start_sector = static_cast<std::uint32_t>(data_start_sector); state.cluster_count = static_cast<std::uint32_t>(cluster_count); } + + //! Read the free cluster hints from the filesystem information sector, if the volume has a valid one. + //! + //! The sector is optional, so a missing or invalid sector is not an error. The hints then remain unknown. + //! + //! @param state The driver state whose boot sector to use and whose hint fields to fill. + //! @return Nothing on success, an error if the sector could not be read. + [[nodiscard]] auto read_fs_info(driver_state & state) -> kstd::result<void> + { + auto const fs_info_sector = state.boot_sector.filesystem_info_sector; + if (fs_info_sector == 0 || fs_info_sector >= state.boot_sector.reserved_sector_count) + { + return {}; + } + + auto const fs_info_offset = fs_info_sector * state.sector_size; + auto fs_info = fat32::fs_info{}; + if (auto const read_result = state.backing_inode->read(kstd::raw_bytes(fs_info), fs_info_offset); !read_result) + { + return kstd::failure(read_result.error()); + } + + if (!fs_info.is_valid()) + { + return {}; + } + + state.fs_info_offset = fs_info_offset; + state.free_cluster_count = + fs_info.free_cluster_count <= state.cluster_count ? fs_info.free_cluster_count : constants::fs_info_unknown; + state.next_free_cluster = fs_info.next_free_cluster; + return {}; + } } // namespace auto filesystem::probe(inode_ptr const & inode) const -> kstd::result<std::uint32_t> @@ -233,6 +267,11 @@ namespace kernel::filesystems::fat32 compute_layout(*driver_state); + if (auto const fs_info_result = read_fs_info(*driver_state); !fs_info_result) + { + return kstd::failure(fs_info_result.error()); + } + auto const root_cluster = std::uint32_t{driver_state->boot_sector.root_cluster}; if (!is_valid_cluster(root_cluster, *driver_state)) { diff --git a/kernel/kernel/filesystems/fat32/fs_info.hpp b/kernel/kernel/filesystems/fat32/fs_info.hpp new file mode 100644 index 00000000..754f06b1 --- /dev/null +++ b/kernel/kernel/filesystems/fat32/fs_info.hpp @@ -0,0 +1,48 @@ +#ifndef TEACHOS_KERNEL_FILESYSTEMS_FAT32_FS_INFO_HPP +#define TEACHOS_KERNEL_FILESYSTEMS_FAT32_FS_INFO_HPP + +#include <array> +#include <cstdint> + +namespace kernel::filesystems::fat32 +{ + //! Constants related to the fat32 filesystem information sector. + namespace constants + { + constexpr std::uint32_t inline fs_info_lead_signature = 0x4161'5252; + constexpr std::uint32_t inline fs_info_struct_signature = 0x6141'7272; + constexpr std::uint32_t inline fs_info_trail_signature = 0xAA55'0000; + + //! The value of the free cluster count and next free cluster hints if they are not known. + constexpr std::uint32_t inline fs_info_unknown = 0xFFFF'FFFF; + } // namespace constants + + //! The filesystem information sector (FSInfo) in the fat32 filesystem. + //! + //! The sector holds hints about the free clusters of the volume, which spare the driver from scanning the file + //! allocation table. The hints are not guaranteed to be accurate and must be validated before use. The layout follows + //! the "Microsoft Extensible Firmware Initiative FAT32 File System Specification" (fatgen103). + // cspell:ignore fatgen + struct [[gnu::packed]] fs_info + { + //! Check if all signatures of this sector are valid. + [[nodiscard]] constexpr auto is_valid() const noexcept -> bool + { + return lead_signature == constants::fs_info_lead_signature && + struct_signature == constants::fs_info_struct_signature && + trail_signature == constants::fs_info_trail_signature; + } + + std::uint32_t lead_signature; + std::array<std::uint8_t, 480> reserved; // NOLINT(readability-magic-numbers) + std::uint32_t struct_signature; + std::uint32_t free_cluster_count; + std::uint32_t next_free_cluster; + std::array<std::uint8_t, 12> reserved1; // NOLINT(readability-magic-numbers) + std::uint32_t trail_signature; + }; + + static_assert(sizeof(fs_info) == 512, "The fat32 filesystem information sector must be exactly 512 bytes in size."); +} // namespace kernel::filesystems::fat32 + +#endif diff --git a/kernel/kernel/filesystems/fat32/inode.cpp b/kernel/kernel/filesystems/fat32/inode.cpp index 28b642ef..694c261d 100644 --- a/kernel/kernel/filesystems/fat32/inode.cpp +++ b/kernel/kernel/filesystems/fat32/inode.cpp @@ -13,11 +13,14 @@ #include <kstd/memory.hpp> #include <kstd/mutex.hpp> #include <kstd/result.hpp> +#include <kstd/span.hpp> #include <kstd/units.hpp> #include <algorithm> +#include <array> #include <cstddef> #include <cstdint> +#include <optional> #include <span> #include <utility> @@ -25,6 +28,16 @@ using namespace kstd::units_literals; namespace kernel::filesystems::fat32 { + //! Hidden implementation details. + namespace + { + //! The largest file size a directory entry can describe. + constexpr auto max_file_size = kstd::bytes{0xFFFF'FFFF}; + + //! The size of the chunks in which gaps behind the end of a file are zero filled. + constexpr auto zero_fill_chunk_size = 512_B; + } // namespace + inode::inode(std::uint32_t first_cluster, std::uint8_t attributes, kstd::bytes size, std::uint64_t inode_number) : m_first_cluster(first_cluster) , m_attributes(attributes) @@ -35,7 +48,9 @@ namespace kernel::filesystems::fat32 inode::inode(directory_record const & record) : inode(record.entry.first_cluster(), record.entry.attributes, kstd::bytes{record.entry.file_size}, record.inode_number()) - {} + { + m_entry_location = record.location; + } auto inode::read(std::span<std::byte> buffer, kstd::bytes offset) const -> kstd::result<kstd::bytes> { @@ -74,9 +89,102 @@ namespace kernel::filesystems::fat32 return *read_result; } - auto inode::write(std::span<std::byte const>, kstd::bytes) -> kstd::result<kstd::bytes> + auto inode::write(std::span<std::byte const> buffer, kstd::bytes offset) -> kstd::result<kstd::bytes> { - return kstd::failure(vfs::errc::read_only_file_system); + if (is_directory()) + { + return kstd::failure(vfs::errc::is_a_directory); + } + + if (!is_regular()) + { + return kstd::failure(vfs::errc::invalid_inode); + } + + auto state = static_pointer_cast<fat32::driver_state>(driver_state().lock()); + if (!state || !state->backing_inode) + { + return kstd::failure(vfs::errc::not_mounted); + } + + // Without its directory entry, the new size of the file could not be persisted. + if (!m_entry_location) + { + return kstd::failure(vfs::errc::invalid_inode); + } + + if (buffer.empty()) + { + return 0_B; + } + + auto const write_end = offset + kstd::bytes{buffer.size()}; + if (write_end < offset || write_end > max_file_size) + { + return kstd::failure(errc::file_too_large); + } + + auto guard = kstd::lock_guard{state->lock}; + + // An empty file owns no cluster, so the chain has to be started first. + if (m_first_cluster == 0) + { + auto const first_cluster = allocate_cluster(std::nullopt, *state); + if (!first_cluster) + { + return kstd::failure(first_cluster.error()); + } + + m_first_cluster = *first_cluster; + if (auto const entry_result = write_directory_entry(*state); !entry_result) + { + return kstd::failure(entry_result.error()); + } + } + + auto const cluster_count = (write_end + state->cluster_size - 1_B) / state->cluster_size; + if (auto const allocation_result = ensure_clusters_allocated(m_first_cluster, cluster_count, *state); + !allocation_result) + { + return kstd::failure(allocation_result.error()); + } + + // Writing behind the end of the file leaves a gap, which must read as zeros instead of stale cluster contents. + for (auto gap_offset = m_size; gap_offset < offset;) + { + auto const zeros = std::array<std::byte, zero_fill_chunk_size.value>{}; + auto const chunk = std::span{zeros}.first(std::min(offset - gap_offset, zero_fill_chunk_size).value); + auto const fill_result = write_cluster_chain(m_first_cluster, chunk, gap_offset, *state); + if (!fill_result) + { + return kstd::failure(fill_result.error()); + } + + // The backing inode is full, so none of the buffer could be written behind the gap. + if (*fill_result == 0_B) + { + return 0_B; + } + + gap_offset += *fill_result; + } + + auto const write_result = write_cluster_chain(m_first_cluster, buffer, offset, *state); + if (!write_result) + { + return kstd::failure(write_result.error()); + } + + if (auto const new_size = offset + *write_result; new_size > m_size) + { + m_size = new_size; + if (auto const entry_result = write_directory_entry(*state); !entry_result) + { + return kstd::failure(entry_result.error()); + } + } + + return *write_result; } auto inode::is_directory() const -> bool @@ -160,4 +268,24 @@ namespace kernel::filesystems::fat32 { return m_size; } + + auto inode::write_directory_entry(fat32::driver_state const & state) const -> kstd::result<void> + { + auto entry = directory_entry{}; + if (auto const read_result = state.backing_inode->read(kstd::raw_bytes(entry), *m_entry_location); !read_result) + { + return kstd::failure(read_result.error()); + } + + entry.first_cluster_high = static_cast<std::uint16_t>(m_first_cluster >> 16); + entry.first_cluster_low = static_cast<std::uint16_t>(m_first_cluster); + entry.file_size = static_cast<std::uint32_t>(m_size.value); + + if (auto const write_result = state.backing_inode->write(kstd::raw_bytes(entry), *m_entry_location); !write_result) + { + return kstd::failure(write_result.error()); + } + + return {}; + } } // namespace kernel::filesystems::fat32 diff --git a/kernel/kernel/filesystems/fat32/inode.hpp b/kernel/kernel/filesystems/fat32/inode.hpp index 82a8547c..55fc1d13 100644 --- a/kernel/kernel/filesystems/fat32/inode.hpp +++ b/kernel/kernel/filesystems/fat32/inode.hpp @@ -2,6 +2,7 @@ #define TEACHOS_KERNEL_FILESYSTEMS_FAT32_INODE_HPP #include <kernel/filesystems/fat32/directory_iterator.hpp> +#include <kernel/filesystems/fat32/driver_state.hpp> #include <kernel/vfs/inode.hpp> #include <kapi/filesystem.hpp> @@ -14,6 +15,7 @@ #include <cstddef> #include <cstdint> +#include <optional> #include <span> #include <utility> @@ -32,6 +34,9 @@ namespace kernel::filesystems::fat32 //! Create a fat32 inode for the file described by a directory record. //! + //! Only inodes created from a record can be written to, since the record locates the directory entry that has to be + //! updated when the file grows. + //! //! @param record The record describing the inode. explicit inode(directory_record const & record); @@ -62,10 +67,18 @@ namespace kernel::filesystems::fat32 [[nodiscard]] auto size() const -> kstd::bytes; private: + //! Store the first cluster and size of this inode in the directory entry describing it. + //! + //! @param state The driver state to operate on. + //! @return Nothing on success, an error otherwise. + [[nodiscard]] auto write_directory_entry(fat32::driver_state const & state) const -> kstd::result<void>; + std::uint32_t m_first_cluster{}; std::uint8_t m_attributes{}; kstd::bytes m_size{}; std::uint64_t m_inode_number{}; + //! The offset of the directory entry describing this inode on the backing inode, if it has one. + std::optional<kstd::bytes> m_entry_location{}; }; } // namespace kernel::filesystems::fat32 diff --git a/kernel/kernel/filesystems/fat32/inode.tests.cpp b/kernel/kernel/filesystems/fat32/inode.tests.cpp index ee878f23..2f5822a0 100644 --- a/kernel/kernel/filesystems/fat32/inode.tests.cpp +++ b/kernel/kernel/filesystems/fat32/inode.tests.cpp @@ -7,6 +7,7 @@ #include <kernel/filesystems/fat32/error.hpp> #include <kernel/filesystems/fat32/file_allocation_table.hpp> #include <kernel/filesystems/fat32/filesystem.hpp> +#include <kernel/filesystems/fat32/fs_info.hpp> #include <kernel/test_support/devices/block_device.hpp> #include <kernel/test_support/filesystems/fat32.hpp> #include <kernel/test_support/vfs/storage_boot_module_fixture.hpp> @@ -17,6 +18,8 @@ #include <kapi/filesystem.hpp> #include <kstd/memory.hpp> +#include <kstd/span.hpp> +#include <kstd/system_error.hpp> #include <kstd/units.hpp> #include <kstd/vector.hpp> @@ -27,6 +30,7 @@ #include <cstddef> #include <cstdint> #include <filesystem> +#include <optional> #include <span> #include <string> #include <string_view> @@ -178,10 +182,10 @@ SCENARIO("Fat32 inode read/write without a mount", "[filesystem][fat32][inode]") kstd::vector<std::byte> buffer(10, std::byte{'x'}); auto bytes_written = inode.write(buffer, 0_B); - THEN("the write fails because the filesystem is read only") + THEN("the write fails because the inode is not mounted") { REQUIRE_FALSE(bytes_written); - REQUIRE(bytes_written.error() == kernel::vfs::errc::read_only_file_system); + REQUIRE(bytes_written.error() == kernel::vfs::errc::not_mounted); } } } @@ -552,4 +556,317 @@ SCENARIO_METHOD(kernel::tests::vfs::storage_boot_module_fixture, "Fat32 inode re } } +SCENARIO("Fat32 inode writes file data on a mock layout", "[filesystem][fat32][inode][write]") +{ + auto const block_size = 512_B; + + GIVEN("a mounted minimal fat32 layout with a file in the root directory") + { + using namespace kernel::filesystems::fat32; + using kernel::tests::filesystems::fat32::make_entry; + + auto device = kstd::make_shared<kernel::tests::devices::block_device>("mock", block_size, 18 * block_size); + kernel::tests::filesystems::fat32::setup_mock_fat32_layout(*device); + kernel::tests::filesystems::fat32::write_directory_entries( + *device, 2, + std::array{ + make_entry("HELLO TXT", constants::attribute_archive, 3), + make_entry("EMPTY TXT", constants::attribute_archive), + make_entry("DIR", constants::attribute_directory, 5), + }); + kernel::tests::filesystems::fat32::write_fat_entry(*device, 3, 0x0FFF'FFFF); + kernel::tests::filesystems::fat32::write_fat_entry(*device, 5, 0x0FFF'FFFF); + + auto dev_inode = kstd::make_shared<kernel::vfs::device_inode>(device); + auto fs = kstd::make_shared<kernel::filesystems::fat32::filesystem>(); + auto mount = fs->mount(dev_inode); + REQUIRE(mount); + auto [root, driver_data] = *mount; + auto state = static_pointer_cast<driver_state>(driver_data); + + auto const open_file = [&](std::string_view name) { + auto const looked_up = fs->lookup(root, name, driver_data); + REQUIRE(looked_up); + auto file = static_pointer_cast<kernel::filesystems::fat32::inode>(*looked_up); + file->set_driver_state(driver_data); + return file; + }; + + auto const read_all = [](kernel::filesystems::fat32::inode const & file) { + auto buffer = std::vector<std::byte>(file.size().value); + auto const result = file.read(buffer, 0_B); + REQUIRE(result); + REQUIRE(*result == file.size()); + return buffer; + }; + + auto const as_bytes = [](std::string_view text) { + auto const bytes = std::as_bytes(std::span{text}); + return std::vector<std::byte>{bytes.begin(), bytes.end()}; + }; + + auto const file = open_file("hello.txt"); + + WHEN("writing an empty buffer") + { + auto const result = file->write(std::span<std::byte const>{}, 0_B); + + THEN("no bytes are written and the size is unchanged") + { + REQUIRE(result == 0_B); + REQUIRE(file->size() == 0_B); + } + } + + WHEN("writing at the start of the file") + { + auto const result = file->write(as_bytes("Hello"), 0_B); + + THEN("the data can be read back and the size grows") + { + REQUIRE(result == 5_B); + REQUIRE(file->size() == 5_B); + REQUIRE(read_all(*file) == as_bytes("Hello")); + } + + THEN("the new size is persisted in the directory entry") + { + auto const reopened = open_file("hello.txt"); + REQUIRE(reopened->size() == 5_B); + REQUIRE(read_all(*reopened) == as_bytes("Hello")); + } + } + + WHEN("overwriting data inside the file") + { + REQUIRE(file->write(as_bytes("Hello World!"), 0_B)); + auto const result = file->write(as_bytes("Peter"), 6_B); + + THEN("the data is replaced and the size is unchanged") + { + REQUIRE(result == 5_B); + REQUIRE(file->size() == 12_B); + REQUIRE(read_all(*file) == as_bytes("Hello Peter!")); + } + } + + WHEN("overwriting data across the end of the file") + { + REQUIRE(file->write(as_bytes("Hello World!"), 0_B)); + auto const result = file->write(as_bytes("Peter! Goodbye"), 6_B); + + THEN("the file is extended") + { + REQUIRE(result == 14_B); + REQUIRE(file->size() == 20_B); + REQUIRE(read_all(*file) == as_bytes("Hello Peter! Goodbye")); + } + } + + WHEN("writing exactly one cluster") + { + REQUIRE(file->write(std::vector<std::byte>(cluster_size), 0_B) == kstd::bytes{cluster_size}); + + THEN("no further cluster is allocated") + { + REQUIRE(next_cluster(3, *state) == std::nullopt); + } + } + + WHEN("writing one byte more than a cluster") + { + auto const data = expected_bytes(0, cluster_size + 1); + REQUIRE(file->write(data, 0_B) == kstd::bytes{cluster_size + 1}); + + THEN("a second cluster is allocated and the data can be read back") + { + auto const chain = cluster_chain(3, *state); + REQUIRE(chain); + REQUIRE(chain->size() == 2); + REQUIRE(read_all(*file) == data); + } + } + + WHEN("writing a single byte at the end of the first cluster") + { + REQUIRE(file->write(as_bytes("x"), kstd::bytes{cluster_size - 1}) == 1_B); + + THEN("no further cluster is allocated") + { + REQUIRE(next_cluster(3, *state) == std::nullopt); + REQUIRE(file->size() == kstd::bytes{cluster_size}); + } + } + + WHEN("writing a single byte at the start of the second cluster") + { + REQUIRE(file->write(as_bytes("x"), kstd::bytes{cluster_size}) == 1_B); + + THEN("a second cluster is allocated") + { + REQUIRE(next_cluster(3, *state) != std::nullopt); + REQUIRE(file->size() == kstd::bytes{cluster_size + 1}); + } + } + + WHEN("writing behind the end of the file into clusters holding stale data") + { + kernel::tests::filesystems::fat32::write_cluster_data(*device, 4, + std::vector<std::byte>(cluster_size, std::byte{0xEE})); + REQUIRE(file->write(as_bytes("Hi"), 0_B)); + REQUIRE(file->write(as_bytes("!"), kstd::bytes{cluster_size + 10})); + + THEN("the gap reads as zeros") + { + auto expected = std::vector<std::byte>(cluster_size + 11); + expected[0] = std::byte{'H'}; + expected[1] = std::byte{'i'}; + expected[cluster_size + 10] = std::byte{'!'}; + REQUIRE(read_all(*file) == expected); + } + } + + WHEN("writing to an empty file without a cluster") + { + auto const empty = open_file("empty.txt"); + REQUIRE(empty->first_cluster() == 0); + REQUIRE(empty->write(as_bytes("data"), 0_B) == 4_B); + + THEN("a first cluster is allocated and stored in the directory entry") + { + REQUIRE(empty->first_cluster() == 4); + + auto const reopened = open_file("empty.txt"); + REQUIRE(reopened->first_cluster() == 4); + REQUIRE(read_all(*reopened) == as_bytes("data")); + } + } + + WHEN("the volume has no free cluster left") + { + state->cluster_count = 4; + kernel::tests::filesystems::fat32::write_fat_entry(*device, 4, 0x0FFF'FFFF); + + THEN("growing the file fails") + { + auto const result = file->write(std::vector<std::byte>(cluster_size + 1), 0_B); + REQUIRE_FALSE(result); + REQUIRE(result.error() == errc::no_free_clusters); + REQUIRE(result.error() == kstd::errc::no_space_on_device); + } + + THEN("writing within the allocated cluster still succeeds") + { + REQUIRE(file->write(std::vector<std::byte>(cluster_size), 0_B) == kstd::bytes{cluster_size}); + } + } + + WHEN("writing past the largest file size") + { + auto const result = file->write(as_bytes("x"), kstd::bytes{0xFFFF'FFFF}); + + THEN("the write fails because the file would be too large") + { + REQUIRE_FALSE(result); + REQUIRE(result.error() == errc::file_too_large); + } + } + + WHEN("writing to a directory") + { + auto const result = open_file("dir")->write(as_bytes("x"), 0_B); + + THEN("the write fails because it is a directory") + { + REQUIRE_FALSE(result); + REQUIRE(result.error() == kernel::vfs::errc::is_a_directory); + } + } + + WHEN("writing to a file inode without a directory entry") + { + auto orphan = kstd::make_shared<kernel::filesystems::fat32::inode>(3, constants::attribute_archive); + orphan->set_driver_state(driver_data); + auto const result = orphan->write(as_bytes("x"), 0_B); + + THEN("the write fails because the size could not be persisted") + { + REQUIRE_FALSE(result); + REQUIRE(result.error() == kernel::vfs::errc::invalid_inode); + } + } + } +} + +SCENARIO_METHOD(kernel::tests::vfs::storage_boot_module_fixture, "Fat32 inode writes to a real image", + "[filesystem][fat32][inode][write][img]") +{ + auto const image_path = std::filesystem::path{KERNEL_TEST_ASSETS_DIR} / "fat32.img"; + + GIVEN("a mounted fat32 filesystem from a real image") + { + using namespace kernel::filesystems::fat32; + + REQUIRE(std::filesystem::exists(image_path)); + REQUIRE_NOTHROW(setup_modules_from_img({"test_img_module"}, {image_path})); + + auto boot_device = kernel::devices::storage::determine_boot_device(); + REQUIRE(boot_device); + + auto dev_inode = kstd::make_shared<kernel::vfs::device_inode>(boot_device); + auto fs = kstd::make_shared<kernel::filesystems::fat32::filesystem>(); + auto mount = fs->mount(dev_inode); + REQUIRE(mount); + auto [root, driver_data] = *mount; + auto state = static_pointer_cast<driver_state>(driver_data); + + auto const looked_up = fs->lookup(root, "hello.txt", driver_data); + REQUIRE(looked_up); + auto file = static_pointer_cast<kernel::filesystems::fat32::inode>(*looked_up); + file->set_driver_state(driver_data); + + REQUIRE(state->fs_info_offset); + auto const free_clusters_before = state->free_cluster_count; + + WHEN("the file grows beyond its first cluster") + { + auto const data = expected_bytes(0, cluster_size + 100); + REQUIRE(file->write(data, 0_B) == kstd::bytes{data.size()}); + + THEN("the data can be read back") + { + auto buffer = std::vector<std::byte>(data.size()); + REQUIRE(file->read(buffer, 0_B) == kstd::bytes{data.size()}); + REQUIRE(buffer == data); + } + + THEN("the new cluster is linked in both file allocation tables") + { + auto const second = next_cluster(file->first_cluster(), *state); + REQUIRE(second); + REQUIRE(*second); + + auto const fat_size = state->boot_sector.fat_size_32 * state->sector_size; + for (auto fat_index = 0uz; fat_index < state->boot_sector.number_of_fats; ++fat_index) + { + auto raw_entry = std::uint32_t{}; + auto const entry_offset = state->fat_start_sector * state->sector_size + fat_index * fat_size + + file->first_cluster() * constants::fat_entry_size; + REQUIRE(dev_inode->read(kstd::raw_bytes(raw_entry), entry_offset)); + REQUIRE((raw_entry & constants::cluster_mask) == **second); + } + } + + THEN("the filesystem information sector reflects the allocation") + { + auto fs_info = kernel::filesystems::fat32::fs_info{}; + REQUIRE(dev_inode->read(kstd::raw_bytes(fs_info), *state->fs_info_offset)); + REQUIRE(fs_info.is_valid()); + REQUIRE(fs_info.free_cluster_count == free_clusters_before - 1); + REQUIRE(fs_info.next_free_cluster == *next_cluster(file->first_cluster(), *state).value()); + } + } + } +} + // NOLINTEND(readability-magic-numbers) |
