Ext2FileSystem.cpp 67 KB

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