Ext2FileSystem.cpp 69 KB

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