Ext2FileSystem.cpp 67 KB

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