FATFileSystem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright (c) 2022, Undefine <undefine@undefine.pl>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Time.h>
  7. #include <Kernel/Debug.h>
  8. #include <Kernel/Devices/BlockDevice.h>
  9. #include <Kernel/FileSystem/FATFileSystem.h>
  10. #include <Kernel/Memory/Region.h>
  11. namespace Kernel {
  12. ErrorOr<NonnullLockRefPtr<FileSystem>> FATFS::try_create(OpenFileDescription& file_description)
  13. {
  14. return TRY(adopt_nonnull_lock_ref_or_enomem(new (nothrow) FATFS(file_description)));
  15. }
  16. FATFS::FATFS(OpenFileDescription& file_description)
  17. : BlockBasedFileSystem(file_description)
  18. {
  19. }
  20. ErrorOr<void> FATFS::initialize()
  21. {
  22. MutexLocker locker(m_lock);
  23. m_boot_record = TRY(KBuffer::try_create_with_size("FATFS: Boot Record"sv, m_logical_block_size));
  24. auto boot_record_buffer = UserOrKernelBuffer::for_kernel_buffer(m_boot_record->data());
  25. TRY(raw_read(0, boot_record_buffer));
  26. if constexpr (FAT_DEBUG) {
  27. dbgln("FATFS: oem_identifier: {}", boot_record()->oem_identifier);
  28. dbgln("FATFS: bytes_per_sector: {}", boot_record()->bytes_per_sector);
  29. dbgln("FATFS: sectors_per_cluster: {}", boot_record()->sectors_per_cluster);
  30. dbgln("FATFS: reserved_sector_count: {}", boot_record()->reserved_sector_count);
  31. dbgln("FATFS: fat_count: {}", boot_record()->fat_count);
  32. dbgln("FATFS: root_directory_entry_count: {}", boot_record()->root_directory_entry_count);
  33. dbgln("FATFS: media_descriptor_type: {}", boot_record()->media_descriptor_type);
  34. dbgln("FATFS: sectors_per_track: {}", boot_record()->sectors_per_track);
  35. dbgln("FATFS: head_count: {}", boot_record()->head_count);
  36. dbgln("FATFS: hidden_sector_count: {}", boot_record()->hidden_sector_count);
  37. dbgln("FATFS: sector_count: {}", boot_record()->sector_count);
  38. dbgln("FATFS: sectors_per_fat: {}", boot_record()->sectors_per_fat);
  39. dbgln("FATFS: flags: {}", boot_record()->flags);
  40. dbgln("FATFS: fat_version: {}", boot_record()->fat_version);
  41. dbgln("FATFS: root_directory_cluster: {}", boot_record()->root_directory_cluster);
  42. dbgln("FATFS: fs_info_sector: {}", boot_record()->fs_info_sector);
  43. dbgln("FATFS: backup_boot_sector: {}", boot_record()->backup_boot_sector);
  44. dbgln("FATFS: drive_number: {}", boot_record()->drive_number);
  45. dbgln("FATFS: volume_id: {}", boot_record()->volume_id);
  46. }
  47. if (boot_record()->signature != signature_1 && boot_record()->signature != signature_2) {
  48. dbgln("FATFS: Invalid signature");
  49. return EINVAL;
  50. }
  51. m_logical_block_size = boot_record()->bytes_per_sector;
  52. set_block_size(m_logical_block_size);
  53. u32 root_directory_sectors = ((boot_record()->root_directory_entry_count * sizeof(FATEntry)) + (m_logical_block_size - 1)) / m_logical_block_size;
  54. m_first_data_sector = boot_record()->reserved_sector_count + (boot_record()->fat_count * boot_record()->sectors_per_fat) + root_directory_sectors;
  55. TRY(BlockBasedFileSystem::initialize());
  56. FATEntry root_entry {};
  57. root_entry.first_cluster_low = boot_record()->root_directory_cluster & 0xFFFF;
  58. root_entry.first_cluster_high = boot_record()->root_directory_cluster >> 16;
  59. root_entry.attributes = FATAttributes::Directory;
  60. m_root_inode = TRY(FATInode::create(*this, root_entry));
  61. return {};
  62. }
  63. Inode& FATFS::root_inode()
  64. {
  65. return *m_root_inode;
  66. }
  67. BlockBasedFileSystem::BlockIndex FATFS::first_block_of_cluster(u32 cluster) const
  68. {
  69. return ((cluster - first_data_cluster) * boot_record()->sectors_per_cluster) + m_first_data_sector;
  70. }
  71. ErrorOr<NonnullLockRefPtr<FATInode>> FATInode::create(FATFS& fs, FATEntry entry, Vector<FATLongFileNameEntry> const& lfn_entries)
  72. {
  73. auto filename = TRY(compute_filename(entry, lfn_entries));
  74. return adopt_nonnull_lock_ref_or_enomem(new (nothrow) FATInode(fs, entry, move(filename)));
  75. }
  76. FATInode::FATInode(FATFS& fs, FATEntry entry, NonnullOwnPtr<KString> filename)
  77. : Inode(fs, first_cluster())
  78. , m_entry(entry)
  79. , m_filename(move(filename))
  80. {
  81. dbgln_if(FAT_DEBUG, "FATFS: Creating inode {} with filename \"{}\"", index(), m_filename);
  82. m_metadata = {
  83. .inode = identifier(),
  84. .size = m_entry.file_size,
  85. .mode = static_cast<mode_t>((has_flag(m_entry.attributes, FATAttributes::Directory) ? S_IFDIR : S_IFREG) | 0777),
  86. .uid = 0,
  87. .gid = 0,
  88. .link_count = 0,
  89. .atime = fat_date_time(m_entry.last_accessed_date, { 0 }),
  90. .ctime = fat_date_time(m_entry.creation_date, m_entry.creation_time),
  91. .mtime = fat_date_time(m_entry.modification_date, m_entry.modification_time),
  92. .dtime = 0,
  93. .block_count = 0,
  94. .block_size = 0,
  95. .major_device = 0,
  96. .minor_device = 0,
  97. };
  98. }
  99. ErrorOr<Vector<BlockBasedFileSystem::BlockIndex>> FATInode::compute_block_list()
  100. {
  101. VERIFY(m_inode_lock.is_locked());
  102. dbgln_if(FAT_DEBUG, "FATFS: computing block list for inode {}", index());
  103. u32 cluster = first_cluster();
  104. Vector<BlockBasedFileSystem::BlockIndex> block_list;
  105. auto fat_sector = TRY(KBuffer::try_create_with_size("FATFS: FAT read buffer"sv, fs().m_logical_block_size));
  106. auto fat_sector_buffer = UserOrKernelBuffer::for_kernel_buffer(fat_sector->data());
  107. while (cluster < no_more_clusters) {
  108. dbgln_if(FAT_DEBUG, "FATFS: Appending cluster {} to inode {}'s cluster chain", cluster, index());
  109. BlockBasedFileSystem::BlockIndex first_block = fs().first_block_of_cluster(cluster);
  110. for (u8 i = 0; i < fs().boot_record()->sectors_per_cluster; i++)
  111. block_list.append(BlockBasedFileSystem::BlockIndex { first_block.value() + i });
  112. u32 fat_offset = cluster * sizeof(u32);
  113. u32 fat_sector_index = fs().boot_record()->reserved_sector_count + (fat_offset / fs().m_logical_block_size);
  114. u32 entry_offset = fat_offset % fs().m_logical_block_size;
  115. TRY(fs().raw_read(fat_sector_index, fat_sector_buffer));
  116. cluster = *reinterpret_cast<u32*>(&fat_sector->data()[entry_offset]);
  117. cluster &= cluster_number_mask;
  118. }
  119. return block_list;
  120. }
  121. ErrorOr<NonnullOwnPtr<KBuffer>> FATInode::read_block_list()
  122. {
  123. VERIFY(m_inode_lock.is_locked());
  124. dbgln_if(FAT_DEBUG, "FATFS: reading block list for inode {} ({} blocks)", index(), m_block_list.size());
  125. if (m_block_list.is_empty())
  126. m_block_list = TRY(compute_block_list());
  127. auto builder = TRY(KBufferBuilder::try_create());
  128. u8 buffer[512];
  129. VERIFY(fs().m_logical_block_size <= sizeof(buffer));
  130. auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
  131. for (BlockBasedFileSystem::BlockIndex block : m_block_list) {
  132. dbgln_if(FAT_DEBUG, "FATFS: reading block: {}", block);
  133. TRY(fs().raw_read(block, buf));
  134. TRY(builder.append((char const*)buffer, fs().m_logical_block_size));
  135. }
  136. auto blocks = builder.build();
  137. if (!blocks)
  138. return ENOMEM;
  139. return blocks.release_nonnull();
  140. }
  141. ErrorOr<LockRefPtr<FATInode>> FATInode::traverse(Function<ErrorOr<bool>(LockRefPtr<FATInode>)> callback)
  142. {
  143. VERIFY(has_flag(m_entry.attributes, FATAttributes::Directory));
  144. Vector<FATLongFileNameEntry> lfn_entries;
  145. auto blocks = TRY(read_block_list());
  146. for (u32 i = 0; i < blocks->size() / sizeof(FATEntry); i++) {
  147. auto* entry = reinterpret_cast<FATEntry*>(blocks->data() + i * sizeof(FATEntry));
  148. if (entry->filename[0] == end_entry_byte) {
  149. dbgln_if(FAT_DEBUG, "FATFS: Found end entry");
  150. return nullptr;
  151. } else if (static_cast<u8>(entry->filename[0]) == unused_entry_byte) {
  152. dbgln_if(FAT_DEBUG, "FATFS: Found unused entry");
  153. lfn_entries.clear();
  154. } else if (entry->attributes == FATAttributes::LongFileName) {
  155. dbgln_if(FAT_DEBUG, "FATFS: Found LFN entry");
  156. TRY(lfn_entries.try_append(*reinterpret_cast<FATLongFileNameEntry*>(entry)));
  157. } else {
  158. dbgln_if(FAT_DEBUG, "FATFS: Found 8.3 entry");
  159. lfn_entries.reverse();
  160. auto inode = TRY(FATInode::create(fs(), *entry, lfn_entries));
  161. if (TRY(callback(inode)))
  162. return inode;
  163. lfn_entries.clear();
  164. }
  165. }
  166. return EINVAL;
  167. }
  168. ErrorOr<NonnullOwnPtr<KString>> FATInode::compute_filename(FATEntry& entry, Vector<FATLongFileNameEntry> const& lfn_entries)
  169. {
  170. if (lfn_entries.is_empty()) {
  171. StringBuilder filename;
  172. filename.append(byte_terminated_string(StringView(entry.filename, normal_filename_length), ' '));
  173. if (entry.extension[0] != ' ') {
  174. filename.append('.');
  175. filename.append(byte_terminated_string(StringView(entry.extension, normal_extension_length), ' '));
  176. }
  177. return TRY(KString::try_create(filename.string_view()));
  178. } else {
  179. StringBuilder filename;
  180. for (auto& lfn_entry : lfn_entries) {
  181. filename.append(lfn_entry.characters1[0]);
  182. filename.append(lfn_entry.characters1[1]);
  183. filename.append(lfn_entry.characters1[2]);
  184. filename.append(lfn_entry.characters1[3]);
  185. filename.append(lfn_entry.characters1[4]);
  186. filename.append(lfn_entry.characters2[0]);
  187. filename.append(lfn_entry.characters2[1]);
  188. filename.append(lfn_entry.characters2[2]);
  189. filename.append(lfn_entry.characters2[3]);
  190. filename.append(lfn_entry.characters2[4]);
  191. filename.append(lfn_entry.characters2[5]);
  192. filename.append(lfn_entry.characters3[0]);
  193. filename.append(lfn_entry.characters3[1]);
  194. }
  195. return TRY(KString::try_create(byte_terminated_string(filename.string_view(), lfn_entry_text_termination)));
  196. }
  197. VERIFY_NOT_REACHED();
  198. }
  199. time_t FATInode::fat_date_time(FATPackedDate date, FATPackedTime time)
  200. {
  201. if (date.value == 0)
  202. return 0;
  203. return Time::from_timestamp(first_fat_year + date.year, date.month, date.day, time.hour, time.minute, time.second * 2, 0).to_seconds();
  204. }
  205. StringView FATInode::byte_terminated_string(StringView string, u8 fill_byte)
  206. {
  207. if (auto index = string.find_last_not(fill_byte); index.has_value())
  208. return string.substring_view(0, index.value());
  209. return string;
  210. }
  211. u32 FATInode::first_cluster() const
  212. {
  213. return (((u32)m_entry.first_cluster_high) << 16) | m_entry.first_cluster_low;
  214. }
  215. ErrorOr<size_t> FATInode::read_bytes_locked(off_t offset, size_t size, UserOrKernelBuffer& buffer, OpenFileDescription*) const
  216. {
  217. dbgln_if(FAT_DEBUG, "FATFS: Reading inode {}: size: {} offset: {}", identifier().index(), size, offset);
  218. // FIXME: Read only the needed blocks instead of the whole file
  219. auto blocks = TRY(const_cast<FATInode&>(*this).read_block_list());
  220. TRY(buffer.write(blocks->data() + offset, min(size, m_block_list.size() * fs().m_logical_block_size - offset)));
  221. return min(size, m_block_list.size() * fs().m_logical_block_size - offset);
  222. }
  223. InodeMetadata FATInode::metadata() const
  224. {
  225. return m_metadata;
  226. }
  227. ErrorOr<void> FATInode::traverse_as_directory(Function<ErrorOr<void>(FileSystem::DirectoryEntryView const&)> callback) const
  228. {
  229. MutexLocker locker(m_inode_lock);
  230. VERIFY(has_flag(m_entry.attributes, FATAttributes::Directory));
  231. [[maybe_unused]] auto inode = TRY(const_cast<FATInode&>(*this).traverse([&callback](auto inode) -> ErrorOr<bool> {
  232. if (inode->m_filename->view() == "" || inode->m_filename->view() == "." || inode->m_filename->view() == "..")
  233. return false;
  234. TRY(callback({ inode->m_filename->view(), inode->identifier(), static_cast<u8>(inode->m_entry.attributes) }));
  235. return false;
  236. }));
  237. return {};
  238. }
  239. ErrorOr<NonnullLockRefPtr<Inode>> FATInode::lookup(StringView name)
  240. {
  241. MutexLocker locker(m_inode_lock);
  242. VERIFY(has_flag(m_entry.attributes, FATAttributes::Directory));
  243. auto inode = TRY(traverse([name](auto child) -> ErrorOr<bool> {
  244. return child->m_filename->view() == name;
  245. }));
  246. if (inode.is_null())
  247. return ENOENT;
  248. else
  249. return inode.release_nonnull();
  250. }
  251. ErrorOr<size_t> FATInode::write_bytes_locked(off_t, size_t, UserOrKernelBuffer const&, OpenFileDescription*)
  252. {
  253. return EROFS;
  254. }
  255. ErrorOr<NonnullLockRefPtr<Inode>> FATInode::create_child(StringView, mode_t, dev_t, UserID, GroupID)
  256. {
  257. return EROFS;
  258. }
  259. ErrorOr<void> FATInode::add_child(Inode&, StringView, mode_t)
  260. {
  261. return EROFS;
  262. }
  263. ErrorOr<void> FATInode::remove_child(StringView)
  264. {
  265. return EROFS;
  266. }
  267. ErrorOr<void> FATInode::chmod(mode_t)
  268. {
  269. return EROFS;
  270. }
  271. ErrorOr<void> FATInode::chown(UserID, GroupID)
  272. {
  273. return EROFS;
  274. }
  275. ErrorOr<void> FATInode::flush_metadata()
  276. {
  277. return EROFS;
  278. }
  279. }