BlockBasedFileSystem.cpp 11 KB

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