Ext2FileSystem.cpp 68 KB

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