Ext2FileSystem.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  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/HashMap.h>
  8. #include <AK/MemoryStream.h>
  9. #include <AK/StdLibExtras.h>
  10. #include <AK/StringView.h>
  11. #include <Kernel/API/POSIX/errno.h>
  12. #include <Kernel/Debug.h>
  13. #include <Kernel/Devices/BlockDevice.h>
  14. #include <Kernel/FileSystem/Ext2FileSystem.h>
  15. #include <Kernel/FileSystem/OpenFileDescription.h>
  16. #include <Kernel/FileSystem/ext2_fs.h>
  17. #include <Kernel/Process.h>
  18. #include <Kernel/UnixTypes.h>
  19. namespace Kernel {
  20. static constexpr size_t max_block_size = 4096;
  21. static constexpr size_t max_inline_symlink_length = 60;
  22. struct Ext2FSDirectoryEntry {
  23. StringView name;
  24. InodeIndex inode_index { 0 };
  25. u8 file_type { 0 };
  26. u16 record_length { 0 };
  27. };
  28. static u8 to_ext2_file_type(mode_t mode)
  29. {
  30. if (is_regular_file(mode))
  31. return EXT2_FT_REG_FILE;
  32. if (is_directory(mode))
  33. return EXT2_FT_DIR;
  34. if (is_character_device(mode))
  35. return EXT2_FT_CHRDEV;
  36. if (is_block_device(mode))
  37. return EXT2_FT_BLKDEV;
  38. if (is_fifo(mode))
  39. return EXT2_FT_FIFO;
  40. if (is_socket(mode))
  41. return EXT2_FT_SOCK;
  42. if (is_symlink(mode))
  43. return EXT2_FT_SYMLINK;
  44. return EXT2_FT_UNKNOWN;
  45. }
  46. ErrorOr<NonnullRefPtr<Ext2FS>> Ext2FS::try_create(OpenFileDescription& file_description)
  47. {
  48. return adopt_nonnull_ref_or_enomem(new (nothrow) Ext2FS(file_description));
  49. }
  50. Ext2FS::Ext2FS(OpenFileDescription& file_description)
  51. : BlockBasedFileSystem(file_description)
  52. {
  53. }
  54. Ext2FS::~Ext2FS()
  55. {
  56. }
  57. bool Ext2FS::flush_super_block()
  58. {
  59. MutexLocker locker(m_lock);
  60. VERIFY((sizeof(ext2_super_block) % logical_block_size()) == 0);
  61. auto super_block_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&m_super_block);
  62. bool success = raw_write_blocks(2, (sizeof(ext2_super_block) / logical_block_size()), super_block_buffer);
  63. VERIFY(success);
  64. return true;
  65. }
  66. const ext2_group_desc& Ext2FS::group_descriptor(GroupIndex group_index) const
  67. {
  68. // FIXME: Should this fail gracefully somehow?
  69. VERIFY(group_index <= m_block_group_count);
  70. VERIFY(group_index > 0);
  71. return block_group_descriptors()[group_index.value() - 1];
  72. }
  73. ErrorOr<void> Ext2FS::initialize()
  74. {
  75. MutexLocker locker(m_lock);
  76. VERIFY((sizeof(ext2_super_block) % logical_block_size()) == 0);
  77. auto super_block_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&m_super_block);
  78. bool success = raw_read_blocks(2, (sizeof(ext2_super_block) / logical_block_size()), super_block_buffer);
  79. VERIFY(success);
  80. auto const& super_block = this->super_block();
  81. if constexpr (EXT2_DEBUG) {
  82. dmesgln("Ext2FS: super block magic: {:04x} (super block size: {})", super_block.s_magic, sizeof(ext2_super_block));
  83. }
  84. if (super_block.s_magic != EXT2_SUPER_MAGIC) {
  85. dmesgln("Ext2FS: Bad super block magic");
  86. return EINVAL;
  87. }
  88. if constexpr (EXT2_DEBUG) {
  89. dmesgln("Ext2FS: {} inodes, {} blocks", super_block.s_inodes_count, super_block.s_blocks_count);
  90. dmesgln("Ext2FS: Block size: {}", EXT2_BLOCK_SIZE(&super_block));
  91. dmesgln("Ext2FS: First data block: {}", super_block.s_first_data_block);
  92. dmesgln("Ext2FS: Inodes per block: {}", inodes_per_block());
  93. dmesgln("Ext2FS: Inodes per group: {}", inodes_per_group());
  94. dmesgln("Ext2FS: Free inodes: {}", super_block.s_free_inodes_count);
  95. dmesgln("Ext2FS: Descriptors per block: {}", EXT2_DESC_PER_BLOCK(&super_block));
  96. dmesgln("Ext2FS: Descriptor size: {}", EXT2_DESC_SIZE(&super_block));
  97. }
  98. set_block_size(EXT2_BLOCK_SIZE(&super_block));
  99. set_fragment_size(EXT2_FRAG_SIZE(&super_block));
  100. // Note: This depends on the block size being available.
  101. TRY(BlockBasedFileSystem::initialize());
  102. VERIFY(block_size() <= (int)max_block_size);
  103. m_block_group_count = ceil_div(super_block.s_blocks_count, super_block.s_blocks_per_group);
  104. if (m_block_group_count == 0) {
  105. dmesgln("Ext2FS: no block groups :(");
  106. return EINVAL;
  107. }
  108. auto blocks_to_read = ceil_div(m_block_group_count * sizeof(ext2_group_desc), block_size());
  109. BlockIndex first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  110. m_cached_group_descriptor_table = TRY(KBuffer::try_create_with_size(block_size() * blocks_to_read, Memory::Region::Access::ReadWrite, "Ext2FS: Block group descriptors"));
  111. auto buffer = UserOrKernelBuffer::for_kernel_buffer(m_cached_group_descriptor_table->data());
  112. TRY(read_blocks(first_block_of_bgdt, blocks_to_read, buffer));
  113. if constexpr (EXT2_DEBUG) {
  114. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  115. auto const& group = group_descriptor(i);
  116. dbgln("Ext2FS: group[{}] ( block_bitmap: {}, inode_bitmap: {}, inode_table: {} )", i, group.bg_block_bitmap, group.bg_inode_bitmap, group.bg_inode_table);
  117. }
  118. }
  119. m_root_inode = static_ptr_cast<Ext2FSInode>(TRY(get_inode({ fsid(), EXT2_ROOT_INO })));
  120. return {};
  121. }
  122. Ext2FSInode& Ext2FS::root_inode()
  123. {
  124. return *m_root_inode;
  125. }
  126. bool Ext2FS::find_block_containing_inode(InodeIndex inode, BlockIndex& block_index, unsigned& offset) const
  127. {
  128. auto const& super_block = this->super_block();
  129. if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&super_block))
  130. return false;
  131. if (inode > super_block.s_inodes_count)
  132. return false;
  133. auto const& bgd = group_descriptor(group_index_from_inode(inode));
  134. u64 full_offset = ((inode.value() - 1) % inodes_per_group()) * inode_size();
  135. block_index = bgd.bg_inode_table + (full_offset >> EXT2_BLOCK_SIZE_BITS(&super_block));
  136. offset = full_offset & (block_size() - 1);
  137. return true;
  138. }
  139. Ext2FS::BlockListShape Ext2FS::compute_block_list_shape(unsigned blocks) const
  140. {
  141. BlockListShape shape;
  142. const unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block());
  143. unsigned blocks_remaining = blocks;
  144. shape.direct_blocks = min((unsigned)EXT2_NDIR_BLOCKS, blocks_remaining);
  145. blocks_remaining -= shape.direct_blocks;
  146. if (!blocks_remaining)
  147. return shape;
  148. shape.indirect_blocks = min(blocks_remaining, entries_per_block);
  149. shape.meta_blocks += 1;
  150. blocks_remaining -= shape.indirect_blocks;
  151. if (!blocks_remaining)
  152. return shape;
  153. shape.doubly_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block);
  154. shape.meta_blocks += 1;
  155. shape.meta_blocks += ceil_div(shape.doubly_indirect_blocks, entries_per_block);
  156. blocks_remaining -= shape.doubly_indirect_blocks;
  157. if (!blocks_remaining)
  158. return shape;
  159. shape.triply_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block * entries_per_block);
  160. shape.meta_blocks += 1;
  161. shape.meta_blocks += ceil_div(shape.triply_indirect_blocks, entries_per_block * entries_per_block);
  162. shape.meta_blocks += ceil_div(shape.triply_indirect_blocks, entries_per_block);
  163. blocks_remaining -= shape.triply_indirect_blocks;
  164. VERIFY(blocks_remaining == 0);
  165. return shape;
  166. }
  167. ErrorOr<void> Ext2FSInode::write_indirect_block(BlockBasedFileSystem::BlockIndex block, Span<BlockBasedFileSystem::BlockIndex> blocks_indices)
  168. {
  169. const auto entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  170. VERIFY(blocks_indices.size() <= entries_per_block);
  171. auto block_contents_result = ByteBuffer::create_uninitialized(fs().block_size());
  172. if (!block_contents_result.has_value())
  173. return ENOMEM;
  174. auto block_contents = block_contents_result.release_value();
  175. OutputMemoryStream stream { block_contents };
  176. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  177. VERIFY(blocks_indices.size() <= EXT2_ADDR_PER_BLOCK(&fs().super_block()));
  178. for (unsigned i = 0; i < blocks_indices.size(); ++i)
  179. stream << static_cast<u32>(blocks_indices[i].value());
  180. stream.fill_to_end(0);
  181. return fs().write_block(block, buffer, stream.size());
  182. }
  183. 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)
  184. {
  185. const auto entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  186. const auto entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  187. const auto old_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_block);
  188. const auto new_indirect_blocks_length = ceil_div(blocks_indices.size(), entries_per_block);
  189. VERIFY(blocks_indices.size() > 0);
  190. VERIFY(blocks_indices.size() > old_blocks_length);
  191. VERIFY(blocks_indices.size() <= entries_per_doubly_indirect_block);
  192. auto block_contents_result = ByteBuffer::create_uninitialized(fs().block_size());
  193. if (!block_contents_result.has_value())
  194. return ENOMEM;
  195. auto block_contents = block_contents_result.release_value();
  196. auto* block_as_pointers = (unsigned*)block_contents.data();
  197. OutputMemoryStream stream { block_contents };
  198. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  199. if (old_blocks_length > 0) {
  200. TRY(fs().read_block(block, &buffer, fs().block_size()));
  201. }
  202. // Grow the doubly indirect block.
  203. for (unsigned i = 0; i < old_indirect_blocks_length; i++)
  204. stream << static_cast<u32>(block_as_pointers[i]);
  205. for (unsigned i = old_indirect_blocks_length; i < new_indirect_blocks_length; i++) {
  206. auto new_block = new_meta_blocks.take_last().value();
  207. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::grow_doubly_indirect_block(): Allocating indirect block {} at index {}", identifier(), new_block, i);
  208. stream << static_cast<u32>(new_block);
  209. meta_blocks++;
  210. }
  211. stream.fill_to_end(0);
  212. // Write out the indirect blocks.
  213. for (unsigned i = old_blocks_length / entries_per_block; i < new_indirect_blocks_length; i++) {
  214. const auto offset_block = i * entries_per_block;
  215. TRY(write_indirect_block(block_as_pointers[i], blocks_indices.slice(offset_block, min(blocks_indices.size() - offset_block, entries_per_block))));
  216. }
  217. // Write out the doubly indirect block.
  218. return fs().write_block(block, buffer, stream.size());
  219. }
  220. ErrorOr<void> Ext2FSInode::shrink_doubly_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, size_t new_blocks_length, unsigned& meta_blocks)
  221. {
  222. const auto entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  223. const auto entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  224. const auto old_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_block);
  225. const auto new_indirect_blocks_length = ceil_div(new_blocks_length, entries_per_block);
  226. VERIFY(old_blocks_length > 0);
  227. VERIFY(old_blocks_length >= new_blocks_length);
  228. VERIFY(new_blocks_length <= entries_per_doubly_indirect_block);
  229. auto block_contents_result = ByteBuffer::create_uninitialized(fs().block_size());
  230. if (!block_contents_result.has_value())
  231. return ENOMEM;
  232. auto block_contents = block_contents_result.release_value();
  233. auto* block_as_pointers = (unsigned*)block_contents.data();
  234. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(block_as_pointers));
  235. TRY(fs().read_block(block, &buffer, fs().block_size()));
  236. // Free the unused indirect blocks.
  237. for (unsigned i = new_indirect_blocks_length; i < old_indirect_blocks_length; i++) {
  238. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_doubly_indirect_block(): Freeing indirect block {} at index {}", identifier(), block_as_pointers[i], i);
  239. TRY(fs().set_block_allocation_state(block_as_pointers[i], false));
  240. meta_blocks--;
  241. }
  242. // Free the doubly indirect block if no longer needed.
  243. if (new_blocks_length == 0) {
  244. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_doubly_indirect_block(): Freeing doubly indirect block {}", identifier(), block);
  245. TRY(fs().set_block_allocation_state(block, false));
  246. meta_blocks--;
  247. }
  248. return {};
  249. }
  250. 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)
  251. {
  252. const auto entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  253. const auto entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  254. const auto entries_per_triply_indirect_block = entries_per_block * entries_per_block;
  255. const auto old_doubly_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_doubly_indirect_block);
  256. const auto new_doubly_indirect_blocks_length = ceil_div(blocks_indices.size(), entries_per_doubly_indirect_block);
  257. VERIFY(blocks_indices.size() > 0);
  258. VERIFY(blocks_indices.size() > old_blocks_length);
  259. VERIFY(blocks_indices.size() <= entries_per_triply_indirect_block);
  260. auto block_contents_result = ByteBuffer::create_uninitialized(fs().block_size());
  261. if (!block_contents_result.has_value())
  262. return ENOMEM;
  263. auto block_contents = block_contents_result.release_value();
  264. auto* block_as_pointers = (unsigned*)block_contents.data();
  265. OutputMemoryStream stream { block_contents };
  266. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  267. if (old_blocks_length > 0) {
  268. TRY(fs().read_block(block, &buffer, fs().block_size()));
  269. }
  270. // Grow the triply indirect block.
  271. for (unsigned i = 0; i < old_doubly_indirect_blocks_length; i++)
  272. stream << static_cast<u32>(block_as_pointers[i]);
  273. for (unsigned i = old_doubly_indirect_blocks_length; i < new_doubly_indirect_blocks_length; i++) {
  274. auto new_block = new_meta_blocks.take_last().value();
  275. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::grow_triply_indirect_block(): Allocating doubly indirect block {} at index {}", identifier(), new_block, i);
  276. stream << static_cast<u32>(new_block);
  277. meta_blocks++;
  278. }
  279. stream.fill_to_end(0);
  280. // Write out the doubly indirect blocks.
  281. for (unsigned i = old_blocks_length / entries_per_doubly_indirect_block; i < new_doubly_indirect_blocks_length; i++) {
  282. const auto processed_blocks = i * entries_per_doubly_indirect_block;
  283. const auto old_doubly_indirect_blocks_length = min(old_blocks_length > processed_blocks ? old_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  284. const auto new_doubly_indirect_blocks_length = min(blocks_indices.size() > processed_blocks ? blocks_indices.size() - processed_blocks : 0, entries_per_doubly_indirect_block);
  285. 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));
  286. }
  287. // Write out the triply indirect block.
  288. return fs().write_block(block, buffer, stream.size());
  289. }
  290. ErrorOr<void> Ext2FSInode::shrink_triply_indirect_block(BlockBasedFileSystem::BlockIndex block, size_t old_blocks_length, size_t new_blocks_length, unsigned& meta_blocks)
  291. {
  292. const auto entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  293. const auto entries_per_doubly_indirect_block = entries_per_block * entries_per_block;
  294. const auto entries_per_triply_indirect_block = entries_per_doubly_indirect_block * entries_per_block;
  295. const auto old_triply_indirect_blocks_length = ceil_div(old_blocks_length, entries_per_doubly_indirect_block);
  296. const auto new_triply_indirect_blocks_length = new_blocks_length / entries_per_doubly_indirect_block;
  297. VERIFY(old_blocks_length > 0);
  298. VERIFY(old_blocks_length >= new_blocks_length);
  299. VERIFY(new_blocks_length <= entries_per_triply_indirect_block);
  300. auto block_contents_result = ByteBuffer::create_uninitialized(fs().block_size());
  301. if (!block_contents_result.has_value())
  302. return ENOMEM;
  303. auto block_contents = block_contents_result.release_value();
  304. auto* block_as_pointers = (unsigned*)block_contents.data();
  305. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(block_as_pointers));
  306. TRY(fs().read_block(block, &buffer, fs().block_size()));
  307. // Shrink the doubly indirect blocks.
  308. for (unsigned i = new_triply_indirect_blocks_length; i < old_triply_indirect_blocks_length; i++) {
  309. const auto processed_blocks = i * entries_per_doubly_indirect_block;
  310. const auto old_doubly_indirect_blocks_length = min(old_blocks_length > processed_blocks ? old_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  311. const auto new_doubly_indirect_blocks_length = min(new_blocks_length > processed_blocks ? new_blocks_length - processed_blocks : 0, entries_per_doubly_indirect_block);
  312. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_triply_indirect_block(): Shrinking doubly indirect block {} at index {}", identifier(), block_as_pointers[i], i);
  313. TRY(shrink_doubly_indirect_block(block_as_pointers[i], old_doubly_indirect_blocks_length, new_doubly_indirect_blocks_length, meta_blocks));
  314. }
  315. // Free the triply indirect block if no longer needed.
  316. if (new_blocks_length == 0) {
  317. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::shrink_triply_indirect_block(): Freeing triply indirect block {}", identifier(), block);
  318. TRY(fs().set_block_allocation_state(block, false));
  319. meta_blocks--;
  320. }
  321. return {};
  322. }
  323. ErrorOr<void> Ext2FSInode::flush_block_list()
  324. {
  325. MutexLocker locker(m_inode_lock);
  326. if (m_block_list.is_empty()) {
  327. m_raw_inode.i_blocks = 0;
  328. memset(m_raw_inode.i_block, 0, sizeof(m_raw_inode.i_block));
  329. set_metadata_dirty(true);
  330. return {};
  331. }
  332. // NOTE: There is a mismatch between i_blocks and blocks.size() since i_blocks includes meta blocks and blocks.size() does not.
  333. const auto old_block_count = ceil_div(size(), static_cast<u64>(fs().block_size()));
  334. auto old_shape = fs().compute_block_list_shape(old_block_count);
  335. const auto new_shape = fs().compute_block_list_shape(m_block_list.size());
  336. Vector<Ext2FS::BlockIndex> new_meta_blocks;
  337. if (new_shape.meta_blocks > old_shape.meta_blocks) {
  338. new_meta_blocks = TRY(fs().allocate_blocks(fs().group_index_from_inode(index()), new_shape.meta_blocks - old_shape.meta_blocks));
  339. }
  340. m_raw_inode.i_blocks = (m_block_list.size() + new_shape.meta_blocks) * (fs().block_size() / 512);
  341. 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);
  342. unsigned output_block_index = 0;
  343. unsigned remaining_blocks = m_block_list.size();
  344. // Deal with direct blocks.
  345. bool inode_dirty = false;
  346. VERIFY(new_shape.direct_blocks <= EXT2_NDIR_BLOCKS);
  347. for (unsigned i = 0; i < new_shape.direct_blocks; ++i) {
  348. if (BlockBasedFileSystem::BlockIndex(m_raw_inode.i_block[i]) != m_block_list[output_block_index])
  349. inode_dirty = true;
  350. m_raw_inode.i_block[i] = m_block_list[output_block_index].value();
  351. ++output_block_index;
  352. --remaining_blocks;
  353. }
  354. // e2fsck considers all blocks reachable through any of the pointers in
  355. // m_raw_inode.i_block as part of this inode regardless of the value in
  356. // m_raw_inode.i_size. When it finds more blocks than the amount that
  357. // is indicated by i_size or i_blocks it offers to repair the filesystem
  358. // by changing those values. That will actually cause further corruption.
  359. // So we must zero all pointers to blocks that are now unused.
  360. for (unsigned i = new_shape.direct_blocks; i < EXT2_NDIR_BLOCKS; ++i) {
  361. m_raw_inode.i_block[i] = 0;
  362. }
  363. if (inode_dirty) {
  364. if constexpr (EXT2_DEBUG) {
  365. 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());
  366. for (size_t i = 0; i < min((size_t)EXT2_NDIR_BLOCKS, m_block_list.size()); ++i)
  367. dbgln(" + {}", m_block_list[i]);
  368. }
  369. set_metadata_dirty(true);
  370. }
  371. // Deal with indirect blocks.
  372. if (old_shape.indirect_blocks != new_shape.indirect_blocks) {
  373. if (new_shape.indirect_blocks > old_shape.indirect_blocks) {
  374. // Write out the indirect block.
  375. if (old_shape.indirect_blocks == 0) {
  376. auto new_block = new_meta_blocks.take_last().value();
  377. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating indirect block: {}", identifier(), new_block);
  378. m_raw_inode.i_block[EXT2_IND_BLOCK] = new_block;
  379. set_metadata_dirty(true);
  380. old_shape.meta_blocks++;
  381. }
  382. TRY(write_indirect_block(m_raw_inode.i_block[EXT2_IND_BLOCK], m_block_list.span().slice(output_block_index, new_shape.indirect_blocks)));
  383. } else if ((new_shape.indirect_blocks == 0) && (old_shape.indirect_blocks != 0)) {
  384. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Freeing indirect block: {}", identifier(), m_raw_inode.i_block[EXT2_IND_BLOCK]);
  385. TRY(fs().set_block_allocation_state(m_raw_inode.i_block[EXT2_IND_BLOCK], false));
  386. old_shape.meta_blocks--;
  387. m_raw_inode.i_block[EXT2_IND_BLOCK] = 0;
  388. }
  389. }
  390. remaining_blocks -= new_shape.indirect_blocks;
  391. output_block_index += new_shape.indirect_blocks;
  392. if (old_shape.doubly_indirect_blocks != new_shape.doubly_indirect_blocks) {
  393. // Write out the doubly indirect block.
  394. if (new_shape.doubly_indirect_blocks > old_shape.doubly_indirect_blocks) {
  395. if (old_shape.doubly_indirect_blocks == 0) {
  396. auto new_block = new_meta_blocks.take_last().value();
  397. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating doubly indirect block: {}", identifier(), new_block);
  398. m_raw_inode.i_block[EXT2_DIND_BLOCK] = new_block;
  399. set_metadata_dirty(true);
  400. old_shape.meta_blocks++;
  401. }
  402. 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));
  403. } else {
  404. 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));
  405. if (new_shape.doubly_indirect_blocks == 0)
  406. m_raw_inode.i_block[EXT2_DIND_BLOCK] = 0;
  407. }
  408. }
  409. remaining_blocks -= new_shape.doubly_indirect_blocks;
  410. output_block_index += new_shape.doubly_indirect_blocks;
  411. if (old_shape.triply_indirect_blocks != new_shape.triply_indirect_blocks) {
  412. // Write out the triply indirect block.
  413. if (new_shape.triply_indirect_blocks > old_shape.triply_indirect_blocks) {
  414. if (old_shape.triply_indirect_blocks == 0) {
  415. auto new_block = new_meta_blocks.take_last().value();
  416. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): Allocating triply indirect block: {}", identifier(), new_block);
  417. m_raw_inode.i_block[EXT2_TIND_BLOCK] = new_block;
  418. set_metadata_dirty(true);
  419. old_shape.meta_blocks++;
  420. }
  421. 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));
  422. } else {
  423. 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));
  424. if (new_shape.triply_indirect_blocks == 0)
  425. m_raw_inode.i_block[EXT2_TIND_BLOCK] = 0;
  426. }
  427. }
  428. remaining_blocks -= new_shape.triply_indirect_blocks;
  429. output_block_index += new_shape.triply_indirect_blocks;
  430. dbgln_if(EXT2_BLOCKLIST_DEBUG, "Ext2FSInode[{}]::flush_block_list(): New meta blocks count at {}, expecting {}", identifier(), old_shape.meta_blocks, new_shape.meta_blocks);
  431. VERIFY(new_meta_blocks.size() == 0);
  432. VERIFY(old_shape.meta_blocks == new_shape.meta_blocks);
  433. if (!remaining_blocks)
  434. return {};
  435. dbgln("we don't know how to write qind ext2fs blocks, they don't exist anyway!");
  436. VERIFY_NOT_REACHED();
  437. }
  438. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list() const
  439. {
  440. return compute_block_list_impl(false);
  441. }
  442. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_with_meta_blocks() const
  443. {
  444. return compute_block_list_impl(true);
  445. }
  446. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_impl(bool include_block_list_blocks) const
  447. {
  448. // FIXME: This is really awkwardly factored.. foo_impl_internal :|
  449. auto block_list = TRY(compute_block_list_impl_internal(m_raw_inode, include_block_list_blocks));
  450. while (!block_list.is_empty() && block_list.last() == 0)
  451. block_list.take_last();
  452. return block_list;
  453. }
  454. ErrorOr<Vector<Ext2FS::BlockIndex>> Ext2FSInode::compute_block_list_impl_internal(ext2_inode const& e2inode, bool include_block_list_blocks) const
  455. {
  456. unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&fs().super_block());
  457. unsigned block_count = ceil_div(size(), static_cast<u64>(fs().block_size()));
  458. // If we are handling a symbolic link, the path is stored in the 60 bytes in
  459. // the inode that are used for the 12 direct and 3 indirect block pointers,
  460. // If the path is longer than 60 characters, a block is allocated, and the
  461. // block contains the destination path. The file size corresponds to the
  462. // path length of the destination.
  463. if (::is_symlink(e2inode.i_mode) && e2inode.i_blocks == 0)
  464. block_count = 0;
  465. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::block_list_for_inode(): i_size={}, i_blocks={}, block_count={}", identifier(), e2inode.i_size, e2inode.i_blocks, block_count);
  466. unsigned blocks_remaining = block_count;
  467. if (include_block_list_blocks) {
  468. auto shape = fs().compute_block_list_shape(block_count);
  469. blocks_remaining += shape.meta_blocks;
  470. }
  471. Vector<Ext2FS::BlockIndex> list;
  472. auto add_block = [&](auto bi) -> ErrorOr<void> {
  473. if (blocks_remaining) {
  474. TRY(list.try_append(bi));
  475. --blocks_remaining;
  476. }
  477. return {};
  478. };
  479. if (include_block_list_blocks) {
  480. // This seems like an excessive over-estimate but w/e.
  481. TRY(list.try_ensure_capacity(blocks_remaining * 2));
  482. } else {
  483. TRY(list.try_ensure_capacity(blocks_remaining));
  484. }
  485. unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS);
  486. for (unsigned i = 0; i < direct_count; ++i) {
  487. auto block_index = e2inode.i_block[i];
  488. TRY(add_block(block_index));
  489. }
  490. if (!blocks_remaining)
  491. return list;
  492. // Don't need to make copy of add_block, since this capture will only
  493. // be called before compute_block_list_impl_internal finishes.
  494. auto process_block_array = [&](auto array_block_index, auto&& callback) -> ErrorOr<void> {
  495. if (include_block_list_blocks)
  496. TRY(add_block(array_block_index));
  497. auto count = min(blocks_remaining, entries_per_block);
  498. if (!count)
  499. return {};
  500. size_t read_size = count * sizeof(u32);
  501. auto maybe_array_storage = ByteBuffer::create_uninitialized(read_size);
  502. if (!maybe_array_storage.has_value())
  503. return ENOMEM;
  504. auto array_storage = maybe_array_storage.release_value();
  505. auto* array = (u32*)array_storage.data();
  506. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)array);
  507. TRY(fs().read_block(array_block_index, &buffer, read_size, 0));
  508. for (unsigned i = 0; i < count; ++i)
  509. TRY(callback(Ext2FS::BlockIndex(array[i])));
  510. return {};
  511. };
  512. TRY(process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  513. return add_block(block_index);
  514. }));
  515. if (!blocks_remaining)
  516. return list;
  517. TRY(process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  518. return process_block_array(block_index, [&](auto block_index2) -> ErrorOr<void> {
  519. return add_block(block_index2);
  520. });
  521. }));
  522. if (!blocks_remaining)
  523. return list;
  524. TRY(process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](auto block_index) -> ErrorOr<void> {
  525. return process_block_array(block_index, [&](auto block_index2) -> ErrorOr<void> {
  526. return process_block_array(block_index2, [&](auto block_index3) -> ErrorOr<void> {
  527. return add_block(block_index3);
  528. });
  529. });
  530. }));
  531. return list;
  532. }
  533. ErrorOr<void> Ext2FS::free_inode(Ext2FSInode& inode)
  534. {
  535. MutexLocker locker(m_lock);
  536. VERIFY(inode.m_raw_inode.i_links_count == 0);
  537. dbgln_if(EXT2_DEBUG, "Ext2FS[{}]::free_inode(): Inode {} has no more links, time to delete!", fsid(), inode.index());
  538. // Mark all blocks used by this inode as free.
  539. {
  540. auto blocks = TRY(inode.compute_block_list_with_meta_blocks());
  541. for (auto block_index : blocks) {
  542. VERIFY(block_index <= super_block().s_blocks_count);
  543. if (block_index.value())
  544. TRY(set_block_allocation_state(block_index, false));
  545. }
  546. }
  547. // If the inode being freed is a directory, update block group directory counter.
  548. if (inode.is_directory()) {
  549. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  550. --bgd.bg_used_dirs_count;
  551. dbgln_if(EXT2_DEBUG, "Ext2FS[{}]::free_inode(): Decremented bg_used_dirs_count to {} for inode {}", fsid(), bgd.bg_used_dirs_count, inode.index());
  552. m_block_group_descriptors_dirty = true;
  553. }
  554. // NOTE: After this point, the inode metadata is wiped.
  555. memset(&inode.m_raw_inode, 0, sizeof(ext2_inode));
  556. inode.m_raw_inode.i_dtime = kgettimeofday().to_truncated_seconds();
  557. TRY(write_ext2_inode(inode.index(), inode.m_raw_inode));
  558. // Mark the inode as free.
  559. TRY(set_inode_allocation_state(inode.index(), false));
  560. return {};
  561. }
  562. void Ext2FS::flush_block_group_descriptor_table()
  563. {
  564. MutexLocker locker(m_lock);
  565. auto blocks_to_write = ceil_div(m_block_group_count * sizeof(ext2_group_desc), block_size());
  566. auto first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  567. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)block_group_descriptors());
  568. if (auto result = write_blocks(first_block_of_bgdt, blocks_to_write, buffer); result.is_error())
  569. dbgln("Ext2FS[{}]::flush_block_group_descriptor_table(): Failed to write blocks: {}", fsid(), result.error());
  570. }
  571. void Ext2FS::flush_writes()
  572. {
  573. {
  574. MutexLocker locker(m_lock);
  575. if (m_super_block_dirty) {
  576. flush_super_block();
  577. m_super_block_dirty = false;
  578. }
  579. if (m_block_group_descriptors_dirty) {
  580. flush_block_group_descriptor_table();
  581. m_block_group_descriptors_dirty = false;
  582. }
  583. for (auto& cached_bitmap : m_cached_bitmaps) {
  584. if (cached_bitmap->dirty) {
  585. auto buffer = UserOrKernelBuffer::for_kernel_buffer(cached_bitmap->buffer->data());
  586. if (auto result = write_block(cached_bitmap->bitmap_block_index, buffer, block_size()); result.is_error()) {
  587. dbgln("Ext2FS[{}]::flush_writes(): Failed to write blocks: {}", fsid(), result.error());
  588. }
  589. cached_bitmap->dirty = false;
  590. dbgln_if(EXT2_DEBUG, "Ext2FS[{}]::flush_writes(): Flushed bitmap block {}", fsid(), cached_bitmap->bitmap_block_index);
  591. }
  592. }
  593. // Uncache Inodes that are only kept alive by the index-to-inode lookup cache.
  594. // We don't uncache Inodes that are being watched by at least one InodeWatcher.
  595. // FIXME: It would be better to keep a capped number of Inodes around.
  596. // The problem is that they are quite heavy objects, and use a lot of heap memory
  597. // for their (child name lookup) and (block list) caches.
  598. m_inode_cache.remove_all_matching([](InodeIndex, RefPtr<Ext2FSInode> const& cached_inode) {
  599. // NOTE: If we're asked to look up an inode by number (via get_inode) and it turns out
  600. // to not exist, we remember the fact that it doesn't exist by caching a nullptr.
  601. // This seems like a reasonable time to uncache ideas about unknown inodes, so do that.
  602. if (cached_inode == nullptr)
  603. return true;
  604. return cached_inode->ref_count() == 1 && !cached_inode->has_watchers();
  605. });
  606. }
  607. BlockBasedFileSystem::flush_writes();
  608. }
  609. Ext2FSInode::Ext2FSInode(Ext2FS& fs, InodeIndex index)
  610. : Inode(fs, index)
  611. {
  612. }
  613. Ext2FSInode::~Ext2FSInode()
  614. {
  615. if (m_raw_inode.i_links_count == 0) {
  616. // Alas, we have nowhere to propagate any errors that occur here.
  617. (void)fs().free_inode(*this);
  618. }
  619. }
  620. u64 Ext2FSInode::size() const
  621. {
  622. if (Kernel::is_regular_file(m_raw_inode.i_mode) && ((u32)fs().get_features_readonly() & (u32)Ext2FS::FeaturesReadOnly::FileSize64bits))
  623. return static_cast<u64>(m_raw_inode.i_dir_acl) << 32 | m_raw_inode.i_size;
  624. return m_raw_inode.i_size;
  625. }
  626. InodeMetadata Ext2FSInode::metadata() const
  627. {
  628. MutexLocker locker(m_inode_lock);
  629. InodeMetadata metadata;
  630. metadata.inode = identifier();
  631. metadata.size = size();
  632. metadata.mode = m_raw_inode.i_mode;
  633. metadata.uid = m_raw_inode.i_uid;
  634. metadata.gid = m_raw_inode.i_gid;
  635. metadata.link_count = m_raw_inode.i_links_count;
  636. metadata.atime = m_raw_inode.i_atime;
  637. metadata.ctime = m_raw_inode.i_ctime;
  638. metadata.mtime = m_raw_inode.i_mtime;
  639. metadata.dtime = m_raw_inode.i_dtime;
  640. metadata.block_size = fs().block_size();
  641. metadata.block_count = m_raw_inode.i_blocks;
  642. if (Kernel::is_character_device(m_raw_inode.i_mode) || Kernel::is_block_device(m_raw_inode.i_mode)) {
  643. unsigned dev = m_raw_inode.i_block[0];
  644. if (!dev)
  645. dev = m_raw_inode.i_block[1];
  646. metadata.major_device = (dev & 0xfff00) >> 8;
  647. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  648. }
  649. return metadata;
  650. }
  651. ErrorOr<void> Ext2FSInode::flush_metadata()
  652. {
  653. MutexLocker locker(m_inode_lock);
  654. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::flush_metadata(): Flushing inode", identifier());
  655. TRY(fs().write_ext2_inode(index(), m_raw_inode));
  656. if (is_directory()) {
  657. // Unless we're about to go away permanently, invalidate the lookup cache.
  658. if (m_raw_inode.i_links_count != 0) {
  659. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  660. m_lookup_cache.clear();
  661. }
  662. }
  663. set_metadata_dirty(false);
  664. return {};
  665. }
  666. ErrorOr<NonnullRefPtr<Inode>> Ext2FS::get_inode(InodeIdentifier inode) const
  667. {
  668. MutexLocker locker(m_lock);
  669. VERIFY(inode.fsid() == fsid());
  670. {
  671. auto it = m_inode_cache.find(inode.index());
  672. if (it != m_inode_cache.end()) {
  673. if (!it->value)
  674. return ENOENT;
  675. return NonnullRefPtr<Inode> { *it->value };
  676. }
  677. }
  678. auto inode_allocation_state = TRY(get_inode_allocation_state(inode.index()));
  679. if (!inode_allocation_state) {
  680. TRY(m_inode_cache.try_set(inode.index(), nullptr));
  681. return ENOENT;
  682. }
  683. BlockIndex block_index;
  684. unsigned offset;
  685. if (!find_block_containing_inode(inode.index(), block_index, offset))
  686. return EINVAL;
  687. auto new_inode = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index())));
  688. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(&new_inode->m_raw_inode));
  689. TRY(read_block(block_index, &buffer, sizeof(ext2_inode), offset));
  690. TRY(m_inode_cache.try_set(inode.index(), new_inode));
  691. return new_inode;
  692. }
  693. ErrorOr<size_t> Ext2FSInode::read_bytes(off_t offset, size_t count, UserOrKernelBuffer& buffer, OpenFileDescription* description) const
  694. {
  695. MutexLocker inode_locker(m_inode_lock);
  696. VERIFY(offset >= 0);
  697. if (m_raw_inode.i_size == 0)
  698. return 0;
  699. if (static_cast<u64>(offset) >= size())
  700. return 0;
  701. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  702. // This avoids wasting an entire block on short links. (Most links are short.)
  703. if (is_symlink() && size() < max_inline_symlink_length) {
  704. VERIFY(offset == 0);
  705. size_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  706. TRY(buffer.write(((const u8*)m_raw_inode.i_block) + offset, nread));
  707. return nread;
  708. }
  709. if (m_block_list.is_empty())
  710. m_block_list = TRY(compute_block_list());
  711. if (m_block_list.is_empty()) {
  712. dmesgln("Ext2FSInode[{}]::read_bytes(): Empty block list", identifier());
  713. return EIO;
  714. }
  715. bool allow_cache = !description || !description->is_direct();
  716. const int block_size = fs().block_size();
  717. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  718. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  719. if (last_block_logical_index >= m_block_list.size())
  720. last_block_logical_index = m_block_list.size() - 1;
  721. int offset_into_first_block = offset % block_size;
  722. size_t nread = 0;
  723. auto remaining_count = min((off_t)count, (off_t)size() - offset);
  724. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::read_bytes(): Reading up to {} bytes, {} bytes into inode to {}", identifier(), count, offset, buffer.user_or_kernel_ptr());
  725. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  726. auto block_index = m_block_list[bi.value()];
  727. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  728. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  729. auto buffer_offset = buffer.offset(nread);
  730. if (block_index.value() == 0) {
  731. // This is a hole, act as if it's filled with zeroes.
  732. TRY(buffer_offset.memset(0, num_bytes_to_copy));
  733. } else {
  734. if (auto result = fs().read_block(block_index, &buffer_offset, num_bytes_to_copy, offset_into_block, allow_cache); result.is_error()) {
  735. dmesgln("Ext2FSInode[{}]::read_bytes(): Failed to read block {} (index {})", identifier(), block_index.value(), bi);
  736. return result.release_error();
  737. }
  738. }
  739. remaining_count -= num_bytes_to_copy;
  740. nread += num_bytes_to_copy;
  741. }
  742. return nread;
  743. }
  744. ErrorOr<void> Ext2FSInode::resize(u64 new_size)
  745. {
  746. auto old_size = size();
  747. if (old_size == new_size)
  748. return {};
  749. if (!((u32)fs().get_features_readonly() & (u32)Ext2FS::FeaturesReadOnly::FileSize64bits) && (new_size >= static_cast<u32>(-1)))
  750. return ENOSPC;
  751. u64 block_size = fs().block_size();
  752. auto blocks_needed_before = ceil_div(old_size, block_size);
  753. auto blocks_needed_after = ceil_div(new_size, block_size);
  754. if constexpr (EXT2_DEBUG) {
  755. dbgln("Ext2FSInode[{}]::resize(): Blocks needed before (size was {}): {}", identifier(), old_size, blocks_needed_before);
  756. dbgln("Ext2FSInode[{}]::resize(): Blocks needed after (size is {}): {}", identifier(), new_size, blocks_needed_after);
  757. }
  758. if (blocks_needed_after > blocks_needed_before) {
  759. auto additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  760. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  761. return ENOSPC;
  762. }
  763. if (m_block_list.is_empty())
  764. m_block_list = TRY(compute_block_list());
  765. if (blocks_needed_after > blocks_needed_before) {
  766. auto blocks = TRY(fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before));
  767. TRY(m_block_list.try_extend(move(blocks)));
  768. } else if (blocks_needed_after < blocks_needed_before) {
  769. if constexpr (EXT2_VERY_DEBUG) {
  770. dbgln("Ext2FSInode[{}]::resize(): Shrinking inode, old block list is {} entries:", identifier(), m_block_list.size());
  771. for (auto block_index : m_block_list) {
  772. dbgln(" # {}", block_index);
  773. }
  774. }
  775. while (m_block_list.size() != blocks_needed_after) {
  776. auto block_index = m_block_list.take_last();
  777. if (block_index.value()) {
  778. if (auto result = fs().set_block_allocation_state(block_index, false); result.is_error()) {
  779. dbgln("Ext2FSInode[{}]::resize(): Failed to free block {}: {}", identifier(), block_index, result.error());
  780. return result;
  781. }
  782. }
  783. }
  784. }
  785. TRY(flush_block_list());
  786. m_raw_inode.i_size = new_size;
  787. if (Kernel::is_regular_file(m_raw_inode.i_mode))
  788. m_raw_inode.i_dir_acl = new_size >> 32;
  789. set_metadata_dirty(true);
  790. if (new_size > old_size) {
  791. // If we're growing the inode, make sure we zero out all the new space.
  792. // FIXME: There are definitely more efficient ways to achieve this.
  793. auto bytes_to_clear = new_size - old_size;
  794. auto clear_from = old_size;
  795. u8 zero_buffer[PAGE_SIZE] {};
  796. while (bytes_to_clear) {
  797. auto nwritten = TRY(write_bytes(clear_from, min(static_cast<u64>(sizeof(zero_buffer)), bytes_to_clear), UserOrKernelBuffer::for_kernel_buffer(zero_buffer), nullptr));
  798. VERIFY(nwritten != 0);
  799. bytes_to_clear -= nwritten;
  800. clear_from += nwritten;
  801. }
  802. }
  803. return {};
  804. }
  805. ErrorOr<size_t> Ext2FSInode::write_bytes(off_t offset, size_t count, const UserOrKernelBuffer& data, OpenFileDescription* description)
  806. {
  807. VERIFY(offset >= 0);
  808. if (count == 0)
  809. return 0;
  810. MutexLocker inode_locker(m_inode_lock);
  811. TRY(prepare_to_write_data());
  812. if (is_symlink()) {
  813. VERIFY(offset == 0);
  814. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  815. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes(): Poking into i_block array for inline symlink ({} bytes)", identifier(), count);
  816. TRY(data.read(((u8*)m_raw_inode.i_block) + offset, count));
  817. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  818. m_raw_inode.i_size = offset + count;
  819. set_metadata_dirty(true);
  820. return count;
  821. }
  822. }
  823. bool allow_cache = !description || !description->is_direct();
  824. const auto block_size = fs().block_size();
  825. auto new_size = max(static_cast<u64>(offset) + count, size());
  826. TRY(resize(new_size));
  827. if (m_block_list.is_empty())
  828. m_block_list = TRY(compute_block_list());
  829. if (m_block_list.is_empty()) {
  830. dbgln("Ext2FSInode[{}]::write_bytes(): Empty block list", identifier());
  831. return EIO;
  832. }
  833. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  834. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  835. if (last_block_logical_index >= m_block_list.size())
  836. last_block_logical_index = m_block_list.size() - 1;
  837. size_t offset_into_first_block = offset % block_size;
  838. size_t nwritten = 0;
  839. auto remaining_count = min((off_t)count, (off_t)new_size - offset);
  840. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes(): Writing {} bytes, {} bytes into inode from {}", identifier(), count, offset, data.user_or_kernel_ptr());
  841. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  842. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  843. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  844. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes(): Writing block {} (offset_into_block: {})", identifier(), m_block_list[bi.value()], offset_into_block);
  845. 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()) {
  846. dbgln("Ext2FSInode[{}]::write_bytes(): Failed to write block {} (index {})", identifier(), m_block_list[bi.value()], bi);
  847. return result.release_error();
  848. }
  849. remaining_count -= num_bytes_to_copy;
  850. nwritten += num_bytes_to_copy;
  851. }
  852. did_modify_contents();
  853. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes(): After write, i_size={}, i_blocks={} ({} blocks in list)", identifier(), size(), m_raw_inode.i_blocks, m_block_list.size());
  854. return nwritten;
  855. }
  856. u8 Ext2FS::internal_file_type_to_directory_entry_type(const DirectoryEntryView& entry) const
  857. {
  858. switch (entry.file_type) {
  859. case EXT2_FT_REG_FILE:
  860. return DT_REG;
  861. case EXT2_FT_DIR:
  862. return DT_DIR;
  863. case EXT2_FT_CHRDEV:
  864. return DT_CHR;
  865. case EXT2_FT_BLKDEV:
  866. return DT_BLK;
  867. case EXT2_FT_FIFO:
  868. return DT_FIFO;
  869. case EXT2_FT_SOCK:
  870. return DT_SOCK;
  871. case EXT2_FT_SYMLINK:
  872. return DT_LNK;
  873. default:
  874. return DT_UNKNOWN;
  875. }
  876. }
  877. Ext2FS::FeaturesReadOnly Ext2FS::get_features_readonly() const
  878. {
  879. if (m_super_block.s_rev_level > 0)
  880. return static_cast<Ext2FS::FeaturesReadOnly>(m_super_block.s_feature_ro_compat);
  881. return Ext2FS::FeaturesReadOnly::None;
  882. }
  883. ErrorOr<void> Ext2FSInode::traverse_as_directory(Function<ErrorOr<void>(FileSystem::DirectoryEntryView const&)> callback) const
  884. {
  885. VERIFY(is_directory());
  886. u8 buffer[max_block_size];
  887. auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
  888. auto block_size = fs().block_size();
  889. auto file_size = size();
  890. // Directory entries are guaranteed not to span multiple blocks,
  891. // so we can iterate over blocks separately.
  892. for (u64 offset = 0; offset < file_size; offset += block_size) {
  893. TRY(read_bytes(offset, block_size, buf, nullptr));
  894. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer);
  895. auto* entries_end = reinterpret_cast<ext2_dir_entry_2*>(buffer + block_size);
  896. while (entry < entries_end) {
  897. if (entry->inode != 0) {
  898. 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));
  899. TRY(callback({ { entry->name, entry->name_len }, { fsid(), entry->inode }, entry->file_type }));
  900. }
  901. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  902. }
  903. }
  904. return {};
  905. }
  906. ErrorOr<void> Ext2FSInode::write_directory(Vector<Ext2FSDirectoryEntry>& entries)
  907. {
  908. MutexLocker locker(m_inode_lock);
  909. auto block_size = fs().block_size();
  910. // Calculate directory size and record length of entries so that
  911. // the following constraints are met:
  912. // - All used blocks must be entirely filled.
  913. // - Entries are aligned on a 4-byte boundary.
  914. // - No entry may span multiple blocks.
  915. size_t directory_size = 0;
  916. size_t space_in_block = block_size;
  917. for (size_t i = 0; i < entries.size(); ++i) {
  918. auto& entry = entries[i];
  919. entry.record_length = EXT2_DIR_REC_LEN(entry.name.length());
  920. space_in_block -= entry.record_length;
  921. if (i + 1 < entries.size()) {
  922. if (EXT2_DIR_REC_LEN(entries[i + 1].name.length()) > space_in_block) {
  923. entry.record_length += space_in_block;
  924. space_in_block = block_size;
  925. }
  926. } else {
  927. entry.record_length += space_in_block;
  928. }
  929. directory_size += entry.record_length;
  930. }
  931. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_directory(): New directory contents to write (size {}):", identifier(), directory_size);
  932. auto directory_data_result = ByteBuffer::create_uninitialized(directory_size);
  933. if (!directory_data_result.has_value())
  934. return ENOMEM;
  935. auto directory_data = directory_data_result.release_value();
  936. OutputMemoryStream stream { directory_data };
  937. for (auto& entry : entries) {
  938. 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);
  939. stream << u32(entry.inode_index.value());
  940. stream << u16(entry.record_length);
  941. stream << u8(entry.name.length());
  942. stream << u8(entry.file_type);
  943. stream << entry.name.bytes();
  944. int padding = entry.record_length - entry.name.length() - 8;
  945. for (int j = 0; j < padding; ++j)
  946. stream << u8(0);
  947. }
  948. VERIFY(stream.is_end());
  949. TRY(resize(stream.size()));
  950. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  951. auto nwritten = TRY(write_bytes(0, stream.size(), buffer, nullptr));
  952. set_metadata_dirty(true);
  953. if (nwritten != directory_data.size())
  954. return EIO;
  955. return {};
  956. }
  957. ErrorOr<NonnullRefPtr<Inode>> Ext2FSInode::create_child(StringView name, mode_t mode, dev_t dev, UserID uid, GroupID gid)
  958. {
  959. if (::is_directory(mode))
  960. return fs().create_directory(*this, name, mode, uid, gid);
  961. return fs().create_inode(*this, name, mode, dev, uid, gid);
  962. }
  963. ErrorOr<void> Ext2FSInode::add_child(Inode& child, StringView name, mode_t mode)
  964. {
  965. MutexLocker locker(m_inode_lock);
  966. VERIFY(is_directory());
  967. if (name.length() > EXT2_NAME_LEN)
  968. return ENAMETOOLONG;
  969. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::add_child(): Adding inode {} with name '{}' and mode {:o} to directory {}", identifier(), child.index(), name, mode, index());
  970. Vector<Ext2FSDirectoryEntry> entries;
  971. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  972. if (name == entry.name)
  973. return EEXIST;
  974. TRY(entries.try_append({ entry.name, entry.inode.index(), entry.file_type }));
  975. return {};
  976. }));
  977. TRY(child.increment_link_count());
  978. TRY(entries.try_empend(name, child.index(), to_ext2_file_type(mode)));
  979. TRY(write_directory(entries));
  980. TRY(populate_lookup_cache());
  981. TRY(m_lookup_cache.try_set(name, child.index()));
  982. did_add_child(child.identifier(), name);
  983. return {};
  984. }
  985. ErrorOr<void> Ext2FSInode::remove_child(StringView name)
  986. {
  987. MutexLocker locker(m_inode_lock);
  988. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::remove_child(): Removing '{}'", identifier(), name);
  989. VERIFY(is_directory());
  990. TRY(populate_lookup_cache());
  991. auto it = m_lookup_cache.find(name);
  992. if (it == m_lookup_cache.end())
  993. return ENOENT;
  994. auto child_inode_index = (*it).value;
  995. InodeIdentifier child_id { fsid(), child_inode_index };
  996. Vector<Ext2FSDirectoryEntry> entries;
  997. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  998. if (name != entry.name)
  999. TRY(entries.try_append({ entry.name, entry.inode.index(), entry.file_type }));
  1000. return {};
  1001. }));
  1002. TRY(write_directory(entries));
  1003. m_lookup_cache.remove(name);
  1004. auto child_inode = TRY(fs().get_inode(child_id));
  1005. TRY(child_inode->decrement_link_count());
  1006. did_remove_child(child_id, name);
  1007. return {};
  1008. }
  1009. u64 Ext2FS::inodes_per_block() const
  1010. {
  1011. return EXT2_INODES_PER_BLOCK(&super_block());
  1012. }
  1013. u64 Ext2FS::inodes_per_group() const
  1014. {
  1015. return EXT2_INODES_PER_GROUP(&super_block());
  1016. }
  1017. u64 Ext2FS::inode_size() const
  1018. {
  1019. return EXT2_INODE_SIZE(&super_block());
  1020. }
  1021. u64 Ext2FS::blocks_per_group() const
  1022. {
  1023. return EXT2_BLOCKS_PER_GROUP(&super_block());
  1024. }
  1025. ErrorOr<void> Ext2FS::write_ext2_inode(InodeIndex inode, ext2_inode const& e2inode)
  1026. {
  1027. BlockIndex block_index;
  1028. unsigned offset;
  1029. if (!find_block_containing_inode(inode, block_index, offset))
  1030. return EINVAL;
  1031. auto buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((const u8*)&e2inode));
  1032. return write_block(block_index, buffer, inode_size(), offset);
  1033. }
  1034. auto Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count) -> ErrorOr<Vector<BlockIndex>>
  1035. {
  1036. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_blocks(preferred group: {}, count {})", preferred_group_index, count);
  1037. if (count == 0)
  1038. return Vector<BlockIndex> {};
  1039. Vector<BlockIndex> blocks;
  1040. TRY(blocks.try_ensure_capacity(count));
  1041. MutexLocker locker(m_lock);
  1042. auto group_index = preferred_group_index;
  1043. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  1044. group_index = 1;
  1045. }
  1046. while (blocks.size() < count) {
  1047. bool found_a_group = false;
  1048. if (group_descriptor(group_index).bg_free_blocks_count) {
  1049. found_a_group = true;
  1050. } else {
  1051. if (group_index == preferred_group_index)
  1052. group_index = 1;
  1053. for (; group_index <= m_block_group_count; group_index = GroupIndex { group_index.value() + 1 }) {
  1054. if (group_descriptor(group_index).bg_free_blocks_count) {
  1055. found_a_group = true;
  1056. break;
  1057. }
  1058. }
  1059. }
  1060. VERIFY(found_a_group);
  1061. auto const& bgd = group_descriptor(group_index);
  1062. auto* cached_bitmap = TRY(get_bitmap_block(bgd.bg_block_bitmap));
  1063. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  1064. auto block_bitmap = cached_bitmap->bitmap(blocks_in_group);
  1065. BlockIndex first_block_in_group = (group_index.value() - 1) * blocks_per_group() + first_block_index().value();
  1066. size_t free_region_size = 0;
  1067. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  1068. VERIFY(first_unset_bit_index.has_value());
  1069. dbgln_if(EXT2_DEBUG, "Ext2FS: allocating free region of size: {} [{}]", free_region_size, group_index);
  1070. for (size_t i = 0; i < free_region_size; ++i) {
  1071. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group.value();
  1072. TRY(set_block_allocation_state(block_index, true));
  1073. blocks.unchecked_append(block_index);
  1074. dbgln_if(EXT2_DEBUG, " allocated > {}", block_index);
  1075. }
  1076. }
  1077. VERIFY(blocks.size() == count);
  1078. return blocks;
  1079. }
  1080. ErrorOr<InodeIndex> Ext2FS::allocate_inode(GroupIndex preferred_group)
  1081. {
  1082. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode(preferred_group: {})", preferred_group);
  1083. MutexLocker locker(m_lock);
  1084. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  1085. // In those cases we should just spread it across multiple groups.
  1086. auto is_suitable_group = [this](auto group_index) {
  1087. auto& bgd = group_descriptor(group_index);
  1088. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= 1;
  1089. };
  1090. GroupIndex group_index;
  1091. if (preferred_group.value() && is_suitable_group(preferred_group)) {
  1092. group_index = preferred_group;
  1093. } else {
  1094. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  1095. if (is_suitable_group(i)) {
  1096. group_index = i;
  1097. break;
  1098. }
  1099. }
  1100. }
  1101. if (!group_index) {
  1102. dmesgln("Ext2FS: allocate_inode: no suitable group found for new inode");
  1103. return ENOSPC;
  1104. }
  1105. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode: found suitable group [{}] for new inode :^)", group_index);
  1106. auto const& bgd = group_descriptor(group_index);
  1107. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  1108. InodeIndex first_inode_in_group = (group_index.value() - 1) * inodes_per_group() + 1;
  1109. auto* cached_bitmap = TRY(get_bitmap_block(bgd.bg_inode_bitmap));
  1110. auto inode_bitmap = cached_bitmap->bitmap(inodes_in_group);
  1111. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  1112. if (inode_bitmap.get(i))
  1113. continue;
  1114. inode_bitmap.set(i, true);
  1115. auto inode_index = InodeIndex(first_inode_in_group.value() + i);
  1116. cached_bitmap->dirty = true;
  1117. m_super_block.s_free_inodes_count--;
  1118. m_super_block_dirty = true;
  1119. const_cast<ext2_group_desc&>(bgd).bg_free_inodes_count--;
  1120. m_block_group_descriptors_dirty = true;
  1121. // In case the inode cache had this cached as "non-existent", uncache that info.
  1122. m_inode_cache.remove(inode_index.value());
  1123. return inode_index;
  1124. }
  1125. dmesgln("Ext2FS: allocate_inode found no available inode, despite bgd claiming there are inodes :(");
  1126. return EIO;
  1127. }
  1128. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  1129. {
  1130. if (!block_index)
  1131. return 0;
  1132. return (block_index.value() - 1) / blocks_per_group() + 1;
  1133. }
  1134. auto Ext2FS::group_index_from_inode(InodeIndex inode) const -> GroupIndex
  1135. {
  1136. if (!inode)
  1137. return 0;
  1138. return (inode.value() - 1) / inodes_per_group() + 1;
  1139. }
  1140. ErrorOr<bool> Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1141. {
  1142. MutexLocker locker(m_lock);
  1143. if (index == 0)
  1144. return EINVAL;
  1145. auto group_index = group_index_from_inode(index);
  1146. auto const& bgd = group_descriptor(group_index);
  1147. unsigned index_in_group = index.value() - ((group_index.value() - 1) * inodes_per_group());
  1148. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1149. auto* cached_bitmap = TRY(const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap));
  1150. return cached_bitmap->bitmap(inodes_per_group()).get(bit_index);
  1151. }
  1152. ErrorOr<void> Ext2FS::update_bitmap_block(BlockIndex bitmap_block, size_t bit_index, bool new_state, u32& super_block_counter, u16& group_descriptor_counter)
  1153. {
  1154. auto* cached_bitmap = TRY(get_bitmap_block(bitmap_block));
  1155. bool current_state = cached_bitmap->bitmap(blocks_per_group()).get(bit_index);
  1156. if (current_state == new_state) {
  1157. dbgln("Ext2FS: Bit {} in bitmap block {} had unexpected state {}", bit_index, bitmap_block, current_state);
  1158. return EIO;
  1159. }
  1160. cached_bitmap->bitmap(blocks_per_group()).set(bit_index, new_state);
  1161. cached_bitmap->dirty = true;
  1162. if (new_state) {
  1163. --super_block_counter;
  1164. --group_descriptor_counter;
  1165. } else {
  1166. ++super_block_counter;
  1167. ++group_descriptor_counter;
  1168. }
  1169. m_super_block_dirty = true;
  1170. m_block_group_descriptors_dirty = true;
  1171. return {};
  1172. }
  1173. ErrorOr<void> Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1174. {
  1175. MutexLocker locker(m_lock);
  1176. auto group_index = group_index_from_inode(inode_index);
  1177. unsigned index_in_group = inode_index.value() - ((group_index.value() - 1) * inodes_per_group());
  1178. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1179. dbgln_if(EXT2_DEBUG, "Ext2FS: set_inode_allocation_state: Inode {} -> {}", inode_index, new_state);
  1180. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1181. return update_bitmap_block(bgd.bg_inode_bitmap, bit_index, new_state, m_super_block.s_free_inodes_count, bgd.bg_free_inodes_count);
  1182. }
  1183. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1184. {
  1185. return block_size() == 1024 ? 1 : 0;
  1186. }
  1187. ErrorOr<Ext2FS::CachedBitmap*> Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1188. {
  1189. for (auto& cached_bitmap : m_cached_bitmaps) {
  1190. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1191. return cached_bitmap.ptr();
  1192. }
  1193. auto block = TRY(KBuffer::try_create_with_size(block_size(), Memory::Region::Access::ReadWrite, "Ext2FS: Cached bitmap block"));
  1194. auto buffer = UserOrKernelBuffer::for_kernel_buffer(block->data());
  1195. TRY(read_block(bitmap_block_index, &buffer, block_size()));
  1196. auto new_bitmap = TRY(adopt_nonnull_own_or_enomem(new (nothrow) CachedBitmap(bitmap_block_index, move(block))));
  1197. TRY(m_cached_bitmaps.try_append(move(new_bitmap)));
  1198. return m_cached_bitmaps.last().ptr();
  1199. }
  1200. ErrorOr<void> Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1201. {
  1202. VERIFY(block_index != 0);
  1203. MutexLocker locker(m_lock);
  1204. auto group_index = group_index_from_block_index(block_index);
  1205. unsigned index_in_group = (block_index.value() - first_block_index().value()) - ((group_index.value() - 1) * blocks_per_group());
  1206. unsigned bit_index = index_in_group % blocks_per_group();
  1207. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1208. dbgln_if(EXT2_DEBUG, "Ext2FS: Block {} state -> {} (in bitmap block {})", block_index, new_state, bgd.bg_block_bitmap);
  1209. return update_bitmap_block(bgd.bg_block_bitmap, bit_index, new_state, m_super_block.s_free_blocks_count, bgd.bg_free_blocks_count);
  1210. }
  1211. ErrorOr<NonnullRefPtr<Inode>> Ext2FS::create_directory(Ext2FSInode& parent_inode, StringView name, mode_t mode, UserID uid, GroupID gid)
  1212. {
  1213. MutexLocker locker(m_lock);
  1214. VERIFY(is_directory(mode));
  1215. auto inode = TRY(create_inode(parent_inode, name, mode, 0, uid, gid));
  1216. dbgln_if(EXT2_DEBUG, "Ext2FS: create_directory: created new directory named '{} with inode {}", name, inode->index());
  1217. Vector<Ext2FSDirectoryEntry> entries;
  1218. TRY(entries.try_empend("."sv, inode->index(), static_cast<u8>(EXT2_FT_DIR)));
  1219. TRY(entries.try_empend(".."sv, parent_inode.index(), static_cast<u8>(EXT2_FT_DIR)));
  1220. TRY(static_cast<Ext2FSInode&>(*inode).write_directory(entries));
  1221. TRY(parent_inode.increment_link_count());
  1222. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1223. ++bgd.bg_used_dirs_count;
  1224. m_block_group_descriptors_dirty = true;
  1225. return inode;
  1226. }
  1227. ErrorOr<NonnullRefPtr<Inode>> Ext2FS::create_inode(Ext2FSInode& parent_inode, StringView name, mode_t mode, dev_t dev, UserID uid, GroupID gid)
  1228. {
  1229. if (name.length() > EXT2_NAME_LEN)
  1230. return ENAMETOOLONG;
  1231. if (parent_inode.m_raw_inode.i_links_count == 0)
  1232. return ENOENT;
  1233. ext2_inode e2inode {};
  1234. auto now = kgettimeofday().to_truncated_seconds();
  1235. e2inode.i_mode = mode;
  1236. e2inode.i_uid = uid.value();
  1237. e2inode.i_gid = gid.value();
  1238. e2inode.i_size = 0;
  1239. e2inode.i_atime = now;
  1240. e2inode.i_ctime = now;
  1241. e2inode.i_mtime = now;
  1242. e2inode.i_dtime = 0;
  1243. e2inode.i_flags = 0;
  1244. // For directories, add +1 link count for the "." entry in self.
  1245. e2inode.i_links_count = is_directory(mode);
  1246. if (is_character_device(mode))
  1247. e2inode.i_block[0] = dev;
  1248. else if (is_block_device(mode))
  1249. e2inode.i_block[1] = dev;
  1250. auto inode_id = TRY(allocate_inode());
  1251. dbgln_if(EXT2_DEBUG, "Ext2FS: writing initial metadata for inode {}", inode_id.value());
  1252. TRY(write_ext2_inode(inode_id, e2inode));
  1253. auto new_inode = TRY(get_inode({ fsid(), inode_id }));
  1254. dbgln_if(EXT2_DEBUG, "Ext2FS: Adding inode '{}' (mode {:o}) to parent directory {}", name, mode, parent_inode.index());
  1255. TRY(parent_inode.add_child(*new_inode, name, mode));
  1256. return new_inode;
  1257. }
  1258. ErrorOr<void> Ext2FSInode::populate_lookup_cache() const
  1259. {
  1260. MutexLocker locker(m_inode_lock);
  1261. if (!m_lookup_cache.is_empty())
  1262. return {};
  1263. HashMap<String, InodeIndex> children;
  1264. TRY(traverse_as_directory([&children](auto& entry) -> ErrorOr<void> {
  1265. TRY(children.try_set(entry.name, entry.inode.index()));
  1266. return {};
  1267. }));
  1268. VERIFY(m_lookup_cache.is_empty());
  1269. m_lookup_cache = move(children);
  1270. return {};
  1271. }
  1272. ErrorOr<NonnullRefPtr<Inode>> Ext2FSInode::lookup(StringView name)
  1273. {
  1274. VERIFY(is_directory());
  1275. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): Looking up '{}'", identifier(), name);
  1276. TRY(populate_lookup_cache());
  1277. InodeIndex inode_index;
  1278. {
  1279. MutexLocker locker(m_inode_lock);
  1280. auto it = m_lookup_cache.find(name.hash(), [&](auto& entry) { return entry.key == name; });
  1281. if (it == m_lookup_cache.end()) {
  1282. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): '{}' not found", identifier(), name);
  1283. return ENOENT;
  1284. }
  1285. inode_index = it->value;
  1286. }
  1287. return fs().get_inode({ fsid(), inode_index });
  1288. }
  1289. ErrorOr<void> Ext2FSInode::set_atime(time_t t)
  1290. {
  1291. MutexLocker locker(m_inode_lock);
  1292. if (fs().is_readonly())
  1293. return EROFS;
  1294. m_raw_inode.i_atime = t;
  1295. set_metadata_dirty(true);
  1296. return {};
  1297. }
  1298. ErrorOr<void> Ext2FSInode::set_ctime(time_t t)
  1299. {
  1300. MutexLocker locker(m_inode_lock);
  1301. if (fs().is_readonly())
  1302. return EROFS;
  1303. m_raw_inode.i_ctime = t;
  1304. set_metadata_dirty(true);
  1305. return {};
  1306. }
  1307. ErrorOr<void> Ext2FSInode::set_mtime(time_t t)
  1308. {
  1309. MutexLocker locker(m_inode_lock);
  1310. if (fs().is_readonly())
  1311. return EROFS;
  1312. m_raw_inode.i_mtime = t;
  1313. set_metadata_dirty(true);
  1314. return {};
  1315. }
  1316. ErrorOr<void> Ext2FSInode::increment_link_count()
  1317. {
  1318. MutexLocker locker(m_inode_lock);
  1319. if (fs().is_readonly())
  1320. return EROFS;
  1321. constexpr size_t max_link_count = 65535;
  1322. if (m_raw_inode.i_links_count == max_link_count)
  1323. return EMLINK;
  1324. ++m_raw_inode.i_links_count;
  1325. set_metadata_dirty(true);
  1326. return {};
  1327. }
  1328. ErrorOr<void> Ext2FSInode::decrement_link_count()
  1329. {
  1330. MutexLocker locker(m_inode_lock);
  1331. if (fs().is_readonly())
  1332. return EROFS;
  1333. VERIFY(m_raw_inode.i_links_count);
  1334. --m_raw_inode.i_links_count;
  1335. set_metadata_dirty(true);
  1336. if (m_raw_inode.i_links_count == 0)
  1337. did_delete_self();
  1338. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  1339. fs().uncache_inode(index());
  1340. return {};
  1341. }
  1342. void Ext2FS::uncache_inode(InodeIndex index)
  1343. {
  1344. MutexLocker locker(m_lock);
  1345. m_inode_cache.remove(index);
  1346. }
  1347. ErrorOr<void> Ext2FSInode::chmod(mode_t mode)
  1348. {
  1349. MutexLocker locker(m_inode_lock);
  1350. if (m_raw_inode.i_mode == mode)
  1351. return {};
  1352. m_raw_inode.i_mode = mode;
  1353. set_metadata_dirty(true);
  1354. return {};
  1355. }
  1356. ErrorOr<void> Ext2FSInode::chown(UserID uid, GroupID gid)
  1357. {
  1358. MutexLocker locker(m_inode_lock);
  1359. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1360. return {};
  1361. m_raw_inode.i_uid = uid.value();
  1362. m_raw_inode.i_gid = gid.value();
  1363. set_metadata_dirty(true);
  1364. return {};
  1365. }
  1366. ErrorOr<void> Ext2FSInode::truncate(u64 size)
  1367. {
  1368. MutexLocker locker(m_inode_lock);
  1369. if (static_cast<u64>(m_raw_inode.i_size) == size)
  1370. return {};
  1371. TRY(resize(size));
  1372. set_metadata_dirty(true);
  1373. return {};
  1374. }
  1375. ErrorOr<int> Ext2FSInode::get_block_address(int index)
  1376. {
  1377. MutexLocker locker(m_inode_lock);
  1378. if (m_block_list.is_empty())
  1379. m_block_list = TRY(compute_block_list());
  1380. if (index < 0 || (size_t)index >= m_block_list.size())
  1381. return 0;
  1382. return m_block_list[index].value();
  1383. }
  1384. unsigned Ext2FS::total_block_count() const
  1385. {
  1386. MutexLocker locker(m_lock);
  1387. return super_block().s_blocks_count;
  1388. }
  1389. unsigned Ext2FS::free_block_count() const
  1390. {
  1391. MutexLocker locker(m_lock);
  1392. return super_block().s_free_blocks_count;
  1393. }
  1394. unsigned Ext2FS::total_inode_count() const
  1395. {
  1396. MutexLocker locker(m_lock);
  1397. return super_block().s_inodes_count;
  1398. }
  1399. unsigned Ext2FS::free_inode_count() const
  1400. {
  1401. MutexLocker locker(m_lock);
  1402. return super_block().s_free_inodes_count;
  1403. }
  1404. ErrorOr<void> Ext2FS::prepare_to_unmount()
  1405. {
  1406. MutexLocker locker(m_lock);
  1407. for (auto& it : m_inode_cache) {
  1408. if (it.value->ref_count() > 1)
  1409. return EBUSY;
  1410. }
  1411. m_inode_cache.clear();
  1412. m_root_inode = nullptr;
  1413. return {};
  1414. }
  1415. }