Inode.cpp 46 KB

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