Ext2FileSystem.cpp 67 KB

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