BlockBasedFileSystem.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/IntrusiveList.h>
  7. #include <Kernel/Debug.h>
  8. #include <Kernel/FileSystem/BlockBasedFileSystem.h>
  9. #include <Kernel/Process.h>
  10. namespace Kernel {
  11. struct CacheEntry {
  12. IntrusiveListNode<CacheEntry> list_node;
  13. BlockBasedFileSystem::BlockIndex block_index { 0 };
  14. u8* data { nullptr };
  15. bool has_data { false };
  16. };
  17. class DiskCache {
  18. public:
  19. static constexpr size_t EntryCount = 10000;
  20. explicit DiskCache(BlockBasedFileSystem& fs, NonnullOwnPtr<KBuffer> cached_block_data, NonnullOwnPtr<KBuffer> entries_buffer)
  21. : m_fs(fs)
  22. , m_cached_block_data(move(cached_block_data))
  23. , m_entries(move(entries_buffer))
  24. {
  25. for (size_t i = 0; i < EntryCount; ++i) {
  26. entries()[i].data = m_cached_block_data->data() + i * m_fs->block_size();
  27. m_clean_list.append(entries()[i]);
  28. }
  29. }
  30. ~DiskCache() = default;
  31. bool is_dirty() const { return !m_dirty_list.is_empty(); }
  32. bool entry_is_dirty(CacheEntry const& entry) const { return m_dirty_list.contains(entry); }
  33. void mark_all_clean()
  34. {
  35. while (auto* entry = m_dirty_list.first())
  36. m_clean_list.prepend(*entry);
  37. }
  38. void mark_dirty(CacheEntry& entry)
  39. {
  40. m_dirty_list.prepend(entry);
  41. }
  42. void mark_clean(CacheEntry& entry)
  43. {
  44. m_clean_list.prepend(entry);
  45. }
  46. CacheEntry* get(BlockBasedFileSystem::BlockIndex block_index) const
  47. {
  48. auto it = m_hash.find(block_index);
  49. if (it == m_hash.end())
  50. return nullptr;
  51. auto& entry = const_cast<CacheEntry&>(*it->value);
  52. VERIFY(entry.block_index == block_index);
  53. return &entry;
  54. }
  55. ErrorOr<CacheEntry*> ensure(BlockBasedFileSystem::BlockIndex block_index) const
  56. {
  57. if (auto* entry = get(block_index))
  58. return entry;
  59. if (m_clean_list.is_empty()) {
  60. // Not a single clean entry! Flush writes and try again.
  61. // NOTE: We want to make sure we only call FileBackedFileSystem flush here,
  62. // not some FileBackedFileSystem subclass flush!
  63. m_fs->flush_writes_impl();
  64. return ensure(block_index);
  65. }
  66. VERIFY(m_clean_list.last());
  67. auto& new_entry = *m_clean_list.last();
  68. m_clean_list.prepend(new_entry);
  69. m_hash.remove(new_entry.block_index);
  70. TRY(m_hash.try_set(block_index, &new_entry));
  71. new_entry.block_index = block_index;
  72. new_entry.has_data = false;
  73. return &new_entry;
  74. }
  75. CacheEntry const* entries() const { return (CacheEntry const*)m_entries->data(); }
  76. CacheEntry* entries() { return (CacheEntry*)m_entries->data(); }
  77. template<typename Callback>
  78. void for_each_dirty_entry(Callback callback)
  79. {
  80. for (auto& entry : m_dirty_list)
  81. callback(entry);
  82. }
  83. private:
  84. mutable NonnullRefPtr<BlockBasedFileSystem> m_fs;
  85. mutable IntrusiveList<&CacheEntry::list_node> m_dirty_list;
  86. mutable IntrusiveList<&CacheEntry::list_node> m_clean_list;
  87. mutable HashMap<BlockBasedFileSystem::BlockIndex, CacheEntry*> m_hash;
  88. NonnullOwnPtr<KBuffer> m_cached_block_data;
  89. NonnullOwnPtr<KBuffer> m_entries;
  90. };
  91. BlockBasedFileSystem::BlockBasedFileSystem(OpenFileDescription& file_description)
  92. : FileBackedFileSystem(file_description)
  93. {
  94. VERIFY(file_description.file().is_seekable());
  95. }
  96. BlockBasedFileSystem::~BlockBasedFileSystem() = default;
  97. void BlockBasedFileSystem::remove_disk_cache_before_last_unmount()
  98. {
  99. VERIFY(m_lock.is_locked());
  100. m_cache.with_exclusive([&](auto& cache) {
  101. cache.clear();
  102. });
  103. }
  104. ErrorOr<void> BlockBasedFileSystem::initialize_while_locked()
  105. {
  106. VERIFY(m_lock.is_locked());
  107. VERIFY(!is_initialized_while_locked());
  108. VERIFY(block_size() != 0);
  109. auto cached_block_data = TRY(KBuffer::try_create_with_size("BlockBasedFS: Cache blocks"sv, DiskCache::EntryCount * block_size()));
  110. auto entries_data = TRY(KBuffer::try_create_with_size("BlockBasedFS: Cache entries"sv, DiskCache::EntryCount * sizeof(CacheEntry)));
  111. auto disk_cache = TRY(adopt_nonnull_own_or_enomem(new (nothrow) DiskCache(*this, move(cached_block_data), move(entries_data))));
  112. m_cache.with_exclusive([&](auto& cache) {
  113. cache = move(disk_cache);
  114. });
  115. return {};
  116. }
  117. ErrorOr<void> BlockBasedFileSystem::write_block(BlockIndex index, UserOrKernelBuffer const& data, size_t count, u64 offset, bool allow_cache)
  118. {
  119. VERIFY(m_logical_block_size);
  120. VERIFY(offset + count <= block_size());
  121. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_block {}, size={}", index, count);
  122. // NOTE: We copy the `data` to write into a local buffer before taking the cache lock.
  123. // This makes sure any page faults caused by accessing the data will occur before
  124. // we tie down the cache.
  125. auto buffered_data = TRY(ByteBuffer::create_uninitialized(count));
  126. TRY(data.read(buffered_data.bytes()));
  127. return m_cache.with_exclusive([&](auto& cache) -> ErrorOr<void> {
  128. if (!allow_cache) {
  129. flush_specific_block_if_needed(index);
  130. u64 base_offset = index.value() * block_size() + offset;
  131. auto nwritten = TRY(file_description().write(base_offset, data, count));
  132. VERIFY(nwritten == count);
  133. return {};
  134. }
  135. auto entry = TRY(cache->ensure(index));
  136. if (count < block_size()) {
  137. // Fill the cache first.
  138. TRY(read_block(index, nullptr, block_size()));
  139. }
  140. memcpy(entry->data + offset, buffered_data.data(), count);
  141. cache->mark_dirty(*entry);
  142. entry->has_data = true;
  143. return {};
  144. });
  145. }
  146. ErrorOr<void> BlockBasedFileSystem::raw_read(BlockIndex index, UserOrKernelBuffer& buffer)
  147. {
  148. auto base_offset = index.value() * m_logical_block_size;
  149. auto nread = TRY(file_description().read(buffer, base_offset, m_logical_block_size));
  150. VERIFY(nread == m_logical_block_size);
  151. return {};
  152. }
  153. ErrorOr<void> BlockBasedFileSystem::raw_write(BlockIndex index, UserOrKernelBuffer const& buffer)
  154. {
  155. auto base_offset = index.value() * m_logical_block_size;
  156. auto nwritten = TRY(file_description().write(base_offset, buffer, m_logical_block_size));
  157. VERIFY(nwritten == m_logical_block_size);
  158. return {};
  159. }
  160. ErrorOr<void> BlockBasedFileSystem::raw_read_blocks(BlockIndex index, size_t count, UserOrKernelBuffer& buffer)
  161. {
  162. auto current = buffer;
  163. for (auto block = index.value(); block < (index.value() + count); block++) {
  164. TRY(raw_read(BlockIndex { block }, current));
  165. current = current.offset(logical_block_size());
  166. }
  167. return {};
  168. }
  169. ErrorOr<void> BlockBasedFileSystem::raw_write_blocks(BlockIndex index, size_t count, UserOrKernelBuffer const& buffer)
  170. {
  171. auto current = buffer;
  172. for (auto block = index.value(); block < (index.value() + count); block++) {
  173. TRY(raw_write(block, current));
  174. current = current.offset(logical_block_size());
  175. }
  176. return {};
  177. }
  178. ErrorOr<void> BlockBasedFileSystem::write_blocks(BlockIndex index, unsigned count, UserOrKernelBuffer const& data, bool allow_cache)
  179. {
  180. VERIFY(m_logical_block_size);
  181. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_blocks {}, count={}", index, count);
  182. for (unsigned i = 0; i < count; ++i) {
  183. TRY(write_block(BlockIndex { index.value() + i }, data.offset(i * block_size()), block_size(), 0, allow_cache));
  184. }
  185. return {};
  186. }
  187. ErrorOr<void> BlockBasedFileSystem::read_block(BlockIndex index, UserOrKernelBuffer* buffer, size_t count, u64 offset, bool allow_cache) const
  188. {
  189. VERIFY(m_logical_block_size);
  190. VERIFY(offset + count <= block_size());
  191. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::read_block {}", index);
  192. return m_cache.with_exclusive([&](auto& cache) -> ErrorOr<void> {
  193. if (!allow_cache) {
  194. const_cast<BlockBasedFileSystem*>(this)->flush_specific_block_if_needed(index);
  195. u64 base_offset = index.value() * block_size() + offset;
  196. auto nread = TRY(file_description().read(*buffer, base_offset, count));
  197. VERIFY(nread == count);
  198. return {};
  199. }
  200. auto* entry = TRY(cache->ensure(index));
  201. if (!entry->has_data) {
  202. auto base_offset = index.value() * block_size();
  203. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry->data);
  204. auto nread = TRY(file_description().read(entry_data_buffer, base_offset, block_size()));
  205. VERIFY(nread == block_size());
  206. entry->has_data = true;
  207. }
  208. if (buffer)
  209. TRY(buffer->write(entry->data + offset, count));
  210. return {};
  211. });
  212. }
  213. ErrorOr<void> BlockBasedFileSystem::read_blocks(BlockIndex index, unsigned count, UserOrKernelBuffer& buffer, bool allow_cache) const
  214. {
  215. VERIFY(m_logical_block_size);
  216. if (!count)
  217. return EINVAL;
  218. if (count == 1)
  219. return read_block(index, &buffer, block_size(), 0, allow_cache);
  220. auto out = buffer;
  221. for (unsigned i = 0; i < count; ++i) {
  222. TRY(read_block(BlockIndex { index.value() + i }, &out, block_size(), 0, allow_cache));
  223. out = out.offset(block_size());
  224. }
  225. return {};
  226. }
  227. void BlockBasedFileSystem::flush_specific_block_if_needed(BlockIndex index)
  228. {
  229. m_cache.with_exclusive([&](auto& cache) {
  230. if (!cache->is_dirty())
  231. return;
  232. auto* entry = cache->get(index);
  233. if (!entry)
  234. return;
  235. if (!cache->entry_is_dirty(*entry))
  236. return;
  237. size_t base_offset = entry->block_index.value() * block_size();
  238. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry->data);
  239. (void)file_description().write(base_offset, entry_data_buffer, block_size());
  240. });
  241. }
  242. void BlockBasedFileSystem::flush_writes_impl()
  243. {
  244. size_t count = 0;
  245. m_cache.with_exclusive([&](auto& cache) {
  246. if (!cache->is_dirty())
  247. return;
  248. cache->for_each_dirty_entry([&](CacheEntry& entry) {
  249. auto base_offset = entry.block_index.value() * block_size();
  250. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry.data);
  251. [[maybe_unused]] auto rc = file_description().write(base_offset, entry_data_buffer, block_size());
  252. ++count;
  253. });
  254. cache->mark_all_clean();
  255. dbgln("{}: Flushed {} blocks to disk", class_name(), count);
  256. });
  257. }
  258. void BlockBasedFileSystem::flush_writes()
  259. {
  260. flush_writes_impl();
  261. }
  262. }