Ext2FileSystem.cpp 71 KB

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