Ext2FileSystem.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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<NonnullLockRefPtr<FileSystem>> Ext2FS::try_create(OpenFileDescription& file_description)
  47. {
  48. return TRY(adopt_nonnull_lock_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, LockRefPtr<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<NonnullLockRefPtr<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 NonnullLockRefPtr<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_lock_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<void> Ext2FSInode::compute_block_list_with_exclusive_locking()
  676. {
  677. // Note: We verify that the inode mutex is being held locked. Because only the read_bytes_locked()
  678. // method uses this method and the mutex can be locked in shared mode when reading the Inode if
  679. // it is an ext2 regular file, but also in exclusive mode, when the Inode is an ext2 directory and being
  680. // traversed, we use another exclusive lock to ensure we always mutate the block list safely.
  681. VERIFY(m_inode_lock.is_locked());
  682. MutexLocker block_list_locker(m_block_list_lock);
  683. if (m_block_list.is_empty())
  684. m_block_list = TRY(compute_block_list());
  685. return {};
  686. }
  687. ErrorOr<size_t> Ext2FSInode::read_bytes_locked(off_t offset, size_t count, UserOrKernelBuffer& buffer, OpenFileDescription* description) const
  688. {
  689. VERIFY(m_inode_lock.is_locked());
  690. VERIFY(offset >= 0);
  691. if (m_raw_inode.i_size == 0)
  692. return 0;
  693. if (static_cast<u64>(offset) >= size())
  694. return 0;
  695. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  696. // This avoids wasting an entire block on short links. (Most links are short.)
  697. if (is_symlink() && size() < max_inline_symlink_length) {
  698. VERIFY(offset == 0);
  699. size_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  700. TRY(buffer.write(((u8 const*)m_raw_inode.i_block) + offset, nread));
  701. return nread;
  702. }
  703. // Note: We bypass the const declaration of this method, but this is a strong
  704. // requirement to be able to accomplish the read operation successfully.
  705. // We call this special method becuase it locks a separate mutex to ensure we
  706. // update the block list of the inode safely, as the m_inode_lock is locked in
  707. // shared mode.
  708. TRY(const_cast<Ext2FSInode&>(*this).compute_block_list_with_exclusive_locking());
  709. if (m_block_list.is_empty()) {
  710. dmesgln("Ext2FSInode[{}]::read_bytes(): Empty block list", identifier());
  711. return EIO;
  712. }
  713. bool allow_cache = !description || !description->is_direct();
  714. int const block_size = fs().block_size();
  715. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  716. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  717. if (last_block_logical_index >= m_block_list.size())
  718. last_block_logical_index = m_block_list.size() - 1;
  719. int offset_into_first_block = offset % block_size;
  720. size_t nread = 0;
  721. auto remaining_count = min((off_t)count, (off_t)size() - offset);
  722. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::read_bytes(): Reading up to {} bytes, {} bytes into inode to {}", identifier(), count, offset, buffer.user_or_kernel_ptr());
  723. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  724. auto block_index = m_block_list[bi.value()];
  725. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  726. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  727. auto buffer_offset = buffer.offset(nread);
  728. if (block_index.value() == 0) {
  729. // This is a hole, act as if it's filled with zeroes.
  730. TRY(buffer_offset.memset(0, num_bytes_to_copy));
  731. } else {
  732. if (auto result = fs().read_block(block_index, &buffer_offset, num_bytes_to_copy, offset_into_block, allow_cache); result.is_error()) {
  733. dmesgln("Ext2FSInode[{}]::read_bytes(): Failed to read block {} (index {})", identifier(), block_index.value(), bi);
  734. return result.release_error();
  735. }
  736. }
  737. remaining_count -= num_bytes_to_copy;
  738. nread += num_bytes_to_copy;
  739. }
  740. return nread;
  741. }
  742. ErrorOr<void> Ext2FSInode::resize(u64 new_size)
  743. {
  744. auto old_size = size();
  745. if (old_size == new_size)
  746. return {};
  747. if (!((u32)fs().get_features_readonly() & (u32)Ext2FS::FeaturesReadOnly::FileSize64bits) && (new_size >= static_cast<u32>(-1)))
  748. return ENOSPC;
  749. u64 block_size = fs().block_size();
  750. auto blocks_needed_before = ceil_div(old_size, block_size);
  751. auto blocks_needed_after = ceil_div(new_size, block_size);
  752. if constexpr (EXT2_DEBUG) {
  753. dbgln("Ext2FSInode[{}]::resize(): Blocks needed before (size was {}): {}", identifier(), old_size, blocks_needed_before);
  754. dbgln("Ext2FSInode[{}]::resize(): Blocks needed after (size is {}): {}", identifier(), new_size, blocks_needed_after);
  755. }
  756. if (blocks_needed_after > blocks_needed_before) {
  757. auto additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  758. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  759. return ENOSPC;
  760. }
  761. if (m_block_list.is_empty())
  762. m_block_list = TRY(compute_block_list());
  763. if (blocks_needed_after > blocks_needed_before) {
  764. auto blocks = TRY(fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before));
  765. TRY(m_block_list.try_extend(move(blocks)));
  766. } else if (blocks_needed_after < blocks_needed_before) {
  767. if constexpr (EXT2_VERY_DEBUG) {
  768. dbgln("Ext2FSInode[{}]::resize(): Shrinking inode, old block list is {} entries:", identifier(), m_block_list.size());
  769. for (auto block_index : m_block_list) {
  770. dbgln(" # {}", block_index);
  771. }
  772. }
  773. while (m_block_list.size() != blocks_needed_after) {
  774. auto block_index = m_block_list.take_last();
  775. if (block_index.value()) {
  776. if (auto result = fs().set_block_allocation_state(block_index, false); result.is_error()) {
  777. dbgln("Ext2FSInode[{}]::resize(): Failed to free block {}: {}", identifier(), block_index, result.error());
  778. return result;
  779. }
  780. }
  781. }
  782. }
  783. TRY(flush_block_list());
  784. m_raw_inode.i_size = new_size;
  785. if (Kernel::is_regular_file(m_raw_inode.i_mode))
  786. m_raw_inode.i_dir_acl = new_size >> 32;
  787. set_metadata_dirty(true);
  788. if (new_size > old_size) {
  789. // If we're growing the inode, make sure we zero out all the new space.
  790. // FIXME: There are definitely more efficient ways to achieve this.
  791. auto bytes_to_clear = new_size - old_size;
  792. auto clear_from = old_size;
  793. u8 zero_buffer[PAGE_SIZE] {};
  794. while (bytes_to_clear) {
  795. auto nwritten = TRY(write_bytes(clear_from, min(static_cast<u64>(sizeof(zero_buffer)), bytes_to_clear), UserOrKernelBuffer::for_kernel_buffer(zero_buffer), nullptr));
  796. VERIFY(nwritten != 0);
  797. bytes_to_clear -= nwritten;
  798. clear_from += nwritten;
  799. }
  800. }
  801. return {};
  802. }
  803. ErrorOr<size_t> Ext2FSInode::write_bytes_locked(off_t offset, size_t count, UserOrKernelBuffer const& data, OpenFileDescription* description)
  804. {
  805. VERIFY(m_inode_lock.is_locked());
  806. VERIFY(offset >= 0);
  807. if (count == 0)
  808. return 0;
  809. if (is_symlink()) {
  810. VERIFY(offset == 0);
  811. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  812. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Poking into i_block array for inline symlink ({} bytes)", identifier(), count);
  813. TRY(data.read(((u8*)m_raw_inode.i_block) + offset, count));
  814. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  815. m_raw_inode.i_size = offset + count;
  816. set_metadata_dirty(true);
  817. return count;
  818. }
  819. }
  820. bool allow_cache = !description || !description->is_direct();
  821. auto const block_size = fs().block_size();
  822. auto new_size = max(static_cast<u64>(offset) + count, size());
  823. TRY(resize(new_size));
  824. if (m_block_list.is_empty())
  825. m_block_list = TRY(compute_block_list());
  826. if (m_block_list.is_empty()) {
  827. dbgln("Ext2FSInode[{}]::write_bytes(): Empty block list", identifier());
  828. return EIO;
  829. }
  830. BlockBasedFileSystem::BlockIndex first_block_logical_index = offset / block_size;
  831. BlockBasedFileSystem::BlockIndex last_block_logical_index = (offset + count) / block_size;
  832. if (last_block_logical_index >= m_block_list.size())
  833. last_block_logical_index = m_block_list.size() - 1;
  834. size_t offset_into_first_block = offset % block_size;
  835. size_t nwritten = 0;
  836. auto remaining_count = min((off_t)count, (off_t)new_size - offset);
  837. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Writing {} bytes, {} bytes into inode from {}", identifier(), count, offset, data.user_or_kernel_ptr());
  838. for (auto bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; bi = bi.value() + 1) {
  839. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  840. size_t num_bytes_to_copy = min((size_t)block_size - offset_into_block, (size_t)remaining_count);
  841. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): Writing block {} (offset_into_block: {})", identifier(), m_block_list[bi.value()], offset_into_block);
  842. 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()) {
  843. dbgln("Ext2FSInode[{}]::write_bytes_locked(): Failed to write block {} (index {})", identifier(), m_block_list[bi.value()], bi);
  844. return result.release_error();
  845. }
  846. remaining_count -= num_bytes_to_copy;
  847. nwritten += num_bytes_to_copy;
  848. }
  849. did_modify_contents();
  850. dbgln_if(EXT2_VERY_DEBUG, "Ext2FSInode[{}]::write_bytes_locked(): After write, i_size={}, i_blocks={} ({} blocks in list)", identifier(), size(), m_raw_inode.i_blocks, m_block_list.size());
  851. return nwritten;
  852. }
  853. u8 Ext2FS::internal_file_type_to_directory_entry_type(DirectoryEntryView const& entry) const
  854. {
  855. switch (entry.file_type) {
  856. case EXT2_FT_REG_FILE:
  857. return DT_REG;
  858. case EXT2_FT_DIR:
  859. return DT_DIR;
  860. case EXT2_FT_CHRDEV:
  861. return DT_CHR;
  862. case EXT2_FT_BLKDEV:
  863. return DT_BLK;
  864. case EXT2_FT_FIFO:
  865. return DT_FIFO;
  866. case EXT2_FT_SOCK:
  867. return DT_SOCK;
  868. case EXT2_FT_SYMLINK:
  869. return DT_LNK;
  870. default:
  871. return DT_UNKNOWN;
  872. }
  873. }
  874. Ext2FS::FeaturesReadOnly Ext2FS::get_features_readonly() const
  875. {
  876. if (m_super_block.s_rev_level > 0)
  877. return static_cast<Ext2FS::FeaturesReadOnly>(m_super_block.s_feature_ro_compat);
  878. return Ext2FS::FeaturesReadOnly::None;
  879. }
  880. ErrorOr<void> Ext2FSInode::traverse_as_directory(Function<ErrorOr<void>(FileSystem::DirectoryEntryView const&)> callback) const
  881. {
  882. VERIFY(is_directory());
  883. u8 buffer[max_block_size];
  884. auto buf = UserOrKernelBuffer::for_kernel_buffer(buffer);
  885. auto block_size = fs().block_size();
  886. auto file_size = size();
  887. // Directory entries are guaranteed not to span multiple blocks,
  888. // so we can iterate over blocks separately.
  889. for (u64 offset = 0; offset < file_size; offset += block_size) {
  890. TRY(read_bytes(offset, block_size, buf, nullptr));
  891. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer);
  892. auto* entries_end = reinterpret_cast<ext2_dir_entry_2*>(buffer + block_size);
  893. while (entry < entries_end) {
  894. if (entry->inode != 0) {
  895. 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));
  896. TRY(callback({ { entry->name, entry->name_len }, { fsid(), entry->inode }, entry->file_type }));
  897. }
  898. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  899. }
  900. }
  901. return {};
  902. }
  903. ErrorOr<void> Ext2FSInode::write_directory(Vector<Ext2FSDirectoryEntry>& entries)
  904. {
  905. MutexLocker locker(m_inode_lock);
  906. auto block_size = fs().block_size();
  907. // Calculate directory size and record length of entries so that
  908. // the following constraints are met:
  909. // - All used blocks must be entirely filled.
  910. // - Entries are aligned on a 4-byte boundary.
  911. // - No entry may span multiple blocks.
  912. size_t directory_size = 0;
  913. size_t space_in_block = block_size;
  914. for (size_t i = 0; i < entries.size(); ++i) {
  915. auto& entry = entries[i];
  916. entry.record_length = EXT2_DIR_REC_LEN(entry.name->length());
  917. space_in_block -= entry.record_length;
  918. if (i + 1 < entries.size()) {
  919. if (EXT2_DIR_REC_LEN(entries[i + 1].name->length()) > space_in_block) {
  920. entry.record_length += space_in_block;
  921. space_in_block = block_size;
  922. }
  923. } else {
  924. entry.record_length += space_in_block;
  925. }
  926. directory_size += entry.record_length;
  927. }
  928. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::write_directory(): New directory contents to write (size {}):", identifier(), directory_size);
  929. auto directory_data = TRY(ByteBuffer::create_uninitialized(directory_size));
  930. OutputMemoryStream stream { directory_data };
  931. for (auto& entry : entries) {
  932. 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);
  933. stream << u32(entry.inode_index.value());
  934. stream << u16(entry.record_length);
  935. stream << u8(entry.name->length());
  936. stream << u8(entry.file_type);
  937. stream << entry.name->bytes();
  938. int padding = entry.record_length - entry.name->length() - 8;
  939. for (int j = 0; j < padding; ++j)
  940. stream << u8(0);
  941. }
  942. VERIFY(stream.is_end());
  943. TRY(resize(stream.size()));
  944. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  945. auto nwritten = TRY(write_bytes(0, stream.size(), buffer, nullptr));
  946. set_metadata_dirty(true);
  947. if (nwritten != directory_data.size())
  948. return EIO;
  949. return {};
  950. }
  951. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FSInode::create_child(StringView name, mode_t mode, dev_t dev, UserID uid, GroupID gid)
  952. {
  953. if (::is_directory(mode))
  954. return fs().create_directory(*this, name, mode, uid, gid);
  955. return fs().create_inode(*this, name, mode, dev, uid, gid);
  956. }
  957. ErrorOr<void> Ext2FSInode::add_child(Inode& child, StringView name, mode_t mode)
  958. {
  959. MutexLocker locker(m_inode_lock);
  960. VERIFY(is_directory());
  961. if (name.length() > EXT2_NAME_LEN)
  962. return ENAMETOOLONG;
  963. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::add_child(): Adding inode {} with name '{}' and mode {:o} to directory {}", identifier(), child.index(), name, mode, index());
  964. Vector<Ext2FSDirectoryEntry> entries;
  965. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  966. if (name == entry.name)
  967. return EEXIST;
  968. auto entry_name = TRY(KString::try_create(entry.name));
  969. TRY(entries.try_append({ move(entry_name), entry.inode.index(), entry.file_type }));
  970. return {};
  971. }));
  972. TRY(child.increment_link_count());
  973. auto entry_name = TRY(KString::try_create(name));
  974. TRY(entries.try_empend(move(entry_name), child.index(), to_ext2_file_type(mode)));
  975. TRY(write_directory(entries));
  976. TRY(populate_lookup_cache());
  977. auto cache_entry_name = TRY(KString::try_create(name));
  978. TRY(m_lookup_cache.try_set(move(cache_entry_name), child.index()));
  979. did_add_child(child.identifier(), name);
  980. return {};
  981. }
  982. ErrorOr<void> Ext2FSInode::remove_child(StringView name)
  983. {
  984. MutexLocker locker(m_inode_lock);
  985. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]::remove_child(): Removing '{}'", identifier(), name);
  986. VERIFY(is_directory());
  987. TRY(populate_lookup_cache());
  988. auto it = m_lookup_cache.find(name);
  989. if (it == m_lookup_cache.end())
  990. return ENOENT;
  991. auto child_inode_index = (*it).value;
  992. InodeIdentifier child_id { fsid(), child_inode_index };
  993. Vector<Ext2FSDirectoryEntry> entries;
  994. TRY(traverse_as_directory([&](auto& entry) -> ErrorOr<void> {
  995. if (name != entry.name) {
  996. auto entry_name = TRY(KString::try_create(entry.name));
  997. TRY(entries.try_append({ move(entry_name), entry.inode.index(), entry.file_type }));
  998. }
  999. return {};
  1000. }));
  1001. TRY(write_directory(entries));
  1002. m_lookup_cache.remove(it);
  1003. auto child_inode = TRY(fs().get_inode(child_id));
  1004. TRY(child_inode->decrement_link_count());
  1005. did_remove_child(child_id, name);
  1006. return {};
  1007. }
  1008. u64 Ext2FS::inodes_per_block() const
  1009. {
  1010. return EXT2_INODES_PER_BLOCK(&super_block());
  1011. }
  1012. u64 Ext2FS::inodes_per_group() const
  1013. {
  1014. return EXT2_INODES_PER_GROUP(&super_block());
  1015. }
  1016. u64 Ext2FS::inode_size() const
  1017. {
  1018. return EXT2_INODE_SIZE(&super_block());
  1019. }
  1020. u64 Ext2FS::blocks_per_group() const
  1021. {
  1022. return EXT2_BLOCKS_PER_GROUP(&super_block());
  1023. }
  1024. ErrorOr<void> Ext2FS::write_ext2_inode(InodeIndex inode, ext2_inode const& e2inode)
  1025. {
  1026. BlockIndex block_index;
  1027. unsigned offset;
  1028. if (!find_block_containing_inode(inode, block_index, offset))
  1029. return EINVAL;
  1030. auto buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((u8 const*)&e2inode));
  1031. return write_block(block_index, buffer, inode_size(), offset);
  1032. }
  1033. auto Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count) -> ErrorOr<Vector<BlockIndex>>
  1034. {
  1035. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_blocks(preferred group: {}, count {})", preferred_group_index, count);
  1036. if (count == 0)
  1037. return Vector<BlockIndex> {};
  1038. Vector<BlockIndex> blocks;
  1039. TRY(blocks.try_ensure_capacity(count));
  1040. MutexLocker locker(m_lock);
  1041. auto group_index = preferred_group_index;
  1042. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  1043. group_index = 1;
  1044. }
  1045. while (blocks.size() < count) {
  1046. bool found_a_group = false;
  1047. if (group_descriptor(group_index).bg_free_blocks_count) {
  1048. found_a_group = true;
  1049. } else {
  1050. if (group_index == preferred_group_index)
  1051. group_index = 1;
  1052. for (; group_index <= m_block_group_count; group_index = GroupIndex { group_index.value() + 1 }) {
  1053. if (group_descriptor(group_index).bg_free_blocks_count) {
  1054. found_a_group = true;
  1055. break;
  1056. }
  1057. }
  1058. }
  1059. VERIFY(found_a_group);
  1060. auto const& bgd = group_descriptor(group_index);
  1061. auto* cached_bitmap = TRY(get_bitmap_block(bgd.bg_block_bitmap));
  1062. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  1063. auto block_bitmap = cached_bitmap->bitmap(blocks_in_group);
  1064. BlockIndex first_block_in_group = (group_index.value() - 1) * blocks_per_group() + first_block_index().value();
  1065. size_t free_region_size = 0;
  1066. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  1067. VERIFY(first_unset_bit_index.has_value());
  1068. dbgln_if(EXT2_DEBUG, "Ext2FS: allocating free region of size: {} [{}]", free_region_size, group_index);
  1069. for (size_t i = 0; i < free_region_size; ++i) {
  1070. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group.value();
  1071. TRY(set_block_allocation_state(block_index, true));
  1072. blocks.unchecked_append(block_index);
  1073. dbgln_if(EXT2_DEBUG, " allocated > {}", block_index);
  1074. }
  1075. }
  1076. VERIFY(blocks.size() == count);
  1077. return blocks;
  1078. }
  1079. ErrorOr<InodeIndex> Ext2FS::allocate_inode(GroupIndex preferred_group)
  1080. {
  1081. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode(preferred_group: {})", preferred_group);
  1082. MutexLocker locker(m_lock);
  1083. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  1084. // In those cases we should just spread it across multiple groups.
  1085. auto is_suitable_group = [this](auto group_index) {
  1086. auto& bgd = group_descriptor(group_index);
  1087. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= 1;
  1088. };
  1089. GroupIndex group_index;
  1090. if (preferred_group.value() && is_suitable_group(preferred_group)) {
  1091. group_index = preferred_group;
  1092. } else {
  1093. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  1094. if (is_suitable_group(i)) {
  1095. group_index = i;
  1096. break;
  1097. }
  1098. }
  1099. }
  1100. if (!group_index) {
  1101. dmesgln("Ext2FS: allocate_inode: no suitable group found for new inode");
  1102. return ENOSPC;
  1103. }
  1104. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode: found suitable group [{}] for new inode :^)", group_index);
  1105. auto const& bgd = group_descriptor(group_index);
  1106. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  1107. InodeIndex first_inode_in_group = (group_index.value() - 1) * inodes_per_group() + 1;
  1108. auto* cached_bitmap = TRY(get_bitmap_block(bgd.bg_inode_bitmap));
  1109. auto inode_bitmap = cached_bitmap->bitmap(inodes_in_group);
  1110. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  1111. if (inode_bitmap.get(i))
  1112. continue;
  1113. inode_bitmap.set(i, true);
  1114. auto inode_index = InodeIndex(first_inode_in_group.value() + i);
  1115. cached_bitmap->dirty = true;
  1116. m_super_block.s_free_inodes_count--;
  1117. m_super_block_dirty = true;
  1118. const_cast<ext2_group_desc&>(bgd).bg_free_inodes_count--;
  1119. m_block_group_descriptors_dirty = true;
  1120. // In case the inode cache had this cached as "non-existent", uncache that info.
  1121. m_inode_cache.remove(inode_index.value());
  1122. return inode_index;
  1123. }
  1124. dmesgln("Ext2FS: allocate_inode found no available inode, despite bgd claiming there are inodes :(");
  1125. return EIO;
  1126. }
  1127. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  1128. {
  1129. if (!block_index)
  1130. return 0;
  1131. return (block_index.value() - 1) / blocks_per_group() + 1;
  1132. }
  1133. auto Ext2FS::group_index_from_inode(InodeIndex inode) const -> GroupIndex
  1134. {
  1135. if (!inode)
  1136. return 0;
  1137. return (inode.value() - 1) / inodes_per_group() + 1;
  1138. }
  1139. ErrorOr<bool> Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1140. {
  1141. MutexLocker locker(m_lock);
  1142. if (index == 0)
  1143. return EINVAL;
  1144. auto group_index = group_index_from_inode(index);
  1145. auto const& bgd = group_descriptor(group_index);
  1146. unsigned index_in_group = index.value() - ((group_index.value() - 1) * inodes_per_group());
  1147. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1148. auto* cached_bitmap = TRY(const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap));
  1149. return cached_bitmap->bitmap(inodes_per_group()).get(bit_index);
  1150. }
  1151. ErrorOr<void> Ext2FS::update_bitmap_block(BlockIndex bitmap_block, size_t bit_index, bool new_state, u32& super_block_counter, u16& group_descriptor_counter)
  1152. {
  1153. auto* cached_bitmap = TRY(get_bitmap_block(bitmap_block));
  1154. bool current_state = cached_bitmap->bitmap(blocks_per_group()).get(bit_index);
  1155. if (current_state == new_state) {
  1156. dbgln("Ext2FS: Bit {} in bitmap block {} had unexpected state {}", bit_index, bitmap_block, current_state);
  1157. return EIO;
  1158. }
  1159. cached_bitmap->bitmap(blocks_per_group()).set(bit_index, new_state);
  1160. cached_bitmap->dirty = true;
  1161. if (new_state) {
  1162. --super_block_counter;
  1163. --group_descriptor_counter;
  1164. } else {
  1165. ++super_block_counter;
  1166. ++group_descriptor_counter;
  1167. }
  1168. m_super_block_dirty = true;
  1169. m_block_group_descriptors_dirty = true;
  1170. return {};
  1171. }
  1172. ErrorOr<void> Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1173. {
  1174. MutexLocker locker(m_lock);
  1175. auto group_index = group_index_from_inode(inode_index);
  1176. unsigned index_in_group = inode_index.value() - ((group_index.value() - 1) * inodes_per_group());
  1177. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1178. dbgln_if(EXT2_DEBUG, "Ext2FS: set_inode_allocation_state: Inode {} -> {}", inode_index, new_state);
  1179. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1180. return update_bitmap_block(bgd.bg_inode_bitmap, bit_index, new_state, m_super_block.s_free_inodes_count, bgd.bg_free_inodes_count);
  1181. }
  1182. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1183. {
  1184. return block_size() == 1024 ? 1 : 0;
  1185. }
  1186. ErrorOr<Ext2FS::CachedBitmap*> Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1187. {
  1188. for (auto& cached_bitmap : m_cached_bitmaps) {
  1189. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1190. return cached_bitmap.ptr();
  1191. }
  1192. auto block = TRY(KBuffer::try_create_with_size("Ext2FS: Cached bitmap block"sv, block_size(), Memory::Region::Access::ReadWrite));
  1193. auto buffer = UserOrKernelBuffer::for_kernel_buffer(block->data());
  1194. TRY(read_block(bitmap_block_index, &buffer, block_size()));
  1195. auto new_bitmap = TRY(adopt_nonnull_own_or_enomem(new (nothrow) CachedBitmap(bitmap_block_index, move(block))));
  1196. TRY(m_cached_bitmaps.try_append(move(new_bitmap)));
  1197. return m_cached_bitmaps.last().ptr();
  1198. }
  1199. ErrorOr<void> Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1200. {
  1201. VERIFY(block_index != 0);
  1202. MutexLocker locker(m_lock);
  1203. auto group_index = group_index_from_block_index(block_index);
  1204. unsigned index_in_group = (block_index.value() - first_block_index().value()) - ((group_index.value() - 1) * blocks_per_group());
  1205. unsigned bit_index = index_in_group % blocks_per_group();
  1206. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1207. dbgln_if(EXT2_DEBUG, "Ext2FS: Block {} state -> {} (in bitmap block {})", block_index, new_state, bgd.bg_block_bitmap);
  1208. return update_bitmap_block(bgd.bg_block_bitmap, bit_index, new_state, m_super_block.s_free_blocks_count, bgd.bg_free_blocks_count);
  1209. }
  1210. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FS::create_directory(Ext2FSInode& parent_inode, StringView name, mode_t mode, UserID uid, GroupID gid)
  1211. {
  1212. MutexLocker locker(m_lock);
  1213. VERIFY(is_directory(mode));
  1214. auto inode = TRY(create_inode(parent_inode, name, mode, 0, uid, gid));
  1215. dbgln_if(EXT2_DEBUG, "Ext2FS: create_directory: created new directory named '{} with inode {}", name, inode->index());
  1216. Vector<Ext2FSDirectoryEntry> entries;
  1217. auto current_directory_name = TRY(KString::try_create("."sv));
  1218. TRY(entries.try_empend(move(current_directory_name), inode->index(), static_cast<u8>(EXT2_FT_DIR)));
  1219. auto parent_directory_name = TRY(KString::try_create(".."sv));
  1220. TRY(entries.try_empend(move(parent_directory_name), parent_inode.index(), static_cast<u8>(EXT2_FT_DIR)));
  1221. TRY(static_cast<Ext2FSInode&>(*inode).write_directory(entries));
  1222. TRY(parent_inode.increment_link_count());
  1223. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1224. ++bgd.bg_used_dirs_count;
  1225. m_block_group_descriptors_dirty = true;
  1226. return inode;
  1227. }
  1228. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FS::create_inode(Ext2FSInode& parent_inode, StringView name, mode_t mode, dev_t dev, UserID uid, GroupID gid)
  1229. {
  1230. if (name.length() > EXT2_NAME_LEN)
  1231. return ENAMETOOLONG;
  1232. if (parent_inode.m_raw_inode.i_links_count == 0)
  1233. return ENOENT;
  1234. ext2_inode e2inode {};
  1235. auto now = kgettimeofday().to_truncated_seconds();
  1236. e2inode.i_mode = mode;
  1237. e2inode.i_uid = uid.value();
  1238. e2inode.i_gid = gid.value();
  1239. e2inode.i_size = 0;
  1240. e2inode.i_atime = now;
  1241. e2inode.i_ctime = now;
  1242. e2inode.i_mtime = now;
  1243. e2inode.i_dtime = 0;
  1244. e2inode.i_flags = 0;
  1245. // For directories, add +1 link count for the "." entry in self.
  1246. e2inode.i_links_count = is_directory(mode);
  1247. if (is_character_device(mode))
  1248. e2inode.i_block[0] = dev;
  1249. else if (is_block_device(mode))
  1250. e2inode.i_block[1] = dev;
  1251. auto inode_id = TRY(allocate_inode());
  1252. dbgln_if(EXT2_DEBUG, "Ext2FS: writing initial metadata for inode {}", inode_id.value());
  1253. TRY(write_ext2_inode(inode_id, e2inode));
  1254. auto new_inode = TRY(get_inode({ fsid(), inode_id }));
  1255. dbgln_if(EXT2_DEBUG, "Ext2FS: Adding inode '{}' (mode {:o}) to parent directory {}", name, mode, parent_inode.index());
  1256. TRY(parent_inode.add_child(*new_inode, name, mode));
  1257. return new_inode;
  1258. }
  1259. ErrorOr<void> Ext2FSInode::populate_lookup_cache()
  1260. {
  1261. VERIFY(m_inode_lock.is_exclusively_locked_by_current_thread());
  1262. if (!m_lookup_cache.is_empty())
  1263. return {};
  1264. HashMap<NonnullOwnPtr<KString>, InodeIndex> children;
  1265. TRY(traverse_as_directory([&children](auto& entry) -> ErrorOr<void> {
  1266. auto entry_name = TRY(KString::try_create(entry.name));
  1267. TRY(children.try_set(move(entry_name), entry.inode.index()));
  1268. return {};
  1269. }));
  1270. VERIFY(m_lookup_cache.is_empty());
  1271. m_lookup_cache = move(children);
  1272. return {};
  1273. }
  1274. ErrorOr<NonnullLockRefPtr<Inode>> Ext2FSInode::lookup(StringView name)
  1275. {
  1276. VERIFY(is_directory());
  1277. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): Looking up '{}'", identifier(), name);
  1278. InodeIndex inode_index;
  1279. {
  1280. MutexLocker locker(m_inode_lock);
  1281. TRY(populate_lookup_cache());
  1282. auto it = m_lookup_cache.find(name);
  1283. if (it == m_lookup_cache.end()) {
  1284. dbgln_if(EXT2_DEBUG, "Ext2FSInode[{}]:lookup(): '{}' not found", identifier(), name);
  1285. return ENOENT;
  1286. }
  1287. inode_index = it->value;
  1288. }
  1289. return fs().get_inode({ fsid(), inode_index });
  1290. }
  1291. ErrorOr<void> Ext2FSInode::update_timestamps(Optional<time_t> atime, Optional<time_t> ctime, Optional<time_t> mtime)
  1292. {
  1293. MutexLocker locker(m_inode_lock);
  1294. if (fs().is_readonly())
  1295. return EROFS;
  1296. if (atime.value_or(0) > INT32_MAX)
  1297. return EINVAL;
  1298. if (ctime.value_or(0) > INT32_MAX)
  1299. return EINVAL;
  1300. if (mtime.value_or(0) > INT32_MAX)
  1301. return EINVAL;
  1302. if (atime.has_value())
  1303. m_raw_inode.i_atime = atime.value();
  1304. if (ctime.has_value())
  1305. m_raw_inode.i_ctime = ctime.value();
  1306. if (mtime.has_value())
  1307. m_raw_inode.i_mtime = mtime.value();
  1308. set_metadata_dirty(true);
  1309. return {};
  1310. }
  1311. ErrorOr<void> Ext2FSInode::increment_link_count()
  1312. {
  1313. MutexLocker locker(m_inode_lock);
  1314. if (fs().is_readonly())
  1315. return EROFS;
  1316. constexpr size_t max_link_count = 65535;
  1317. if (m_raw_inode.i_links_count == max_link_count)
  1318. return EMLINK;
  1319. ++m_raw_inode.i_links_count;
  1320. set_metadata_dirty(true);
  1321. return {};
  1322. }
  1323. ErrorOr<void> Ext2FSInode::decrement_link_count()
  1324. {
  1325. MutexLocker locker(m_inode_lock);
  1326. if (fs().is_readonly())
  1327. return EROFS;
  1328. VERIFY(m_raw_inode.i_links_count);
  1329. --m_raw_inode.i_links_count;
  1330. set_metadata_dirty(true);
  1331. if (m_raw_inode.i_links_count == 0)
  1332. did_delete_self();
  1333. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  1334. fs().uncache_inode(index());
  1335. return {};
  1336. }
  1337. void Ext2FS::uncache_inode(InodeIndex index)
  1338. {
  1339. MutexLocker locker(m_lock);
  1340. m_inode_cache.remove(index);
  1341. }
  1342. ErrorOr<void> Ext2FSInode::chmod(mode_t mode)
  1343. {
  1344. MutexLocker locker(m_inode_lock);
  1345. if (m_raw_inode.i_mode == mode)
  1346. return {};
  1347. m_raw_inode.i_mode = mode;
  1348. set_metadata_dirty(true);
  1349. return {};
  1350. }
  1351. ErrorOr<void> Ext2FSInode::chown(UserID uid, GroupID gid)
  1352. {
  1353. MutexLocker locker(m_inode_lock);
  1354. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1355. return {};
  1356. m_raw_inode.i_uid = uid.value();
  1357. m_raw_inode.i_gid = gid.value();
  1358. set_metadata_dirty(true);
  1359. return {};
  1360. }
  1361. ErrorOr<void> Ext2FSInode::truncate(u64 size)
  1362. {
  1363. MutexLocker locker(m_inode_lock);
  1364. if (static_cast<u64>(m_raw_inode.i_size) == size)
  1365. return {};
  1366. TRY(resize(size));
  1367. set_metadata_dirty(true);
  1368. return {};
  1369. }
  1370. ErrorOr<int> Ext2FSInode::get_block_address(int index)
  1371. {
  1372. MutexLocker locker(m_inode_lock);
  1373. if (m_block_list.is_empty())
  1374. m_block_list = TRY(compute_block_list());
  1375. if (index < 0 || (size_t)index >= m_block_list.size())
  1376. return 0;
  1377. return m_block_list[index].value();
  1378. }
  1379. unsigned Ext2FS::total_block_count() const
  1380. {
  1381. MutexLocker locker(m_lock);
  1382. return super_block().s_blocks_count;
  1383. }
  1384. unsigned Ext2FS::free_block_count() const
  1385. {
  1386. MutexLocker locker(m_lock);
  1387. return super_block().s_free_blocks_count;
  1388. }
  1389. unsigned Ext2FS::total_inode_count() const
  1390. {
  1391. MutexLocker locker(m_lock);
  1392. return super_block().s_inodes_count;
  1393. }
  1394. unsigned Ext2FS::free_inode_count() const
  1395. {
  1396. MutexLocker locker(m_lock);
  1397. return super_block().s_free_inodes_count;
  1398. }
  1399. ErrorOr<void> Ext2FS::prepare_to_unmount()
  1400. {
  1401. MutexLocker locker(m_lock);
  1402. for (auto& it : m_inode_cache) {
  1403. if (it.value->ref_count() > 1)
  1404. return EBUSY;
  1405. }
  1406. m_inode_cache.clear();
  1407. m_root_inode = nullptr;
  1408. return {};
  1409. }
  1410. }