Inode.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, sin-ack <sin-ack@protonmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/MemoryStream.h>
  8. #include <Kernel/API/POSIX/errno.h>
  9. #include <Kernel/Debug.h>
  10. #include <Kernel/FileSystem/Ext2FS/Inode.h>
  11. #include <Kernel/FileSystem/InodeMetadata.h>
  12. #include <Kernel/UnixTypes.h>
  13. namespace Kernel {
  14. static constexpr size_t max_inline_symlink_length = 60;
  15. static u8 to_ext2_file_type(mode_t mode)
  16. {
  17. if (is_regular_file(mode))
  18. return EXT2_FT_REG_FILE;
  19. if (is_directory(mode))
  20. return EXT2_FT_DIR;
  21. if (is_character_device(mode))
  22. return EXT2_FT_CHRDEV;
  23. if (is_block_device(mode))
  24. return EXT2_FT_BLKDEV;
  25. if (is_fifo(mode))
  26. return EXT2_FT_FIFO;
  27. if (is_socket(mode))
  28. return EXT2_FT_SOCK;
  29. if (is_symlink(mode))
  30. return EXT2_FT_SYMLINK;
  31. return EXT2_FT_UNKNOWN;
  32. }
  33. ErrorOr<void> Ext2FSInode::write_indirect_block(BlockBasedFileSystem::BlockIndex block, Span<BlockBasedFileSystem::BlockIndex> blocks_indices)
  34. {
  35. auto const entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  36. VERIFY(blocks_indices.size() <= entries_per_block);
  37. auto block_contents = TRY(ByteBuffer::create_uninitialized(fs().block_size()));
  38. OutputMemoryStream stream { block_contents };
  39. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  40. VERIFY(blocks_indices.size() <= EXT2_ADDR_PER_BLOCK(&fs().super_block()));
  41. for (unsigned i = 0; i < blocks_indices.size(); ++i)
  42. stream << static_cast<u32>(blocks_indices[i].value());
  43. stream.fill_to_end(0);
  44. return fs().write_block(block, buffer, stream.size());
  45. }
  46. ErrorOr<void> Ext2FSInode::grow_doubly_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, Span<BlockBasedFileSystem::BlockIndex> blocks_indices, Vector<Ext2FS::BlockIndex>& new_meta_blocks, unsigned& meta_blocks)
  47. {
  48. auto const entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  49. auto const entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  50. auto const old_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_block);
  51. auto const new_indirect_blocks_length = ceil_div(blocks_indices.size(), entries_per_block);
  52. VERIFY(blocks_indices.size() > 0);
  53. VERIFY(blocks_indices.size() > old_blocks_length);
  54. VERIFY(blocks_indices.size() <= entries_per_doubly_indirect_block);
  55. auto block_contents = TRY(ByteBuffer::create_uninitialized(fs().block_size()));
  56. auto* block_as_pointers = (unsigned*)block_contents.data();
  57. OutputMemoryStream stream { block_contents };
  58. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  59. if (old_blocks_length > 0) {
  60. TRY(fs().read_block(block, &buffer, fs().block_size()));
  61. }
  62. // Grow the doubly indirect block.
  63. for (unsigned i = 0; i < old_indirect_blocks_length; i++)
  64. stream << static_cast<u32>(block_as_pointers[i]);
  65. for (unsigned i = old_indirect_blocks_length; i < new_indirect_blocks_length; i++) {
  66. auto new_block = new_meta_blocks.take_last().value();
  67. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::grow_doubly_indirect_block(): Allocating indirect block {} at index {}", identifier(), new_block, i);
  68. stream << static_cast<u32>(new_block);
  69. meta_blocks++;
  70. }
  71. stream.fill_to_end(0);
  72. // Write out the indirect blocks.
  73. for (unsigned i = old_blocks_length / entries_per_block; i < new_indirect_blocks_length; i++) {
  74. auto const offset_block = i * entries_per_block;
  75. TRY(write_indirect_block(block_as_pointers[i], blocks_indices.slice(offset_block, min(blocks_indices.size() - offset_block, entries_per_block))));
  76. }
  77. // Write out the doubly indirect block.
  78. return fs().write_block(block, buffer, stream.size());
  79. }
  80. ErrorOr<void> Ext2FSInode::shrink_doubly_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, size_t new_blocks_length, unsigned& meta_blocks)
  81. {
  82. auto const entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  83. auto const entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  84. auto const old_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_block);
  85. auto const new_indirect_blocks_length = ceil_div(new_blocks_length, entries_per_block);
  86. VERIFY(old_blocks_length > 0);
  87. VERIFY(old_blocks_length >= new_blocks_length);
  88. VERIFY(new_blocks_length <= entries_per_doubly_indirect_block);
  89. auto block_contents = TRY(ByteBuffer::create_uninitialized(fs().block_size()));
  90. auto* block_as_pointers = (unsigned*)block_contents.data();
  91. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(block_as_pointers));
  92. TRY(fs().read_block(block, &buffer, fs().block_size()));
  93. // Free the unused indirect blocks.
  94. for (unsigned i = new_indirect_blocks_length; i < old_indirect_blocks_length; i++) {
  95. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_doubly_indirect_block(): Freeing indirect block {} at index {}", identifier(), block_as_pointers[i], i);
  96. TRY(fs().set_block_allocation_state(block_as_pointers[i], false));
  97. meta_blocks--;
  98. }
  99. // Free the doubly indirect block if no longer needed.
  100. if (new_blocks_length == 0) {
  101. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_doubly_indirect_block(): Freeing doubly indirect block {}", identifier(), block);
  102. TRY(fs().set_block_allocation_state(block, false));
  103. meta_blocks--;
  104. }
  105. return {};
  106. }
  107. ErrorOr<void> Ext2FSInode::grow_triply_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, Span<BlockBasedFileSystem::BlockIndex> blocks_indices, Vector<Ext2FS::BlockIndex>& new_meta_blocks, unsigned& meta_blocks)
  108. {
  109. auto const entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  110. auto const entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  111. auto const entries_per_triply_indirect_block = entries_per_block * entries_per_block;
  112. auto const old_doubly_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_doubly_indirect_block);
  113. auto const new_doubly_indirect_blocks_length = ceil_div(blocks_indices.size(), entries_per_doubly_indirect_block);
  114. VERIFY(blocks_indices.size() > 0);
  115. VERIFY(blocks_indices.size() > old_blocks_length);
  116. VERIFY(blocks_indices.size() <= entries_per_triply_indirect_block);
  117. auto block_contents = TRY(ByteBuffer::create_uninitialized(fs().block_size()));
  118. auto* block_as_pointers = (unsigned*)block_contents.data();
  119. OutputMemoryStream stream { block_contents };
  120. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  121. if (old_blocks_length > 0) {
  122. TRY(fs().read_block(block, &buffer, fs().block_size()));
  123. }
  124. // Grow the triply indirect block.
  125. for (unsigned i = 0; i < old_doubly_indirect_blocks_length; i++)
  126. stream << static_cast<u32>(block_as_pointers[i]);
  127. for (unsigned i = old_doubly_indirect_blocks_length; i < new_doubly_indirect_blocks_length; i++) {
  128. auto new_block = new_meta_blocks.take_last().value();
  129. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::grow_triply_indirect_block(): Allocating doubly indirect block {} at index {}", identifier(), new_block, i);
  130. stream << static_cast<u32>(new_block);
  131. meta_blocks++;
  132. }
  133. stream.fill_to_end(0);
  134. // Write out the doubly indirect blocks.
  135. for (unsigned i = old_blocks_length / entries_per_doubly_indirect_block; i < new_doubly_indirect_blocks_length; i++) {
  136. auto const processed_blocks = i * entries_per_doubly_indirect_block;
  137. auto const old_doubly_indirect_blocks_length = min(old_blocks_length > processed_blocks ? old_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  138. auto const new_doubly_indirect_blocks_length = min(blocks_indices.size() > processed_blocks ? blocks_indices.size() - processed_blocks : 0, entries_per_doubly_indirect_block);
  139. TRY(grow_doubly_indirect_block(block_as_pointers[i], old_doubly_indirect_blocks_length, blocks_indices.slice(processed_blocks, new_doubly_indirect_blocks_length), new_meta_blocks, meta_blocks));
  140. }
  141. // Write out the triply indirect block.
  142. return fs().write_block(block, buffer, stream.size());
  143. }
  144. ErrorOr<void> Ext2FSInode::shrink_triply_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, size_t new_blocks_length, unsigned& meta_blocks)
  145. {
  146. auto const entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  147. auto const entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  148. auto const entries_per_triply_indirect_block = entries_per_doubly_indirect_block * entries_per_block;
  149. auto const old_triply_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_doubly_indirect_block);
  150. auto const new_triply_indirect_blocks_length = new_blocks_length / entries_per_doubly_indirect_block;
  151. VERIFY(old_blocks_length > 0);
  152. VERIFY(old_blocks_length >= new_blocks_length);
  153. VERIFY(new_blocks_length <= entries_per_triply_indirect_block);
  154. auto block_contents = TRY(ByteBuffer::create_uninitialized(fs().block_size()));
  155. auto* block_as_pointers = (unsigned*)block_contents.data();
  156. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(block_as_pointers));
  157. TRY(fs().read_block(block, &buffer, fs().block_size()));
  158. // Shrink the doubly indirect blocks.
  159. for (unsigned i = new_triply_indirect_blocks_length; i < old_triply_indirect_blocks_length; i++) {
  160. auto const processed_blocks = i * entries_per_doubly_indirect_block;
  161. auto const old_doubly_indirect_blocks_length = min(old_blocks_length > processed_blocks ? old_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  162. auto const new_doubly_indirect_blocks_length = min(new_blocks_length > processed_blocks ? new_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  163. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_triply_indirect_block(): Shrinking doubly indirect block {} at index {}", identifier(), block_as_pointers[i], i);
  164. TRY(shrink_doubly_indirect_block(block_as_pointers[i], old_doubly_indirect_blocks_length, new_doubly_indirect_blocks_length, meta_blocks));
  165. }
  166. // Free the triply indirect block if no longer needed.
  167. if (new_blocks_length == 0) {
  168. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_triply_indirect_block(): Freeing triply indirect block {}", identifier(), block);
  169. TRY(fs().set_block_allocation_state(block, false));
  170. meta_blocks--;
  171. }
  172. return {};
  173. }
  174. ErrorOr<void> Ext2FSInode::flush_block_list()
  175. {
  176. MutexLocker locker(m_inode_lock);
  177. if (m_block_list.is_empty()) {
  178. m_raw_inode.i_blocks = 0;
  179. memset(m_raw_inode.i_block, 0, sizeof(m_raw_inode.i_block));
  180. set_metadata_dirty(true);
  181. return {};
  182. }
  183. // NOTE: There is a mismatch between i_blocks and blocks.size() since i_blocks includes meta blocks and blocks.size() does not.
  184. auto const old_block_count = ceil_div(size(), static_cast<u64>(fs().block_size()));
  185. auto old_shape = fs().compute_block_list_shape(old_block_count);
  186. auto const new_shape = fs().compute_block_list_shape(m_block_list.size());
  187. Vector<Ext2FS::BlockIndex> new_meta_blocks;
  188. if (new_shape.meta_blocks > old_shape.meta_blocks) {
  189. new_meta_blocks = TRY(fs().allocate_blocks(fs().group_index_from_inode(index()), new_shape.meta_blocks - old_shape.meta_blocks));
  190. }
  191. m_raw_inode.i_blocks = (m_block_list.size() + new_shape.meta_blocks) * (fs().block_size() / 512);
  192. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Old shape=({};{};{};{}:{}), new shape=({};{};{};{}:{})", identifier(), old_shape.direct_blocks, old_shape.indirect_blocks, old_shape.doubly_indirect_blocks, old_shape.triply_indirect_blocks, old_shape.meta_blocks, new_shape.direct_blocks, new_shape.indirect_blocks, new_shape.doubly_indirect_blocks, new_shape.triply_indirect_blocks, new_shape.meta_blocks);
  193. unsigned output_block_index = 0;
  194. unsigned remaining_blocks = m_block_list.size();
  195. // Deal with direct blocks.
  196. bool inode_dirty = false;
  197. VERIFY(new_shape.direct_blocks <= EXT2_NDIR_BLOCKS);
  198. for (unsigned i = 0; i < new_shape.direct_blocks; ++i) {
  199. if (BlockBasedFileSystem::BlockIndex(m_raw_inode.i_block[i]) != m_block_list[output_block_index])
  200. inode_dirty = true;
  201. m_raw_inode.i_block[i] = m_block_list[output_block_index].value();
  202. ++output_block_index;
  203. --remaining_blocks;
  204. }
  205. // e2fsck considers all blocks reachable through any of the pointers in
  206. // m_raw_inode.i_block as part of this inode regardless of the value in
  207. // m_raw_inode.i_size. When it finds more blocks than the amount that
  208. // is indicated by i_size or i_blocks it offers to repair the filesystem
  209. // by changing those values. That will actually cause further corruption.
  210. // So we must zero all pointers to blocks that are now unused.
  211. for (unsigned i = new_shape.direct_blocks; i < EXT2_NDIR_BLOCKS; ++i) {
  212. m_raw_inode.i_block[i] = 0;
  213. }
  214. if (inode_dirty) {
  215. if constexpr (EXT2_DEBUG) {
  216. dbgln("Ext2FSInode[{}]::flush_block_list(): Writing {} direct block(s) to i_block array of inode {}", identifier(), min((size_t)EXT2_NDIR_BLOCKS, m_block_list.size()), index());
  217. for (size_t i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, m_block_list.size()); ++i)
  218. dbgln(" + {}", m_block_list[i]);
  219. }
  220. set_metadata_dirty(true);
  221. }
  222. // Deal with indirect blocks.
  223. if (old_shape.indirect_blocks != new_shape.indirect_blocks) {
  224. if (new_shape.indirect_blocks > old_shape.indirect_blocks) {
  225. // Write out the indirect block.
  226. if (old_shape.indirect_blocks == 0) {
  227. auto new_block = new_meta_blocks.take_last().value();
  228. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating indirect block: {}", identifier(), new_block);
  229. m_raw_inode.i_block[EXT2_IND_BLOCK] = new_block;
  230. set_metadata_dirty(true);
  231. old_shape.meta_blocks++;
  232. }
  233. TRY(write_indirect_block(m_raw_inode.i_block[EXT2_IND_BLOCK], m_block_list.span().slice(output_block_index, new_shape.indirect_blocks)));
  234. } else if ((new_shape.indirect_blocks == 0) && (old_shape.indirect_blocks != 0)) {
  235. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Freeing indirect block: {}", identifier(), m_raw_inode.i_block[EXT2_IND_BLOCK]);
  236. TRY(fs().set_block_allocation_state(m_raw_inode.i_block[EXT2_IND_BLOCK], false));
  237. old_shape.meta_blocks--;
  238. m_raw_inode.i_block[EXT2_IND_BLOCK] = 0;
  239. }
  240. }
  241. remaining_blocks -= new_shape.indirect_blocks;
  242. output_block_index += new_shape.indirect_blocks;
  243. if (old_shape.doubly_indirect_blocks != new_shape.doubly_indirect_blocks) {
  244. // Write out the doubly indirect block.
  245. if (new_shape.doubly_indirect_blocks > old_shape.doubly_indirect_blocks) {
  246. if (old_shape.doubly_indirect_blocks == 0) {
  247. auto new_block = new_meta_blocks.take_last().value();
  248. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating doubly indirect block: {}", identifier(), new_block);
  249. m_raw_inode.i_block[EXT2_DIND_BLOCK] = new_block;
  250. set_metadata_dirty(true);
  251. old_shape.meta_blocks++;
  252. }
  253. TRY(grow_doubly_indirect_block(m_raw_inode.i_block[EXT2_DIND_BLOCK], old_shape.doubly_indirect_blocks, m_block_list.span().slice(output_block_index, new_shape.doubly_indirect_blocks), new_meta_blocks, old_shape.meta_blocks));
  254. } else {
  255. TRY(shrink_doubly_indirect_block(m_raw_inode.i_block[EXT2_DIND_BLOCK], old_shape.doubly_indirect_blocks, new_shape.doubly_indirect_blocks, old_shape.meta_blocks));
  256. if (new_shape.doubly_indirect_blocks == 0)
  257. m_raw_inode.i_block[EXT2_DIND_BLOCK] = 0;
  258. }
  259. }
  260. remaining_blocks -= new_shape.doubly_indirect_blocks;
  261. output_block_index += new_shape.doubly_indirect_blocks;
  262. if (old_shape.triply_indirect_blocks != new_shape.triply_indirect_blocks) {
  263. // Write out the triply indirect block.
  264. if (new_shape.triply_indirect_blocks > old_shape.triply_indirect_blocks) {
  265. if (old_shape.triply_indirect_blocks == 0) {
  266. auto new_block = new_meta_blocks.take_last().value();
  267. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating triply indirect block: {}", identifier(), new_block);
  268. m_raw_inode.i_block[EXT2_TIND_BLOCK] = new_block;
  269. set_metadata_dirty(true);
  270. old_shape.meta_blocks++;
  271. }
  272. TRY(grow_triply_indirect_block(m_raw_inode.i_block[EXT2_TIND_BLOCK], old_shape.triply_indirect_blocks, m_block_list.span().slice(output_block_index, new_shape.triply_indirect_blocks), new_meta_blocks, old_shape.meta_blocks));
  273. } else {
  274. TRY(shrink_triply_indirect_block(m_raw_inode.i_block[EXT2_TIND_BLOCK], old_shape.triply_indirect_blocks, new_shape.triply_indirect_blocks, old_shape.meta_blocks));
  275. if (new_shape.triply_indirect_blocks == 0)
  276. m_raw_inode.i_block[EXT2_TIND_BLOCK] = 0;
  277. }
  278. }
  279. remaining_blocks -= new_shape.triply_indirect_blocks;
  280. output_block_index += new_shape.triply_indirect_blocks;
  281. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): New meta blocks count at {}, expecting {}", identifier(), old_shape.meta_blocks, new_shape.meta_blocks);
  282. VERIFY(new_meta_blocks.size() == 0);
  283. VERIFY(old_shape.meta_blocks == new_shape.meta_blocks);
  284. if (!remaining_blocks)
  285. return {};
  286. dbgln("we don't know how to write qind ext2fs blocks, they don't exist anyway!");
  287. VERIFY_NOT_REACHED();
  288. }
  289. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list() const
  290. {
  291. return compute_block_list_impl(false);
  292. }
  293. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_with_meta_blocks() const
  294. {
  295. return compute_block_list_impl(true);
  296. }
  297. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_impl(bool include_block_list_blocks) const
  298. {
  299. // FIXME: This is really awkwardly factored.. foo_impl_internal :|
  300. auto block_list = TRY(compute_block_list_impl_internal(m_raw_inode, include_block_list_blocks));
  301. while (!block_list.is_empty() && block_list.last() == 0)
  302. block_list.take_last();
  303. return block_list;
  304. }
  305. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_impl_internal(ext2_inode const& e2inode, bool include_block_list_blocks) const
  306. {
  307. unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  308. unsigned block_count = ceil_div(size(), static_cast<u64>(fs().block_size()));
  309. // If we are handling a symbolic link, the path is stored in the 60 bytes in
  310. // the inode that are used for the 12 direct and 3 indirect block pointers,
  311. // If the path is longer than 60 characters, a block is allocated, and the
  312. // block contains the destination path. The file size corresponds to the
  313. // path length of the destination.
  314. if (Kernel::is_symlink(e2inode.i_mode) && e2inode.i_blocks == 0)
  315. block_count = 0;
  316. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::block_list_for_inode(): i_size={}, i_blocks={}, block_count={}", identifier(), e2inode.i_size, e2inode.i_blocks, block_count);
  317. unsigned blocks_remaining = block_count;
  318. if (include_block_list_blocks) {
  319. auto shape = fs().compute_block_list_shape(block_count);
  320. blocks_remaining += shape.meta_blocks;
  321. }
  322. Vector<Ext2FS::BlockIndex> list;
  323. auto add_block = [&](auto bi) -> ErrorOr<void> {
  324. if (blocks_remaining) {
  325. TRY(list.try_append(bi));
  326. --blocks_remaining;
  327. }
  328. return {};
  329. };
  330. if (include_block_list_blocks) {
  331. // This seems like an excessive over-estimate but w/e.
  332. TRY(list.try_ensure_capacity(blocks_remaining * 2));
  333. } else {
  334. TRY(list.try_ensure_capacity(blocks_remaining));
  335. }
  336. unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS);
  337. for (unsigned i = 0; i < direct_count; ++i) {
  338. auto block_index = e2inode.i_block[i];
  339. TRY(add_block(block_index));
  340. }
  341. if (!blocks_remaining)
  342. return list;
  343. // Don't need to make copy of add_block, since this capture will only
  344. // be called before compute_block_list_impl_internal finishes.
  345. auto process_block_array = [&](auto array_block_index, auto&& callback) -> ErrorOr<void> {
  346. if (include_block_list_blocks)
  347. TRY(add_block(array_block_index));
  348. auto count = min(blocks_remaining, entries_per_block);
  349. if (!count)
  350. return {};
  351. size_t read_size = count * sizeof(u32);
  352. auto array_storage = TRY(ByteBuffer::create_uninitialized(read_size));
  353. auto* array = (u32*)array_storage.data();
  354. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)array);
  355. TRY(fs().read_block(array_block_index, &buffer, read_size, 0));
  356. for (unsigned i = 0; i < count; ++i)
  357. TRY(callback(Ext2FS::BlockIndex(array[i])));
  358. return {};
  359. };
  360. TRY(process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  361. return add_block(block_index);
  362. }));
  363. if (!blocks_remaining)
  364. return list;
  365. TRY(process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  366. return process_block_array(block_index, [&](auto block_index2) -> ErrorOr<void> {
  367. return add_block(block_index2);
  368. });
  369. }));
  370. if (!blocks_remaining)
  371. return list;
  372. TRY(process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  373. return process_block_array(block_index, [&](auto block_index2) -> ErrorOr<void> {
  374. return process_block_array(block_index2, [&](auto block_index3) -> ErrorOr<void> {
  375. return add_block(block_index3);
  376. });
  377. });
  378. }));
  379. return list;
  380. }
  381. Ext2FSInode::Ext2FSInode(Ext2FS& fs, InodeIndex index)
  382. : Inode(fs, index)
  383. {
  384. }
  385. Ext2FSInode::~Ext2FSInode()
  386. {
  387. if (m_raw_inode.i_links_count == 0) {
  388. // Alas, we have nowhere to propagate any errors that occur here.
  389. (void)fs().free_inode(*this);
  390. }
  391. }
  392. u64 Ext2FSInode::size() const
  393. {
  394. if (Kernel::is_regular_file(m_raw_inode.i_mode) && ((u32)fs().get_features_readonly() & (u32)Ext2FS::FeaturesReadOnly::FileSize64bits))
  395. return static_cast<u64>(m_raw_inode.i_dir_acl) << 32 | m_raw_inode.i_size;
  396. return m_raw_inode.i_size;
  397. }
  398. InodeMetadata Ext2FSInode::metadata() const
  399. {
  400. MutexLocker locker(m_inode_lock);
  401. InodeMetadata metadata;
  402. metadata.inode = identifier();
  403. metadata.size = size();
  404. metadata.mode = m_raw_inode.i_mode;
  405. metadata.uid = m_raw_inode.i_uid;
  406. metadata.gid = m_raw_inode.i_gid;
  407. metadata.link_count = m_raw_inode.i_links_count;
  408. metadata.atime = Time::from_timespec({ m_raw_inode.i_atime, 0 });
  409. metadata.ctime = Time::from_timespec({ m_raw_inode.i_ctime, 0 });
  410. metadata.mtime = Time::from_timespec({ m_raw_inode.i_mtime, 0 });
  411. metadata.dtime = Time::from_timespec({ m_raw_inode.i_dtime, 0 });
  412. metadata.block_size = fs().block_size();
  413. metadata.block_count = m_raw_inode.i_blocks;
  414. if (Kernel::is_character_device(m_raw_inode.i_mode) || Kernel::is_block_device(m_raw_inode.i_mode)) {
  415. unsigned dev = m_raw_inode.i_block[0];
  416. if (!dev)
  417. dev = m_raw_inode.i_block[1];
  418. metadata.major_device = (dev & 0xfff00) >> 8;
  419. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  420. }
  421. return metadata;
  422. }
  423. ErrorOr<void> Ext2FSInode::flush_metadata()
  424. {
  425. MutexLocker locker(m_inode_lock);
  426. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::flush_metadata(): Flushing inode", identifier());
  427. TRY(fs().write_ext2_inode(index(), m_raw_inode));
  428. if (is_directory()) {
  429. // Unless we're about to go away permanently, invalidate the lookup cache.
  430. if (m_raw_inode.i_links_count != 0) {
  431. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  432. m_lookup_cache.clear();
  433. }
  434. }
  435. set_metadata_dirty(false);
  436. return {};
  437. }
  438. ErrorOr<void> Ext2FSInode::compute_block_list_with_exclusive_locking()
  439. {
  440. // Note: We verify that the inode mutex is being held locked. Because only the read_bytes_locked()
  441. // method uses this method and the mutex can be locked in shared mode when reading the Inode if
  442. // it is an ext2 regular file, but also in exclusive mode, when the Inode is an ext2 directory and being
  443. // traversed, we use another exclusive lock to ensure we always mutate the block list safely.
  444. VERIFY(m_inode_lock.is_locked());
  445. MutexLocker block_list_locker(m_block_list_lock);
  446. if (m_block_list.is_empty())
  447. m_block_list = TRY(compute_block_list());
  448. return {};
  449. }
  450. ErrorOr<size_t> Ext2FSInode::read_bytes_locked(off_t offset, size_t count, UserOrKernelBuffer& buffer, OpenFileDescription* description) const
  451. {
  452. VERIFY(m_inode_lock.is_locked());
  453. VERIFY(offset >= 0);
  454. if (m_raw_inode.i_size == 0)
  455. return 0;
  456. if (static_cast<u64>(offset) >= size())
  457. return 0;
  458. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  459. // This avoids wasting an entire block on short links. (Most links are short.)
  460. if (is_symlink() && size() < max_inline_symlink_length) {
  461. VERIFY(offset == 0);
  462. size_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  463. TRY(buffer.write(((u8 const*)m_raw_inode.i_block) + offset, nread));
  464. return nread;
  465. }
  466. // Note: We bypass the const declaration of this method, but this is a strong
  467. // requirement to be able to accomplish the read operation successfully.
  468. // We call this special method because it locks a separate mutex to ensure we
  469. // update the block list of the inode safely, as the m_inode_lock is locked in
  470. // shared mode.
  471. TRY(const_cast<Ext2FSInode&>(*this).compute_block_list_with_exclusive_locking());
  472. if (m_block_list.is_empty()) {
  473. dmesgln("Ext2FSInode[{}]::read_bytes(): Empty block list", identifier());
  474. return EIO;
  475. }
  476. bool allow_cache = !description || !description->is_direct();
  477. int const block_size = fs().block_size();
  478. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  479. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  480. if (last_block_logical_index >= m_block_list.size())
  481. last_block_logical_index = m_block_list.size() - 1;
  482. int offset_into_first_block = offset % block_size;
  483. size_t nread = 0;
  484. auto remaining_count = min((off_t)count, (off_t)size() - offset);
  485. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::read_bytes(): Reading up to {} bytes, {} bytes into inode to {}", identifier(), count, offset, buffer.user_or_kernel_ptr());
  486. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  487. auto block_index = m_block_list[bi.value()];
  488. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  489. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  490. auto buffer_offset = buffer.offset(nread);
  491. if (block_index.value() == 0) {
  492. // This is a hole, act as if it's filled with zeroes.
  493. TRY(buffer_offset.memset(0, num_bytes_to_copy));
  494. } else {
  495. if (auto result = fs().read_block(block_index, &buffer_offset, num_bytes_to_copy, offset_into_block, allow_cache); result.is_error()) {
  496. dmesgln("Ext2FSInode[{}]::read_bytes(): Failed to read block {} (index {})", identifier(), block_index.value(), bi);
  497. return result.release_error();
  498. }
  499. }
  500. remaining_count -= num_bytes_to_copy;
  501. nread += num_bytes_to_copy;
  502. }
  503. return nread;
  504. }
  505. ErrorOr<void> Ext2FSInode::resize(u64 new_size)
  506. {
  507. auto old_size = size();
  508. if (old_size == new_size)
  509. return {};
  510. if (!((u32)fs().get_features_readonly() & (u32)Ext2FS::FeaturesReadOnly::FileSize64bits) && (new_size >= static_cast<u32>(-1)))
  511. return ENOSPC;
  512. u64 block_size = fs().block_size();
  513. auto blocks_needed_before = ceil_div(old_size, block_size);
  514. auto blocks_needed_after = ceil_div(new_size, block_size);
  515. if constexpr (EXT2_DEBUG) {
  516. dbgln("Ext2FSInode[{}]::resize(): Blocks needed before (size was {}): {}", identifier(), old_size, blocks_needed_before);
  517. dbgln("Ext2FSInode[{}]::resize(): Blocks needed after (size is {}): {}", identifier(), new_size, blocks_needed_after);
  518. }
  519. if (blocks_needed_after > blocks_needed_before) {
  520. auto additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  521. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  522. return ENOSPC;
  523. }
  524. if (m_block_list.is_empty())
  525. m_block_list = TRY(compute_block_list());
  526. if (blocks_needed_after > blocks_needed_before) {
  527. auto blocks = TRY(fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before));
  528. TRY(m_block_list.try_extend(move(blocks)));
  529. } else if (blocks_needed_after < blocks_needed_before) {
  530. if constexpr (EXT2_VERY_DEBUG) {
  531. dbgln("Ext2FSInode[{}]::resize(): Shrinking inode, old block list is {} entries:", identifier(), m_block_list.size());
  532. for (auto block_index : m_block_list) {
  533. dbgln(" # {}", block_index);
  534. }
  535. }
  536. while (m_block_list.size() != blocks_needed_after) {
  537. auto block_index = m_block_list.take_last();
  538. if (block_index.value()) {
  539. if (auto result = fs().set_block_allocation_state(block_index, false); result.is_error()) {
  540. dbgln("Ext2FSInode[{}]::resize(): Failed to free block {}: {}", identifier(), block_index, result.error());
  541. return result;
  542. }
  543. }
  544. }
  545. }
  546. TRY(flush_block_list());
  547. m_raw_inode.i_size = new_size;
  548. if (Kernel::is_regular_file(m_raw_inode.i_mode))
  549. m_raw_inode.i_dir_acl = new_size >> 32;
  550. set_metadata_dirty(true);
  551. if (new_size > old_size) {
  552. // If we're growing the inode, make sure we zero out all the new space.
  553. // FIXME: There are definitely more efficient ways to achieve this.
  554. auto bytes_to_clear = new_size - old_size;
  555. auto clear_from = old_size;
  556. u8 zero_buffer[PAGE_SIZE] {};
  557. while (bytes_to_clear) {
  558. auto nwritten = TRY(write_bytes(clear_from, min(static_cast<u64>(sizeof(zero_buffer)), bytes_to_clear), UserOrKernelBuffer::for_kernel_buffer(zero_buffer), nullptr));
  559. VERIFY(nwritten != 0);
  560. bytes_to_clear -= nwritten;
  561. clear_from += nwritten;
  562. }
  563. }
  564. return {};
  565. }
  566. ErrorOr<size_t> Ext2FSInode::write_bytes_locked(off_t offset, size_t count, UserOrKernelBuffer const& data, OpenFileDescription* description)
  567. {
  568. VERIFY(m_inode_lock.is_locked());
  569. VERIFY(offset >= 0);
  570. if (count == 0)
  571. return 0;
  572. if (is_symlink()) {
  573. VERIFY(offset == 0);
  574. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  575. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Poking into i_block array for inline symlink ({} bytes)", identifier(), count);
  576. TRY(data.read(((u8*)m_raw_inode.i_block) + offset, count));
  577. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  578. m_raw_inode.i_size = offset + count;
  579. set_metadata_dirty(true);
  580. return count;
  581. }
  582. }
  583. bool allow_cache = !description || !description->is_direct();
  584. auto const block_size = fs().block_size();
  585. auto new_size = max(static_cast<u64>(offset) + count, size());
  586. TRY(resize(new_size));
  587. if (m_block_list.is_empty())
  588. m_block_list = TRY(compute_block_list());
  589. if (m_block_list.is_empty()) {
  590. dbgln("Ext2FSInode[{}]::write_bytes(): Empty block list", identifier());
  591. return EIO;
  592. }
  593. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  594. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  595. if (last_block_logical_index >= m_block_list.size())
  596. last_block_logical_index = m_block_list.size() - 1;
  597. size_t offset_into_first_block = offset % block_size;
  598. size_t nwritten = 0;
  599. auto remaining_count = min((off_t)count, (off_t)new_size - offset);
  600. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Writing {} bytes, {} bytes into inode from {}", identifier(), count, offset, data.user_or_kernel_ptr());
  601. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  602. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  603. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  604. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Writing block {} (offset_into_block: {})", identifier(), m_block_list[bi.value()], offset_into_block);
  605. if (auto result = fs().write_block(m_block_list[bi.value()], data.offset(nwritten), num_bytes_to_copy, offset_into_block, allow_cache); result.is_error()) {
  606. dbgln("Ext2FSInode[{}]::write_bytes_locked(): Failed to write block {} (index {})", identifier(), m_block_list[bi.value()], bi);
  607. return result.release_error();
  608. }
  609. remaining_count -= num_bytes_to_copy;
  610. nwritten += num_bytes_to_copy;
  611. }
  612. did_modify_contents();
  613. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): After write, i_size={}, i_blocks={} ({} blocks in list)", identifier(), size(), m_raw_inode.i_blocks, m_block_list.size());
  614. return nwritten;
  615. }
  616. ErrorOr<void> Ext2FSInode::traverse_as_directory(Function<ErrorOr<void>(FileSystem::DirectoryEntryView const&)> callback) const
  617. {
  618. VERIFY(is_directory());
  619. u8 buffer[max_block_size];
  620. auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
  621. auto block_size = fs().block_size();
  622. auto file_size = size();
  623. // Directory entries are guaranteed not to span multiple blocks,
  624. // so we can iterate over blocks separately.
  625. for (u64 offset = 0; offset < file_size; offset += block_size) {
  626. TRY(read_bytes(offset, block_size, buf, nullptr));
  627. using ext2_extended_dir_entry = ext2_dir_entry_2;
  628. auto* entry = reinterpret_cast<ext2_extended_dir_entry*>(buffer);
  629. auto* entries_end = reinterpret_cast<ext2_extended_dir_entry*>(buffer + block_size);
  630. while (entry < entries_end) {
  631. if (entry->inode != 0) {
  632. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::traverse_as_directory(): inode {}, name_len: {}, rec_len: {}, file_type: {}, name: {}", identifier(), entry->inode, entry->name_len, entry->rec_len, entry->file_type, StringView(entry->name, entry->name_len));
  633. TRY(callback({ { entry->name, entry->name_len }, { fsid(), entry->inode }, entry->file_type }));
  634. }
  635. entry = (ext2_extended_dir_entry*)((char*)entry + entry->rec_len);
  636. }
  637. }
  638. return {};
  639. }
  640. ErrorOr<void> Ext2FSInode::write_directory(Vector<Ext2FSDirectoryEntry>& entries)
  641. {
  642. MutexLocker locker(m_inode_lock);
  643. auto block_size = fs().block_size();
  644. // Calculate directory size and record length of entries so that
  645. // the following constraints are met:
  646. // - All used blocks must be entirely filled.
  647. // - Entries are aligned on a 4-byte boundary.
  648. // - No entry may span multiple blocks.
  649. size_t directory_size = 0;
  650. size_t space_in_block = block_size;
  651. for (size_t i = 0; i < entries.size(); ++i) {
  652. auto& entry = entries[i];
  653. entry.record_length = EXT2_DIR_REC_LEN(entry.name->length());
  654. space_in_block -= entry.record_length;
  655. if (i + 1 < entries.size()) {
  656. if (EXT2_DIR_REC_LEN(entries[i + 1].name->length()) > space_in_block) {
  657. entry.record_length += space_in_block;
  658. space_in_block = block_size;
  659. }
  660. } else {
  661. entry.record_length += space_in_block;
  662. }
  663. directory_size += entry.record_length;
  664. }
  665. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_directory(): New directory contents to write (size {}):", identifier(), directory_size);
  666. auto directory_data = TRY(ByteBuffer::create_uninitialized(directory_size));
  667. OutputMemoryStream stream { directory_data };
  668. for (auto& entry : entries) {
  669. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_directory(): Writing inode: {}, name_len: {}, rec_len: {}, file_type: {}, name: {}", identifier(), entry.inode_index, u16(entry.name->length()), u16(entry.record_length), u8(entry.file_type), entry.name);
  670. stream << u32(entry.inode_index.value());
  671. stream << u16(entry.record_length);
  672. stream << u8(entry.name->length());
  673. stream << u8(entry.file_type);
  674. stream << entry.name->bytes();
  675. int padding = entry.record_length - entry.name->length() - 8;
  676. for (int j = 0; j < padding; ++j)
  677. stream << u8(0);
  678. }
  679. VERIFY(stream.is_end());
  680. TRY(resize(stream.size()));
  681. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  682. auto nwritten = TRY(write_bytes(0, stream.size(), buffer, nullptr));
  683. set_metadata_dirty(true);
  684. if (nwritten != directory_data.size())
  685. return EIO;
  686. return {};
  687. }
  688. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FSInode::create_child(StringView name, mode_t mode, dev_t dev, UserID uid, GroupID gid)
  689. {
  690. if (Kernel::is_directory(mode))
  691. return fs().create_directory(*this, name, mode, uid, gid);
  692. return fs().create_inode(*this, name, mode, dev, uid, gid);
  693. }
  694. ErrorOr<void> Ext2FSInode::add_child(Inode& child, StringView name, mode_t mode)
  695. {
  696. MutexLocker locker(m_inode_lock);
  697. VERIFY(is_directory());
  698. if (name.length() > EXT2_NAME_LEN)
  699. return ENAMETOOLONG;
  700. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::add_child(): Adding inode {} with name '{}' and mode {:o} to directory {}", identifier(), child.index(), name, mode, index());
  701. Vector<Ext2FSDirectoryEntry> entries;
  702. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  703. if (name == entry.name)
  704. return EEXIST;
  705. auto entry_name = TRY(KString::try_create(entry.name));
  706. TRY(entries.try_append({ move(entry_name), entry.inode.index(), entry.file_type }));
  707. return {};
  708. }));
  709. TRY(child.increment_link_count());
  710. auto entry_name = TRY(KString::try_create(name));
  711. TRY(entries.try_empend(move(entry_name), child.index(), to_ext2_file_type(mode)));
  712. TRY(write_directory(entries));
  713. TRY(populate_lookup_cache());
  714. auto cache_entry_name = TRY(KString::try_create(name));
  715. TRY(m_lookup_cache.try_set(move(cache_entry_name), child.index()));
  716. did_add_child(child.identifier(), name);
  717. return {};
  718. }
  719. ErrorOr<void> Ext2FSInode::remove_child(StringView name)
  720. {
  721. MutexLocker locker(m_inode_lock);
  722. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::remove_child(): Removing '{}'", identifier(), name);
  723. VERIFY(is_directory());
  724. TRY(populate_lookup_cache());
  725. auto it = m_lookup_cache.find(name);
  726. if (it == m_lookup_cache.end())
  727. return ENOENT;
  728. auto child_inode_index = (*it).value;
  729. InodeIdentifier child_id { fsid(), child_inode_index };
  730. Vector<Ext2FSDirectoryEntry> entries;
  731. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  732. if (name != entry.name) {
  733. auto entry_name = TRY(KString::try_create(entry.name));
  734. TRY(entries.try_append({ move(entry_name), entry.inode.index(), entry.file_type }));
  735. }
  736. return {};
  737. }));
  738. TRY(write_directory(entries));
  739. m_lookup_cache.remove(it);
  740. auto child_inode = TRY(fs().get_inode(child_id));
  741. TRY(child_inode->decrement_link_count());
  742. did_remove_child(child_id, name);
  743. return {};
  744. }
  745. ErrorOr<void> Ext2FSInode::replace_child(StringView name, Inode& child)
  746. {
  747. MutexLocker locker(m_inode_lock);
  748. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::replace_child(): Replacing '{}' with inode {}", identifier(), name, child.index());
  749. VERIFY(is_directory());
  750. TRY(populate_lookup_cache());
  751. if (name.length() > EXT2_NAME_LEN)
  752. return ENAMETOOLONG;
  753. Vector<Ext2FSDirectoryEntry> entries;
  754. Optional<InodeIndex> old_child_index;
  755. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  756. auto is_replacing_this_inode = name == entry.name;
  757. auto inode_index = is_replacing_this_inode ? child.index() : entry.inode.index();
  758. auto entry_name = TRY(KString::try_create(entry.name));
  759. TRY(entries.try_empend(move(entry_name), inode_index, to_ext2_file_type(child.mode())));
  760. if (is_replacing_this_inode)
  761. old_child_index = entry.inode.index();
  762. return {};
  763. }));
  764. if (!old_child_index.has_value())
  765. return ENOENT;
  766. auto old_child = TRY(fs().get_inode({ fsid(), *old_child_index }));
  767. auto old_index_it = m_lookup_cache.find(name);
  768. VERIFY(old_index_it != m_lookup_cache.end());
  769. old_index_it->value = child.index();
  770. // NOTE: Between this line and the write_directory line, all operations must
  771. // be atomic. Any changes made should be reverted.
  772. TRY(child.increment_link_count());
  773. auto maybe_decrement_error = old_child->decrement_link_count();
  774. if (maybe_decrement_error.is_error()) {
  775. old_index_it->value = *old_child_index;
  776. MUST(child.decrement_link_count());
  777. return maybe_decrement_error;
  778. }
  779. // FIXME: The filesystem is left in an inconsistent state if this fails.
  780. // Revert the changes made above if we can't write_directory.
  781. // Ideally, decrement should be the last operation, but we currently
  782. // can't "un-write" a directory entry list.
  783. TRY(write_directory(entries));
  784. // TODO: Emit a did_replace_child event.
  785. return {};
  786. }
  787. ErrorOr<void> Ext2FSInode::populate_lookup_cache()
  788. {
  789. VERIFY(m_inode_lock.is_exclusively_locked_by_current_thread());
  790. if (!m_lookup_cache.is_empty())
  791. return {};
  792. HashMap<NonnullOwnPtr<KString>, InodeIndex> children;
  793. TRY(traverse_as_directory([&children](auto& entry) -> ErrorOr<void> {
  794. auto entry_name = TRY(KString::try_create(entry.name));
  795. TRY(children.try_set(move(entry_name), entry.inode.index()));
  796. return {};
  797. }));
  798. VERIFY(m_lookup_cache.is_empty());
  799. m_lookup_cache = move(children);
  800. return {};
  801. }
  802. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FSInode::lookup(StringView name)
  803. {
  804. VERIFY(is_directory());
  805. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): Looking up '{}'", identifier(), name);
  806. InodeIndex inode_index;
  807. {
  808. MutexLocker locker(m_inode_lock);
  809. TRY(populate_lookup_cache());
  810. auto it = m_lookup_cache.find(name);
  811. if (it == m_lookup_cache.end()) {
  812. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): '{}' not found", identifier(), name);
  813. return ENOENT;
  814. }
  815. inode_index = it->value;
  816. }
  817. return fs().get_inode({ fsid(), inode_index });
  818. }
  819. ErrorOr<void> Ext2FSInode::update_timestamps(Optional<Time> atime, Optional<Time> ctime, Optional<Time> mtime)
  820. {
  821. MutexLocker locker(m_inode_lock);
  822. if (fs().is_readonly())
  823. return EROFS;
  824. if (atime.value_or({}).to_timespec().tv_sec > INT32_MAX)
  825. return EINVAL;
  826. if (ctime.value_or({}).to_timespec().tv_sec > INT32_MAX)
  827. return EINVAL;
  828. if (mtime.value_or({}).to_timespec().tv_sec > INT32_MAX)
  829. return EINVAL;
  830. if (atime.has_value())
  831. m_raw_inode.i_atime = atime.value().to_timespec().tv_sec;
  832. if (ctime.has_value())
  833. m_raw_inode.i_ctime = ctime.value().to_timespec().tv_sec;
  834. if (mtime.has_value())
  835. m_raw_inode.i_mtime = mtime.value().to_timespec().tv_sec;
  836. set_metadata_dirty(true);
  837. return {};
  838. }
  839. ErrorOr<void> Ext2FSInode::increment_link_count()
  840. {
  841. MutexLocker locker(m_inode_lock);
  842. if (fs().is_readonly())
  843. return EROFS;
  844. constexpr size_t max_link_count = 65535;
  845. if (m_raw_inode.i_links_count == max_link_count)
  846. return EMLINK;
  847. ++m_raw_inode.i_links_count;
  848. set_metadata_dirty(true);
  849. return {};
  850. }
  851. ErrorOr<void> Ext2FSInode::decrement_link_count()
  852. {
  853. MutexLocker locker(m_inode_lock);
  854. if (fs().is_readonly())
  855. return EROFS;
  856. VERIFY(m_raw_inode.i_links_count);
  857. --m_raw_inode.i_links_count;
  858. set_metadata_dirty(true);
  859. if (m_raw_inode.i_links_count == 0)
  860. did_delete_self();
  861. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  862. fs().uncache_inode(index());
  863. return {};
  864. }
  865. ErrorOr<void> Ext2FSInode::chmod(mode_t mode)
  866. {
  867. MutexLocker locker(m_inode_lock);
  868. if (m_raw_inode.i_mode == mode)
  869. return {};
  870. m_raw_inode.i_mode = mode;
  871. set_metadata_dirty(true);
  872. return {};
  873. }
  874. ErrorOr<void> Ext2FSInode::chown(UserID uid, GroupID gid)
  875. {
  876. MutexLocker locker(m_inode_lock);
  877. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  878. return {};
  879. m_raw_inode.i_uid = uid.value();
  880. m_raw_inode.i_gid = gid.value();
  881. set_metadata_dirty(true);
  882. return {};
  883. }
  884. ErrorOr<void> Ext2FSInode::truncate(u64 size)
  885. {
  886. MutexLocker locker(m_inode_lock);
  887. if (static_cast<u64>(m_raw_inode.i_size) == size)
  888. return {};
  889. TRY(resize(size));
  890. set_metadata_dirty(true);
  891. return {};
  892. }
  893. ErrorOr<int> Ext2FSInode::get_block_address(int index)
  894. {
  895. MutexLocker locker(m_inode_lock);
  896. if (m_block_list.is_empty())
  897. m_block_list = TRY(compute_block_list());
  898. if (index < 0 || (size_t)index >= m_block_list.size())
  899. return 0;
  900. return m_block_list[index].value();
  901. }
  902. }