Ext2FileSystem.cpp 68 KB

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