BlockBasedFileSystem.cpp 10 KB

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