Ext2FileSystem.cpp 68 KB

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