BlockBasedFileSystem.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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/Tasks/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. if (!entry_is_dirty(entry) && (m_clean_list.first() != &entry)) {
  54. // Cache hit! Promote the entry to the front of the list.
  55. m_clean_list.prepend(entry);
  56. }
  57. return &entry;
  58. }
  59. ErrorOr<CacheEntry*> ensure(BlockBasedFileSystem::BlockIndex block_index) const
  60. {
  61. if (auto* entry = get(block_index))
  62. return entry;
  63. if (m_clean_list.is_empty()) {
  64. // Not a single clean entry! Flush writes and try again.
  65. // NOTE: We want to make sure we only call FileBackedFileSystem flush here,
  66. // not some FileBackedFileSystem subclass flush!
  67. m_fs->flush_writes_impl();
  68. return ensure(block_index);
  69. }
  70. VERIFY(m_clean_list.last());
  71. auto& new_entry = *m_clean_list.last();
  72. m_clean_list.prepend(new_entry);
  73. m_hash.remove(new_entry.block_index);
  74. TRY(m_hash.try_set(block_index, &new_entry));
  75. new_entry.block_index = block_index;
  76. new_entry.has_data = false;
  77. return &new_entry;
  78. }
  79. CacheEntry const* entries() const { return (CacheEntry const*)m_entries->data(); }
  80. CacheEntry* entries() { return (CacheEntry*)m_entries->data(); }
  81. template<typename Callback>
  82. void for_each_dirty_entry(Callback callback)
  83. {
  84. for (auto& entry : m_dirty_list)
  85. callback(entry);
  86. }
  87. private:
  88. mutable NonnullRefPtr<BlockBasedFileSystem> m_fs;
  89. NonnullOwnPtr<KBuffer> m_cached_block_data;
  90. // NOTE: m_entries must be declared before m_dirty_list and m_clean_list because their entries are allocated from it.
  91. // We need to ensure that the destructors of m_dirty_list and m_clean_list are called before m_entries is destroyed.
  92. NonnullOwnPtr<KBuffer> m_entries;
  93. mutable IntrusiveList<&CacheEntry::list_node> m_dirty_list;
  94. mutable IntrusiveList<&CacheEntry::list_node> m_clean_list;
  95. mutable HashMap<BlockBasedFileSystem::BlockIndex, CacheEntry*> m_hash;
  96. };
  97. BlockBasedFileSystem::BlockBasedFileSystem(OpenFileDescription& file_description)
  98. : FileBackedFileSystem(file_description)
  99. {
  100. VERIFY(file_description.file().is_seekable());
  101. }
  102. BlockBasedFileSystem::~BlockBasedFileSystem() = default;
  103. void BlockBasedFileSystem::remove_disk_cache_before_last_unmount()
  104. {
  105. VERIFY(m_lock.is_locked());
  106. m_cache.with_exclusive([&](auto& cache) {
  107. cache.clear();
  108. });
  109. }
  110. ErrorOr<void> BlockBasedFileSystem::initialize_while_locked()
  111. {
  112. VERIFY(m_lock.is_locked());
  113. VERIFY(!is_initialized_while_locked());
  114. VERIFY(block_size() != 0);
  115. auto cached_block_data = TRY(KBuffer::try_create_with_size("BlockBasedFS: Cache blocks"sv, DiskCache::EntryCount * block_size()));
  116. auto entries_data = TRY(KBuffer::try_create_with_size("BlockBasedFS: Cache entries"sv, DiskCache::EntryCount * sizeof(CacheEntry)));
  117. auto disk_cache = TRY(adopt_nonnull_own_or_enomem(new (nothrow) DiskCache(*this, move(cached_block_data), move(entries_data))));
  118. m_cache.with_exclusive([&](auto& cache) {
  119. cache = move(disk_cache);
  120. });
  121. return {};
  122. }
  123. ErrorOr<void> BlockBasedFileSystem::write_block(BlockIndex index, UserOrKernelBuffer const& data, size_t count, u64 offset, bool allow_cache)
  124. {
  125. VERIFY(m_logical_block_size);
  126. VERIFY(offset + count <= block_size());
  127. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_block {}, size={}", index, count);
  128. // NOTE: We copy the `data` to write into a local buffer before taking the cache lock.
  129. // This makes sure any page faults caused by accessing the data will occur before
  130. // we tie down the cache.
  131. auto buffered_data = TRY(ByteBuffer::create_uninitialized(count));
  132. TRY(data.read(buffered_data.bytes()));
  133. return m_cache.with_exclusive([&](auto& cache) -> ErrorOr<void> {
  134. if (!allow_cache) {
  135. flush_specific_block_if_needed(index);
  136. u64 base_offset = index.value() * block_size() + offset;
  137. auto nwritten = TRY(file_description().write(base_offset, data, count));
  138. VERIFY(nwritten == count);
  139. return {};
  140. }
  141. auto entry = TRY(cache->ensure(index));
  142. if (count < block_size()) {
  143. // Fill the cache first.
  144. TRY(read_block(index, nullptr, block_size()));
  145. }
  146. memcpy(entry->data + offset, buffered_data.data(), count);
  147. cache->mark_dirty(*entry);
  148. entry->has_data = true;
  149. return {};
  150. });
  151. }
  152. ErrorOr<void> BlockBasedFileSystem::raw_read(BlockIndex index, UserOrKernelBuffer& buffer)
  153. {
  154. auto base_offset = index.value() * m_logical_block_size;
  155. auto nread = TRY(file_description().read(buffer, base_offset, m_logical_block_size));
  156. VERIFY(nread == m_logical_block_size);
  157. return {};
  158. }
  159. ErrorOr<void> BlockBasedFileSystem::raw_write(BlockIndex index, UserOrKernelBuffer const& buffer)
  160. {
  161. auto base_offset = index.value() * m_logical_block_size;
  162. auto nwritten = TRY(file_description().write(base_offset, buffer, m_logical_block_size));
  163. VERIFY(nwritten == m_logical_block_size);
  164. return {};
  165. }
  166. ErrorOr<void> BlockBasedFileSystem::raw_read_blocks(BlockIndex index, size_t count, UserOrKernelBuffer& buffer)
  167. {
  168. auto current = buffer;
  169. for (auto block = index.value(); block < (index.value() + count); block++) {
  170. TRY(raw_read(BlockIndex { block }, current));
  171. current = current.offset(logical_block_size());
  172. }
  173. return {};
  174. }
  175. ErrorOr<void> BlockBasedFileSystem::raw_write_blocks(BlockIndex index, size_t count, UserOrKernelBuffer const& buffer)
  176. {
  177. auto current = buffer;
  178. for (auto block = index.value(); block < (index.value() + count); block++) {
  179. TRY(raw_write(block, current));
  180. current = current.offset(logical_block_size());
  181. }
  182. return {};
  183. }
  184. ErrorOr<void> BlockBasedFileSystem::write_blocks(BlockIndex index, unsigned count, UserOrKernelBuffer const& data, bool allow_cache)
  185. {
  186. VERIFY(m_logical_block_size);
  187. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_blocks {}, count={}", index, count);
  188. for (unsigned i = 0; i < count; ++i) {
  189. TRY(write_block(BlockIndex { index.value() + i }, data.offset(i * block_size()), block_size(), 0, allow_cache));
  190. }
  191. return {};
  192. }
  193. ErrorOr<void> BlockBasedFileSystem::read_block(BlockIndex index, UserOrKernelBuffer* buffer, size_t count, u64 offset, bool allow_cache) const
  194. {
  195. VERIFY(m_logical_block_size);
  196. VERIFY(offset + count <= block_size());
  197. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::read_block {}", index);
  198. return m_cache.with_exclusive([&](auto& cache) -> ErrorOr<void> {
  199. if (!allow_cache) {
  200. const_cast<BlockBasedFileSystem*>(this)->flush_specific_block_if_needed(index);
  201. u64 base_offset = index.value() * block_size() + offset;
  202. auto nread = TRY(file_description().read(*buffer, base_offset, count));
  203. VERIFY(nread == count);
  204. return {};
  205. }
  206. auto* entry = TRY(cache->ensure(index));
  207. if (!entry->has_data) {
  208. auto base_offset = index.value() * block_size();
  209. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry->data);
  210. auto nread = TRY(file_description().read(entry_data_buffer, base_offset, block_size()));
  211. VERIFY(nread == block_size());
  212. entry->has_data = true;
  213. }
  214. if (buffer)
  215. TRY(buffer->write(entry->data + offset, count));
  216. return {};
  217. });
  218. }
  219. ErrorOr<void> BlockBasedFileSystem::read_blocks(BlockIndex index, unsigned count, UserOrKernelBuffer& buffer, bool allow_cache) const
  220. {
  221. VERIFY(m_logical_block_size);
  222. if (!count)
  223. return EINVAL;
  224. if (count == 1)
  225. return read_block(index, &buffer, block_size(), 0, allow_cache);
  226. auto out = buffer;
  227. for (unsigned i = 0; i < count; ++i) {
  228. TRY(read_block(BlockIndex { index.value() + i }, &out, block_size(), 0, allow_cache));
  229. out = out.offset(block_size());
  230. }
  231. return {};
  232. }
  233. void BlockBasedFileSystem::flush_specific_block_if_needed(BlockIndex index)
  234. {
  235. m_cache.with_exclusive([&](auto& cache) {
  236. if (!cache->is_dirty())
  237. return;
  238. auto* entry = cache->get(index);
  239. if (!entry)
  240. return;
  241. if (!cache->entry_is_dirty(*entry))
  242. return;
  243. size_t base_offset = entry->block_index.value() * block_size();
  244. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry->data);
  245. (void)file_description().write(base_offset, entry_data_buffer, block_size());
  246. });
  247. }
  248. void BlockBasedFileSystem::flush_writes_impl()
  249. {
  250. size_t count = 0;
  251. m_cache.with_exclusive([&](auto& cache) {
  252. if (!cache->is_dirty())
  253. return;
  254. cache->for_each_dirty_entry([&](CacheEntry& entry) {
  255. auto base_offset = entry.block_index.value() * block_size();
  256. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry.data);
  257. [[maybe_unused]] auto rc = file_description().write(base_offset, entry_data_buffer, block_size());
  258. ++count;
  259. });
  260. cache->mark_all_clean();
  261. dbgln("{}: Flushed {} blocks to disk", class_name(), count);
  262. });
  263. }
  264. void BlockBasedFileSystem::flush_writes()
  265. {
  266. flush_writes_impl();
  267. }
  268. }