Ext2FileSystem.cpp 71 KB

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