Ext2FileSystem.cpp 68 KB

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