BlockBasedFileSystem.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/IntrusiveList.h>
  27. #include <Kernel/Debug.h>
  28. #include <Kernel/FileSystem/BlockBasedFileSystem.h>
  29. #include <Kernel/Process.h>
  30. namespace Kernel {
  31. struct CacheEntry {
  32. IntrusiveListNode list_node;
  33. BlockBasedFS::BlockIndex block_index { 0 };
  34. u8* data { nullptr };
  35. bool has_data { false };
  36. };
  37. class DiskCache {
  38. public:
  39. explicit DiskCache(BlockBasedFS& fs)
  40. : m_fs(fs)
  41. , m_cached_block_data(KBuffer::create_with_size(m_entry_count * m_fs.block_size()))
  42. , m_entries(KBuffer::create_with_size(m_entry_count * sizeof(CacheEntry)))
  43. {
  44. for (size_t i = 0; i < m_entry_count; ++i) {
  45. entries()[i].data = m_cached_block_data.data() + i * m_fs.block_size();
  46. m_clean_list.append(entries()[i]);
  47. }
  48. }
  49. ~DiskCache() = default;
  50. bool is_dirty() const { return m_dirty; }
  51. void set_dirty(bool b) { m_dirty = b; }
  52. void mark_all_clean()
  53. {
  54. while (auto* entry = m_dirty_list.first())
  55. m_clean_list.prepend(*entry);
  56. m_dirty = false;
  57. }
  58. void mark_dirty(CacheEntry& entry)
  59. {
  60. m_dirty_list.prepend(entry);
  61. m_dirty = true;
  62. }
  63. void mark_clean(CacheEntry& entry)
  64. {
  65. m_clean_list.prepend(entry);
  66. }
  67. CacheEntry& get(BlockBasedFS::BlockIndex block_index) const
  68. {
  69. if (auto it = m_hash.find(block_index); it != m_hash.end()) {
  70. auto& entry = const_cast<CacheEntry&>(*it->value);
  71. VERIFY(entry.block_index == block_index);
  72. return entry;
  73. }
  74. if (m_clean_list.is_empty()) {
  75. // Not a single clean entry! Flush writes and try again.
  76. // NOTE: We want to make sure we only call FileBackedFS flush here,
  77. // not some FileBackedFS subclass flush!
  78. m_fs.flush_writes_impl();
  79. return get(block_index);
  80. }
  81. VERIFY(m_clean_list.last());
  82. auto& new_entry = *m_clean_list.last();
  83. m_clean_list.prepend(new_entry);
  84. m_hash.remove(new_entry.block_index);
  85. m_hash.set(block_index, &new_entry);
  86. new_entry.block_index = block_index;
  87. new_entry.has_data = false;
  88. return new_entry;
  89. }
  90. const CacheEntry* entries() const { return (const CacheEntry*)m_entries.data(); }
  91. CacheEntry* entries() { return (CacheEntry*)m_entries.data(); }
  92. template<typename Callback>
  93. void for_each_dirty_entry(Callback callback)
  94. {
  95. for (auto& entry : m_dirty_list)
  96. callback(entry);
  97. }
  98. private:
  99. BlockBasedFS& m_fs;
  100. size_t m_entry_count { 10000 };
  101. mutable HashMap<BlockBasedFS::BlockIndex, CacheEntry*> m_hash;
  102. mutable IntrusiveList<CacheEntry, &CacheEntry::list_node> m_clean_list;
  103. mutable IntrusiveList<CacheEntry, &CacheEntry::list_node> m_dirty_list;
  104. KBuffer m_cached_block_data;
  105. KBuffer m_entries;
  106. bool m_dirty { false };
  107. };
  108. BlockBasedFS::BlockBasedFS(FileDescription& file_description)
  109. : FileBackedFS(file_description)
  110. {
  111. VERIFY(file_description.file().is_seekable());
  112. }
  113. BlockBasedFS::~BlockBasedFS()
  114. {
  115. }
  116. KResult BlockBasedFS::write_block(BlockIndex index, const UserOrKernelBuffer& data, size_t count, size_t offset, bool allow_cache)
  117. {
  118. LOCKER(m_lock);
  119. VERIFY(m_logical_block_size);
  120. VERIFY(offset + count <= block_size());
  121. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_block {}, size={}", index, count);
  122. if (!allow_cache) {
  123. flush_specific_block_if_needed(index);
  124. u32 base_offset = index.value() * block_size() + offset;
  125. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  126. if (seek_result.is_error())
  127. return seek_result.error();
  128. auto nwritten = file_description().write(data, count);
  129. if (nwritten.is_error())
  130. return nwritten.error();
  131. VERIFY(nwritten.value() == count);
  132. return KSuccess;
  133. }
  134. auto& entry = cache().get(index);
  135. if (count < block_size()) {
  136. // Fill the cache first.
  137. auto result = read_block(index, nullptr, block_size());
  138. if (result.is_error())
  139. return result;
  140. }
  141. if (!data.read(entry.data + offset, count))
  142. return EFAULT;
  143. cache().mark_dirty(entry);
  144. entry.has_data = true;
  145. return KSuccess;
  146. }
  147. bool BlockBasedFS::raw_read(BlockIndex index, UserOrKernelBuffer& buffer)
  148. {
  149. LOCKER(m_lock);
  150. u32 base_offset = index.value() * m_logical_block_size;
  151. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  152. VERIFY(!seek_result.is_error());
  153. auto nread = file_description().read(buffer, m_logical_block_size);
  154. VERIFY(!nread.is_error());
  155. VERIFY(nread.value() == m_logical_block_size);
  156. return true;
  157. }
  158. bool BlockBasedFS::raw_write(BlockIndex index, const UserOrKernelBuffer& buffer)
  159. {
  160. LOCKER(m_lock);
  161. size_t base_offset = index.value() * m_logical_block_size;
  162. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  163. VERIFY(!seek_result.is_error());
  164. auto nwritten = file_description().write(buffer, m_logical_block_size);
  165. VERIFY(!nwritten.is_error());
  166. VERIFY(nwritten.value() == m_logical_block_size);
  167. return true;
  168. }
  169. bool BlockBasedFS::raw_read_blocks(BlockIndex index, size_t count, UserOrKernelBuffer& buffer)
  170. {
  171. LOCKER(m_lock);
  172. auto current = buffer;
  173. for (unsigned block = index.value(); block < (index.value() + count); block++) {
  174. if (!raw_read(BlockIndex { block }, current))
  175. return false;
  176. current = current.offset(logical_block_size());
  177. }
  178. return true;
  179. }
  180. bool BlockBasedFS::raw_write_blocks(BlockIndex index, size_t count, const UserOrKernelBuffer& buffer)
  181. {
  182. LOCKER(m_lock);
  183. auto current = buffer;
  184. for (unsigned block = index.value(); block < (index.value() + count); block++) {
  185. if (!raw_write(block, current))
  186. return false;
  187. current = current.offset(logical_block_size());
  188. }
  189. return true;
  190. }
  191. KResult BlockBasedFS::write_blocks(BlockIndex index, unsigned count, const UserOrKernelBuffer& data, bool allow_cache)
  192. {
  193. LOCKER(m_lock);
  194. VERIFY(m_logical_block_size);
  195. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::write_blocks {}, count={}", index, count);
  196. for (unsigned i = 0; i < count; ++i) {
  197. auto result = write_block(BlockIndex { index.value() + i }, data.offset(i * block_size()), block_size(), 0, allow_cache);
  198. if (result.is_error())
  199. return result;
  200. }
  201. return KSuccess;
  202. }
  203. KResult BlockBasedFS::read_block(BlockIndex index, UserOrKernelBuffer* buffer, size_t count, size_t offset, bool allow_cache) const
  204. {
  205. LOCKER(m_lock);
  206. VERIFY(m_logical_block_size);
  207. VERIFY(offset + count <= block_size());
  208. dbgln_if(BBFS_DEBUG, "BlockBasedFileSystem::read_block {}", index);
  209. if (!allow_cache) {
  210. const_cast<BlockBasedFS*>(this)->flush_specific_block_if_needed(index);
  211. auto base_offset = index.value() * block_size() + offset;
  212. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  213. if (seek_result.is_error())
  214. return seek_result.error();
  215. auto nread = file_description().read(*buffer, count);
  216. if (nread.is_error())
  217. return nread.error();
  218. VERIFY(nread.value() == count);
  219. return KSuccess;
  220. }
  221. auto& entry = cache().get(index);
  222. if (!entry.has_data) {
  223. auto base_offset = index.value() * block_size();
  224. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  225. if (seek_result.is_error())
  226. return seek_result.error();
  227. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry.data);
  228. auto nread = file_description().read(entry_data_buffer, block_size());
  229. if (nread.is_error())
  230. return nread.error();
  231. VERIFY(nread.value() == block_size());
  232. entry.has_data = true;
  233. }
  234. if (buffer && !buffer->write(entry.data + offset, count))
  235. return EFAULT;
  236. return KSuccess;
  237. }
  238. KResult BlockBasedFS::read_blocks(BlockIndex index, unsigned count, UserOrKernelBuffer& buffer, bool allow_cache) const
  239. {
  240. LOCKER(m_lock);
  241. VERIFY(m_logical_block_size);
  242. if (!count)
  243. return EINVAL;
  244. if (count == 1)
  245. return read_block(index, &buffer, block_size(), 0, allow_cache);
  246. auto out = buffer;
  247. for (unsigned i = 0; i < count; ++i) {
  248. auto result = read_block(BlockIndex { index.value() + i }, &out, block_size(), 0, allow_cache);
  249. if (result.is_error())
  250. return result;
  251. out = out.offset(block_size());
  252. }
  253. return KSuccess;
  254. }
  255. void BlockBasedFS::flush_specific_block_if_needed(BlockIndex index)
  256. {
  257. LOCKER(m_lock);
  258. if (!cache().is_dirty())
  259. return;
  260. Vector<CacheEntry*, 32> cleaned_entries;
  261. cache().for_each_dirty_entry([&](CacheEntry& entry) {
  262. if (entry.block_index != index) {
  263. size_t base_offset = entry.block_index.value() * block_size();
  264. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  265. VERIFY(!seek_result.is_error());
  266. // FIXME: Should this error path be surfaced somehow?
  267. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry.data);
  268. [[maybe_unused]] auto rc = file_description().write(entry_data_buffer, block_size());
  269. cleaned_entries.append(&entry);
  270. }
  271. });
  272. // NOTE: We make a separate pass to mark entries clean since marking them clean
  273. // moves them out of the dirty list which would disturb the iteration above.
  274. for (auto* entry : cleaned_entries)
  275. cache().mark_clean(*entry);
  276. }
  277. void BlockBasedFS::flush_writes_impl()
  278. {
  279. LOCKER(m_lock);
  280. if (!cache().is_dirty())
  281. return;
  282. u32 count = 0;
  283. cache().for_each_dirty_entry([&](CacheEntry& entry) {
  284. u32 base_offset = entry.block_index.value() * block_size();
  285. auto seek_result = file_description().seek(base_offset, SEEK_SET);
  286. VERIFY(!seek_result.is_error());
  287. // FIXME: Should this error path be surfaced somehow?
  288. auto entry_data_buffer = UserOrKernelBuffer::for_kernel_buffer(entry.data);
  289. [[maybe_unused]] auto rc = file_description().write(entry_data_buffer, block_size());
  290. ++count;
  291. });
  292. cache().mark_all_clean();
  293. dbgln("{}: Flushed {} blocks to disk", class_name(), count);
  294. }
  295. void BlockBasedFS::flush_writes()
  296. {
  297. flush_writes_impl();
  298. }
  299. DiskCache& BlockBasedFS::cache() const
  300. {
  301. if (!m_cache)
  302. m_cache = make<DiskCache>(const_cast<BlockBasedFS&>(*this));
  303. return *m_cache;
  304. }
  305. }