Ext2FileSystem.cpp 68 KB

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