Ext2FileSystem.cpp 58 KB

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