Ext2FileSystem.cpp 67 KB

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