Ext2FileSystem.cpp 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658
  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. klog() << "ext2fs: super block magic: " << String::format("%x", super_block.s_magic) << " (super block size: " << sizeof(ext2_super_block) << ")";
  106. }
  107. if (super_block.s_magic != EXT2_SUPER_MAGIC)
  108. return false;
  109. if constexpr (EXT2_DEBUG) {
  110. klog() << "ext2fs: " << super_block.s_inodes_count << " inodes, " << super_block.s_blocks_count << " blocks";
  111. klog() << "ext2fs: block size = " << EXT2_BLOCK_SIZE(&super_block);
  112. klog() << "ext2fs: first data block = " << super_block.s_first_data_block;
  113. klog() << "ext2fs: inodes per block = " << inodes_per_block();
  114. klog() << "ext2fs: inodes per group = " << inodes_per_group();
  115. klog() << "ext2fs: free inodes = " << super_block.s_free_inodes_count;
  116. klog() << "ext2fs: desc per block = " << EXT2_DESC_PER_BLOCK(&super_block);
  117. klog() << "ext2fs: desc 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. klog() << "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. klog() << "ext2fs: group[" << i << "] { block_bitmap: " << group.bg_block_bitmap << ", inode_bitmap: " << group.bg_inode_bitmap << ", inode_table: " << 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. u32 array[count];
  431. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)array);
  432. auto result = fs().read_block(array_block_index, &buffer, sizeof(array), 0);
  433. if (result.is_error()) {
  434. // FIXME: Stop here and propagate this error.
  435. dbgln("Ext2FS: compute_block_list_impl_internal had error: {}", result.error());
  436. }
  437. for (unsigned i = 0; i < count; ++i)
  438. callback(Ext2FS::BlockIndex(array[i]));
  439. };
  440. process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](auto block_index) {
  441. add_block(block_index);
  442. });
  443. if (!blocks_remaining)
  444. return list;
  445. process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](auto block_index) {
  446. process_block_array(block_index, [&](auto block_index2) {
  447. add_block(block_index2);
  448. });
  449. });
  450. if (!blocks_remaining)
  451. return list;
  452. process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](auto block_index) {
  453. process_block_array(block_index, [&](auto block_index2) {
  454. process_block_array(block_index2, [&](auto block_index3) {
  455. add_block(block_index3);
  456. });
  457. });
  458. });
  459. return list;
  460. }
  461. void Ext2FS::free_inode(Ext2FSInode& inode)
  462. {
  463. LOCKER(m_lock);
  464. VERIFY(inode.m_raw_inode.i_links_count == 0);
  465. dbgln_if(EXT2_DEBUG, "Ext2FS: Inode {} has no more links, time to delete!", inode.index());
  466. // Mark all blocks used by this inode as free.
  467. for (auto block_index : inode.compute_block_list_with_meta_blocks()) {
  468. VERIFY(block_index <= super_block().s_blocks_count);
  469. if (block_index.value()) {
  470. auto result = set_block_allocation_state(block_index, false);
  471. if (result.is_error()) {
  472. dbgln("Ext2FS: Failed to deallocate block {} in free_inode()", block_index);
  473. }
  474. }
  475. }
  476. // If the inode being freed is a directory, update block group directory counter.
  477. if (inode.is_directory()) {
  478. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  479. --bgd.bg_used_dirs_count;
  480. dbgln("Ext2FS: Decremented bg_used_dirs_count to {}", bgd.bg_used_dirs_count);
  481. m_block_group_descriptors_dirty = true;
  482. }
  483. // NOTE: After this point, the inode metadata is wiped.
  484. memset(&inode.m_raw_inode, 0, sizeof(ext2_inode));
  485. inode.m_raw_inode.i_dtime = kgettimeofday().to_truncated_seconds();
  486. write_ext2_inode(inode.index(), inode.m_raw_inode);
  487. // Mark the inode as free.
  488. auto result = set_inode_allocation_state(inode.index(), false);
  489. if (result.is_error()) {
  490. dbgln("Ext2FS: Failed to free inode {}", inode.index());
  491. }
  492. }
  493. void Ext2FS::flush_block_group_descriptor_table()
  494. {
  495. LOCKER(m_lock);
  496. unsigned blocks_to_write = ceil_div(m_block_group_count * sizeof(ext2_group_desc), block_size());
  497. unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  498. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)block_group_descriptors());
  499. auto result = write_blocks(first_block_of_bgdt, blocks_to_write, buffer);
  500. if (result.is_error())
  501. dbgln("Ext2FS: flush_block_group_descriptor_table had error: {}", result.error());
  502. }
  503. void Ext2FS::flush_writes()
  504. {
  505. LOCKER(m_lock);
  506. if (m_super_block_dirty) {
  507. flush_super_block();
  508. m_super_block_dirty = false;
  509. }
  510. if (m_block_group_descriptors_dirty) {
  511. flush_block_group_descriptor_table();
  512. m_block_group_descriptors_dirty = false;
  513. }
  514. for (auto& cached_bitmap : m_cached_bitmaps) {
  515. if (cached_bitmap->dirty) {
  516. auto buffer = UserOrKernelBuffer::for_kernel_buffer(cached_bitmap->buffer.data());
  517. auto result = write_block(cached_bitmap->bitmap_block_index, buffer, block_size());
  518. if (result.is_error()) {
  519. dbgln("Ext2FS: flush_writes() had error {}", result.error());
  520. }
  521. cached_bitmap->dirty = false;
  522. dbgln_if(EXT2_DEBUG, "Flushed bitmap block {}", cached_bitmap->bitmap_block_index);
  523. }
  524. }
  525. BlockBasedFS::flush_writes();
  526. // Uncache Inodes that are only kept alive by the index-to-inode lookup cache.
  527. // We don't uncache Inodes that are being watched by at least one InodeWatcher.
  528. // FIXME: It would be better to keep a capped number of Inodes around.
  529. // The problem is that they are quite heavy objects, and use a lot of heap memory
  530. // for their (child name lookup) and (block list) caches.
  531. Vector<InodeIndex> unused_inodes;
  532. for (auto& it : m_inode_cache) {
  533. if (it.value->ref_count() != 1)
  534. continue;
  535. if (it.value->has_watchers())
  536. continue;
  537. unused_inodes.append(it.key);
  538. }
  539. for (auto index : unused_inodes)
  540. uncache_inode(index);
  541. }
  542. Ext2FSInode::Ext2FSInode(Ext2FS& fs, InodeIndex index)
  543. : Inode(fs, index)
  544. {
  545. }
  546. Ext2FSInode::~Ext2FSInode()
  547. {
  548. if (m_raw_inode.i_links_count == 0)
  549. fs().free_inode(*this);
  550. }
  551. InodeMetadata Ext2FSInode::metadata() const
  552. {
  553. LOCKER(m_lock);
  554. InodeMetadata metadata;
  555. metadata.inode = identifier();
  556. metadata.size = m_raw_inode.i_size;
  557. metadata.mode = m_raw_inode.i_mode;
  558. metadata.uid = m_raw_inode.i_uid;
  559. metadata.gid = m_raw_inode.i_gid;
  560. metadata.link_count = m_raw_inode.i_links_count;
  561. metadata.atime = m_raw_inode.i_atime;
  562. metadata.ctime = m_raw_inode.i_ctime;
  563. metadata.mtime = m_raw_inode.i_mtime;
  564. metadata.dtime = m_raw_inode.i_dtime;
  565. metadata.block_size = fs().block_size();
  566. metadata.block_count = m_raw_inode.i_blocks;
  567. if (Kernel::is_character_device(m_raw_inode.i_mode) || Kernel::is_block_device(m_raw_inode.i_mode)) {
  568. unsigned dev = m_raw_inode.i_block[0];
  569. if (!dev)
  570. dev = m_raw_inode.i_block[1];
  571. metadata.major_device = (dev & 0xfff00) >> 8;
  572. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  573. }
  574. return metadata;
  575. }
  576. void Ext2FSInode::flush_metadata()
  577. {
  578. LOCKER(m_lock);
  579. dbgln_if(EXT2_DEBUG, "Ext2FS: flush_metadata for inode {}", index());
  580. fs().write_ext2_inode(index(), m_raw_inode);
  581. if (is_directory()) {
  582. // Unless we're about to go away permanently, invalidate the lookup cache.
  583. if (m_raw_inode.i_links_count != 0) {
  584. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  585. m_lookup_cache.clear();
  586. }
  587. }
  588. set_metadata_dirty(false);
  589. }
  590. RefPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  591. {
  592. LOCKER(m_lock);
  593. VERIFY(inode.fsid() == fsid());
  594. {
  595. auto it = m_inode_cache.find(inode.index());
  596. if (it != m_inode_cache.end())
  597. return (*it).value;
  598. }
  599. auto state_or_error = get_inode_allocation_state(inode.index());
  600. if (state_or_error.is_error())
  601. return {};
  602. if (!state_or_error.value()) {
  603. m_inode_cache.set(inode.index(), nullptr);
  604. return {};
  605. }
  606. BlockIndex block_index;
  607. unsigned offset;
  608. if (!find_block_containing_inode(inode.index(), block_index, offset))
  609. return {};
  610. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index()));
  611. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(&new_inode->m_raw_inode));
  612. auto result = read_block(block_index, &buffer, sizeof(ext2_inode), offset);
  613. if (result.is_error()) {
  614. // FIXME: Propagate the actual error.
  615. return nullptr;
  616. }
  617. m_inode_cache.set(inode.index(), new_inode);
  618. return new_inode;
  619. }
  620. ssize_t Ext2FSInode::read_bytes(off_t offset, ssize_t count, UserOrKernelBuffer& buffer, FileDescription* description) const
  621. {
  622. Locker inode_locker(m_lock);
  623. VERIFY(offset >= 0);
  624. if (m_raw_inode.i_size == 0)
  625. return 0;
  626. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  627. // This avoids wasting an entire block on short links. (Most links are short.)
  628. if (is_symlink() && size() < max_inline_symlink_length) {
  629. VERIFY(offset == 0);
  630. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  631. if (!buffer.write(((const u8*)m_raw_inode.i_block) + offset, (size_t)nread))
  632. return -EFAULT;
  633. return nread;
  634. }
  635. if (m_block_list.is_empty())
  636. m_block_list = compute_block_list();
  637. if (m_block_list.is_empty()) {
  638. dmesgln("Ext2FS: read_bytes: empty block list for inode {}", index());
  639. return -EIO;
  640. }
  641. bool allow_cache = !description || !description->is_direct();
  642. const int block_size = fs().block_size();
  643. size_t first_block_logical_index = offset / block_size;
  644. size_t last_block_logical_index = (offset + count) / block_size;
  645. if (last_block_logical_index >= m_block_list.size())
  646. last_block_logical_index = m_block_list.size() - 1;
  647. int offset_into_first_block = offset % block_size;
  648. ssize_t nread = 0;
  649. size_t remaining_count = min((off_t)count, (off_t)size() - offset);
  650. dbgln_if(EXT2_VERY_DEBUG, "Ext2FS: Reading up to {} bytes, {} bytes into inode {} to {}", count, offset, index(), buffer.user_or_kernel_ptr());
  651. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  652. auto block_index = m_block_list[bi];
  653. VERIFY(block_index.value());
  654. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  655. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  656. auto buffer_offset = buffer.offset(nread);
  657. int err = fs().read_block(block_index, &buffer_offset, num_bytes_to_copy, offset_into_block, allow_cache);
  658. if (err < 0) {
  659. dmesgln("Ext2FS: read_bytes: read_block({}) failed (bi: {})", block_index.value(), bi);
  660. return err;
  661. }
  662. remaining_count -= num_bytes_to_copy;
  663. nread += num_bytes_to_copy;
  664. }
  665. return nread;
  666. }
  667. KResult Ext2FSInode::resize(u64 new_size)
  668. {
  669. u64 old_size = size();
  670. if (old_size == new_size)
  671. return KSuccess;
  672. u64 block_size = fs().block_size();
  673. size_t blocks_needed_before = ceil_div(old_size, block_size);
  674. size_t blocks_needed_after = ceil_div(new_size, block_size);
  675. if constexpr (EXT2_DEBUG) {
  676. dbgln("Ext2FSInode::resize(): blocks needed before (size was {}): {}", old_size, blocks_needed_before);
  677. dbgln("Ext2FSInode::resize(): blocks needed after (size is {}): {}", new_size, blocks_needed_after);
  678. }
  679. if (blocks_needed_after > blocks_needed_before) {
  680. u32 additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  681. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  682. return ENOSPC;
  683. }
  684. Vector<Ext2FS::BlockIndex> block_list;
  685. if (!m_block_list.is_empty())
  686. block_list = m_block_list;
  687. else
  688. block_list = this->compute_block_list();
  689. if (blocks_needed_after > blocks_needed_before) {
  690. auto blocks_or_error = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  691. if (blocks_or_error.is_error())
  692. return blocks_or_error.error();
  693. block_list.append(blocks_or_error.release_value());
  694. } else if (blocks_needed_after < blocks_needed_before) {
  695. if constexpr (EXT2_DEBUG) {
  696. dbgln("Ext2FS: Shrinking inode {}. Old block list is {} entries:", index(), block_list.size());
  697. for (auto block_index : block_list) {
  698. dbgln(" # {}", block_index);
  699. }
  700. }
  701. while (block_list.size() != blocks_needed_after) {
  702. auto block_index = block_list.take_last();
  703. if (block_index.value()) {
  704. auto result = fs().set_block_allocation_state(block_index, false);
  705. if (result.is_error()) {
  706. dbgln("Ext2FS: Failed to free block {} in Ext2Inode::resize()", block_index);
  707. return result;
  708. }
  709. }
  710. }
  711. }
  712. m_block_list = move(block_list);
  713. auto result = flush_block_list();
  714. if (result.is_error())
  715. return result;
  716. m_raw_inode.i_size = new_size;
  717. set_metadata_dirty(true);
  718. if (new_size > old_size) {
  719. // If we're growing the inode, make sure we zero out all the new space.
  720. // FIXME: There are definitely more efficient ways to achieve this.
  721. size_t bytes_to_clear = new_size - old_size;
  722. size_t clear_from = old_size;
  723. u8 zero_buffer[PAGE_SIZE] {};
  724. while (bytes_to_clear) {
  725. auto nwritten = write_bytes(clear_from, min(sizeof(zero_buffer), bytes_to_clear), UserOrKernelBuffer::for_kernel_buffer(zero_buffer), nullptr);
  726. if (nwritten < 0)
  727. return KResult((ErrnoCode)-nwritten);
  728. VERIFY(nwritten != 0);
  729. bytes_to_clear -= nwritten;
  730. clear_from += nwritten;
  731. }
  732. }
  733. return KSuccess;
  734. }
  735. ssize_t Ext2FSInode::write_bytes(off_t offset, ssize_t count, const UserOrKernelBuffer& data, FileDescription* description)
  736. {
  737. VERIFY(offset >= 0);
  738. VERIFY(count >= 0);
  739. Locker inode_locker(m_lock);
  740. auto result = prepare_to_write_data();
  741. if (result.is_error())
  742. return result;
  743. if (is_symlink()) {
  744. VERIFY(offset == 0);
  745. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  746. dbgln_if(EXT2_DEBUG, "Ext2FS: write_bytes poking into i_block array for inline symlink '{}' ({} bytes)", data.copy_into_string(count), count);
  747. if (!data.read(((u8*)m_raw_inode.i_block) + offset, (size_t)count))
  748. return -EFAULT;
  749. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  750. m_raw_inode.i_size = offset + count;
  751. set_metadata_dirty(true);
  752. return count;
  753. }
  754. }
  755. bool allow_cache = !description || !description->is_direct();
  756. const size_t block_size = fs().block_size();
  757. u64 old_size = size();
  758. u64 new_size = max(static_cast<u64>(offset) + count, (u64)size());
  759. auto resize_result = resize(new_size);
  760. if (resize_result.is_error())
  761. return resize_result;
  762. if (m_block_list.is_empty())
  763. m_block_list = compute_block_list();
  764. if (m_block_list.is_empty()) {
  765. dbgln("Ext2FSInode::write_bytes(): empty block list for inode {}", index());
  766. return -EIO;
  767. }
  768. size_t first_block_logical_index = offset / block_size;
  769. size_t last_block_logical_index = (offset + count) / block_size;
  770. if (last_block_logical_index >= m_block_list.size())
  771. last_block_logical_index = m_block_list.size() - 1;
  772. size_t offset_into_first_block = offset % block_size;
  773. ssize_t nwritten = 0;
  774. size_t remaining_count = min((off_t)count, (off_t)new_size - offset);
  775. dbgln_if(EXT2_VERY_DEBUG, "Ext2FS: Writing {} bytes, {} bytes into inode {} from {}", count, offset, index(), data.user_or_kernel_ptr());
  776. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  777. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  778. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  779. dbgln_if(EXT2_DEBUG, "Ext2FS: Writing block {} (offset_into_block: {})", m_block_list[bi], offset_into_block);
  780. result = fs().write_block(m_block_list[bi], data.offset(nwritten), num_bytes_to_copy, offset_into_block, allow_cache);
  781. if (result.is_error()) {
  782. dbgln("Ext2FS: write_block({}) failed (bi: {})", m_block_list[bi], bi);
  783. return result;
  784. }
  785. remaining_count -= num_bytes_to_copy;
  786. nwritten += num_bytes_to_copy;
  787. }
  788. 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());
  789. if (old_size != new_size)
  790. inode_size_changed(old_size, new_size);
  791. inode_contents_changed(offset, count, data);
  792. return nwritten;
  793. }
  794. u8 Ext2FS::internal_file_type_to_directory_entry_type(const DirectoryEntryView& entry) const
  795. {
  796. switch (entry.file_type) {
  797. case EXT2_FT_REG_FILE:
  798. return DT_REG;
  799. case EXT2_FT_DIR:
  800. return DT_DIR;
  801. case EXT2_FT_CHRDEV:
  802. return DT_CHR;
  803. case EXT2_FT_BLKDEV:
  804. return DT_BLK;
  805. case EXT2_FT_FIFO:
  806. return DT_FIFO;
  807. case EXT2_FT_SOCK:
  808. return DT_SOCK;
  809. case EXT2_FT_SYMLINK:
  810. return DT_LNK;
  811. default:
  812. return DT_UNKNOWN;
  813. }
  814. }
  815. KResult Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntryView&)> callback) const
  816. {
  817. LOCKER(m_lock);
  818. VERIFY(is_directory());
  819. dbgln_if(EXT2_VERY_DEBUG, "Ext2FS: Traversing as directory: {}", index());
  820. auto buffer_or = read_entire();
  821. if (buffer_or.is_error())
  822. return buffer_or.error();
  823. auto& buffer = *buffer_or.value();
  824. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.data());
  825. while (entry < buffer.end_pointer()) {
  826. if (entry->inode != 0) {
  827. 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));
  828. if (!callback({ { entry->name, entry->name_len }, { fsid(), entry->inode }, entry->file_type }))
  829. break;
  830. }
  831. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  832. }
  833. return KSuccess;
  834. }
  835. KResult Ext2FSInode::write_directory(const Vector<Ext2FSDirectoryEntry>& entries)
  836. {
  837. LOCKER(m_lock);
  838. int directory_size = 0;
  839. for (auto& entry : entries)
  840. directory_size += EXT2_DIR_REC_LEN(entry.name.length());
  841. auto block_size = fs().block_size();
  842. int blocks_needed = ceil_div(static_cast<size_t>(directory_size), block_size);
  843. int occupied_size = blocks_needed * block_size;
  844. dbgln_if(EXT2_DEBUG, "Ext2FS: New directory inode {} contents to write (size {}, occupied {}):", index(), directory_size, occupied_size);
  845. auto directory_data = ByteBuffer::create_uninitialized(occupied_size);
  846. OutputMemoryStream stream { directory_data };
  847. for (size_t i = 0; i < entries.size(); ++i) {
  848. auto& entry = entries[i];
  849. int record_length = EXT2_DIR_REC_LEN(entry.name.length());
  850. if (i == entries.size() - 1)
  851. record_length += occupied_size - directory_size;
  852. 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);
  853. stream << u32(entry.inode_index.value());
  854. stream << u16(record_length);
  855. stream << u8(entry.name.length());
  856. stream << u8(entry.file_type);
  857. stream << entry.name.bytes();
  858. int padding = record_length - entry.name.length() - 8;
  859. for (int j = 0; j < padding; ++j)
  860. stream << u8(0);
  861. }
  862. stream.fill_to_end(0);
  863. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  864. ssize_t nwritten = write_bytes(0, stream.size(), buffer, nullptr);
  865. if (nwritten < 0)
  866. return KResult((ErrnoCode)-nwritten);
  867. set_metadata_dirty(true);
  868. if (static_cast<size_t>(nwritten) != directory_data.size())
  869. return EIO;
  870. return KSuccess;
  871. }
  872. KResultOr<NonnullRefPtr<Inode>> Ext2FSInode::create_child(const String& name, mode_t mode, dev_t dev, uid_t uid, gid_t gid)
  873. {
  874. if (::is_directory(mode))
  875. return fs().create_directory(*this, name, mode, uid, gid);
  876. return fs().create_inode(*this, name, mode, dev, uid, gid);
  877. }
  878. KResult Ext2FSInode::add_child(Inode& child, const StringView& name, mode_t mode)
  879. {
  880. LOCKER(m_lock);
  881. VERIFY(is_directory());
  882. if (name.length() > EXT2_NAME_LEN)
  883. return ENAMETOOLONG;
  884. dbgln_if(EXT2_DEBUG, "Ext2FSInode::add_child: Adding inode {} with name '{}' and mode {:o} to directory {}", child.index(), name, mode, index());
  885. Vector<Ext2FSDirectoryEntry> entries;
  886. bool name_already_exists = false;
  887. KResult result = traverse_as_directory([&](auto& entry) {
  888. if (name == entry.name) {
  889. name_already_exists = true;
  890. return false;
  891. }
  892. entries.append({ entry.name, entry.inode.index(), entry.file_type });
  893. return true;
  894. });
  895. if (result.is_error())
  896. return result;
  897. if (name_already_exists) {
  898. dbgln("Ext2FSInode::add_child: Name '{}' already exists in inode {}", name, index());
  899. return EEXIST;
  900. }
  901. result = child.increment_link_count();
  902. if (result.is_error())
  903. return result;
  904. entries.empend(name, child.index(), to_ext2_file_type(mode));
  905. result = write_directory(entries);
  906. if (result.is_error())
  907. return result;
  908. m_lookup_cache.set(name, child.index());
  909. did_add_child(child.identifier());
  910. return KSuccess;
  911. }
  912. KResult Ext2FSInode::remove_child(const StringView& name)
  913. {
  914. LOCKER(m_lock);
  915. dbgln_if(EXT2_DEBUG, "Ext2FSInode::remove_child('{}') in inode {}", name, index());
  916. VERIFY(is_directory());
  917. auto it = m_lookup_cache.find(name);
  918. if (it == m_lookup_cache.end())
  919. return ENOENT;
  920. auto child_inode_index = (*it).value;
  921. InodeIdentifier child_id { fsid(), child_inode_index };
  922. dbgln_if(EXT2_DEBUG, "Ext2FSInode::remove_child(): Removing '{}' in directory {}", name, index());
  923. Vector<Ext2FSDirectoryEntry> entries;
  924. KResult result = traverse_as_directory([&](auto& entry) {
  925. if (name != entry.name)
  926. entries.append({ entry.name, entry.inode.index(), entry.file_type });
  927. return true;
  928. });
  929. if (result.is_error())
  930. return result;
  931. result = write_directory(entries);
  932. if (result.is_error())
  933. return result;
  934. m_lookup_cache.remove(name);
  935. auto child_inode = fs().get_inode(child_id);
  936. result = child_inode->decrement_link_count();
  937. if (result.is_error())
  938. return result;
  939. did_remove_child(child_id);
  940. return KSuccess;
  941. }
  942. unsigned Ext2FS::inodes_per_block() const
  943. {
  944. return EXT2_INODES_PER_BLOCK(&super_block());
  945. }
  946. unsigned Ext2FS::inodes_per_group() const
  947. {
  948. return EXT2_INODES_PER_GROUP(&super_block());
  949. }
  950. unsigned Ext2FS::inode_size() const
  951. {
  952. return EXT2_INODE_SIZE(&super_block());
  953. }
  954. unsigned Ext2FS::blocks_per_group() const
  955. {
  956. return EXT2_BLOCKS_PER_GROUP(&super_block());
  957. }
  958. bool Ext2FS::write_ext2_inode(InodeIndex inode, const ext2_inode& e2inode)
  959. {
  960. BlockIndex block_index;
  961. unsigned offset;
  962. if (!find_block_containing_inode(inode, block_index, offset))
  963. return false;
  964. auto buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((const u8*)&e2inode));
  965. return write_block(block_index, buffer, inode_size(), offset) >= 0;
  966. }
  967. auto Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count) -> KResultOr<Vector<BlockIndex>>
  968. {
  969. LOCKER(m_lock);
  970. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_blocks(preferred group: {}, count {})", preferred_group_index, count);
  971. if (count == 0)
  972. return Vector<BlockIndex> {};
  973. Vector<BlockIndex> blocks;
  974. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_blocks:");
  975. blocks.ensure_capacity(count);
  976. auto group_index = preferred_group_index;
  977. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  978. group_index = 1;
  979. }
  980. while (blocks.size() < count) {
  981. bool found_a_group = false;
  982. if (group_descriptor(group_index).bg_free_blocks_count) {
  983. found_a_group = true;
  984. } else {
  985. if (group_index == preferred_group_index)
  986. group_index = 1;
  987. for (; group_index <= m_block_group_count; group_index = GroupIndex { group_index.value() + 1 }) {
  988. if (group_descriptor(group_index).bg_free_blocks_count) {
  989. found_a_group = true;
  990. break;
  991. }
  992. }
  993. }
  994. VERIFY(found_a_group);
  995. auto& bgd = group_descriptor(group_index);
  996. auto cached_bitmap_or_error = get_bitmap_block(bgd.bg_block_bitmap);
  997. if (cached_bitmap_or_error.is_error())
  998. return cached_bitmap_or_error.error();
  999. auto& cached_bitmap = *cached_bitmap_or_error.value();
  1000. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  1001. auto block_bitmap = cached_bitmap.bitmap(blocks_in_group);
  1002. BlockIndex first_block_in_group = (group_index.value() - 1) * blocks_per_group() + first_block_index().value();
  1003. size_t free_region_size = 0;
  1004. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  1005. VERIFY(first_unset_bit_index.has_value());
  1006. dbgln_if(EXT2_DEBUG, "Ext2FS: allocating free region of size: {} [{}]", free_region_size, group_index);
  1007. for (size_t i = 0; i < free_region_size; ++i) {
  1008. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group.value();
  1009. auto result = set_block_allocation_state(block_index, true);
  1010. if (result.is_error()) {
  1011. dbgln("Ext2FS: Failed to allocate block {} in allocate_blocks()", block_index);
  1012. return result;
  1013. }
  1014. blocks.unchecked_append(block_index);
  1015. dbgln_if(EXT2_DEBUG, " allocated > {}", block_index);
  1016. }
  1017. }
  1018. VERIFY(blocks.size() == count);
  1019. return blocks;
  1020. }
  1021. KResultOr<InodeIndex> Ext2FS::allocate_inode(GroupIndex preferred_group)
  1022. {
  1023. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode(preferred_group: {})", preferred_group);
  1024. LOCKER(m_lock);
  1025. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  1026. // In those cases we should just spread it across multiple groups.
  1027. auto is_suitable_group = [this](auto group_index) {
  1028. auto& bgd = group_descriptor(group_index);
  1029. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= 1;
  1030. };
  1031. GroupIndex group_index;
  1032. if (preferred_group.value() && is_suitable_group(preferred_group)) {
  1033. group_index = preferred_group;
  1034. } else {
  1035. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  1036. if (is_suitable_group(i)) {
  1037. group_index = i;
  1038. break;
  1039. }
  1040. }
  1041. }
  1042. if (!group_index) {
  1043. dmesgln("Ext2FS: allocate_inode: no suitable group found for new inode");
  1044. return ENOSPC;
  1045. }
  1046. dbgln_if(EXT2_DEBUG, "Ext2FS: allocate_inode: found suitable group [{}] for new inode :^)", group_index);
  1047. auto& bgd = group_descriptor(group_index);
  1048. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  1049. InodeIndex first_inode_in_group = (group_index.value() - 1) * inodes_per_group() + 1;
  1050. auto cached_bitmap_or_error = get_bitmap_block(bgd.bg_inode_bitmap);
  1051. if (cached_bitmap_or_error.is_error())
  1052. return cached_bitmap_or_error.error();
  1053. auto& cached_bitmap = *cached_bitmap_or_error.value();
  1054. auto inode_bitmap = cached_bitmap.bitmap(inodes_in_group);
  1055. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  1056. if (inode_bitmap.get(i))
  1057. continue;
  1058. inode_bitmap.set(i, true);
  1059. auto inode_index = InodeIndex(first_inode_in_group.value() + i);
  1060. cached_bitmap.dirty = true;
  1061. m_super_block.s_free_inodes_count--;
  1062. m_super_block_dirty = true;
  1063. const_cast<ext2_group_desc&>(bgd).bg_free_inodes_count--;
  1064. m_block_group_descriptors_dirty = true;
  1065. // In case the inode cache had this cached as "non-existent", uncache that info.
  1066. m_inode_cache.remove(inode_index.value());
  1067. return inode_index;
  1068. }
  1069. dmesgln("Ext2FS: allocate_inode found no available inode, despite bgd claiming there are inodes :(");
  1070. return EIO;
  1071. }
  1072. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  1073. {
  1074. if (!block_index)
  1075. return 0;
  1076. return (block_index.value() - 1) / blocks_per_group() + 1;
  1077. }
  1078. auto Ext2FS::group_index_from_inode(InodeIndex inode) const -> GroupIndex
  1079. {
  1080. if (!inode)
  1081. return 0;
  1082. return (inode.value() - 1) / inodes_per_group() + 1;
  1083. }
  1084. KResultOr<bool> Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1085. {
  1086. LOCKER(m_lock);
  1087. if (index == 0)
  1088. return EINVAL;
  1089. auto group_index = group_index_from_inode(index);
  1090. auto& bgd = group_descriptor(group_index);
  1091. unsigned index_in_group = index.value() - ((group_index.value() - 1) * inodes_per_group());
  1092. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1093. auto cached_bitmap_or_error = const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap);
  1094. if (cached_bitmap_or_error.is_error())
  1095. return cached_bitmap_or_error.error();
  1096. return cached_bitmap_or_error.value()->bitmap(inodes_per_group()).get(bit_index);
  1097. }
  1098. KResult Ext2FS::update_bitmap_block(BlockIndex bitmap_block, size_t bit_index, bool new_state, u32& super_block_counter, u16& group_descriptor_counter)
  1099. {
  1100. auto cached_bitmap_or_error = get_bitmap_block(bitmap_block);
  1101. if (cached_bitmap_or_error.is_error())
  1102. return cached_bitmap_or_error.error();
  1103. auto& cached_bitmap = *cached_bitmap_or_error.value();
  1104. bool current_state = cached_bitmap.bitmap(blocks_per_group()).get(bit_index);
  1105. if (current_state == new_state) {
  1106. dbgln("Ext2FS: Bit {} in bitmap block {} had unexpected state {}", bit_index, bitmap_block, current_state);
  1107. return EIO;
  1108. }
  1109. cached_bitmap.bitmap(blocks_per_group()).set(bit_index, new_state);
  1110. cached_bitmap.dirty = true;
  1111. if (new_state) {
  1112. --super_block_counter;
  1113. --group_descriptor_counter;
  1114. } else {
  1115. ++super_block_counter;
  1116. ++group_descriptor_counter;
  1117. }
  1118. m_super_block_dirty = true;
  1119. m_block_group_descriptors_dirty = true;
  1120. return KSuccess;
  1121. }
  1122. KResult Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1123. {
  1124. LOCKER(m_lock);
  1125. auto group_index = group_index_from_inode(inode_index);
  1126. unsigned index_in_group = inode_index.value() - ((group_index.value() - 1) * inodes_per_group());
  1127. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1128. dbgln_if(EXT2_DEBUG, "Ext2FS: set_inode_allocation_state: Inode {} -> {}", inode_index, new_state);
  1129. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1130. return update_bitmap_block(bgd.bg_inode_bitmap, bit_index, new_state, m_super_block.s_free_inodes_count, bgd.bg_free_inodes_count);
  1131. }
  1132. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1133. {
  1134. return block_size() == 1024 ? 1 : 0;
  1135. }
  1136. KResultOr<Ext2FS::CachedBitmap*> Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1137. {
  1138. for (auto& cached_bitmap : m_cached_bitmaps) {
  1139. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1140. return cached_bitmap;
  1141. }
  1142. auto block = KBuffer::create_with_size(block_size(), Region::Access::Read | Region::Access::Write, "Ext2FS: Cached bitmap block");
  1143. auto buffer = UserOrKernelBuffer::for_kernel_buffer(block.data());
  1144. auto result = read_block(bitmap_block_index, &buffer, block_size());
  1145. if (result.is_error()) {
  1146. dbgln("Ext2FS: Failed to load bitmap block {}", bitmap_block_index);
  1147. return result;
  1148. }
  1149. m_cached_bitmaps.append(make<CachedBitmap>(bitmap_block_index, move(block)));
  1150. return m_cached_bitmaps.last();
  1151. }
  1152. KResult Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1153. {
  1154. VERIFY(block_index != 0);
  1155. LOCKER(m_lock);
  1156. auto group_index = group_index_from_block_index(block_index);
  1157. unsigned index_in_group = (block_index.value() - first_block_index().value()) - ((group_index.value() - 1) * blocks_per_group());
  1158. unsigned bit_index = index_in_group % blocks_per_group();
  1159. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index));
  1160. dbgln_if(EXT2_DEBUG, "Ext2FS: Block {} state -> {} (in bitmap block {})", block_index, new_state, bgd.bg_block_bitmap);
  1161. return update_bitmap_block(bgd.bg_block_bitmap, bit_index, new_state, m_super_block.s_free_blocks_count, bgd.bg_free_blocks_count);
  1162. }
  1163. KResult Ext2FS::create_directory(Ext2FSInode& parent_inode, const String& name, mode_t mode, uid_t uid, gid_t gid)
  1164. {
  1165. LOCKER(m_lock);
  1166. VERIFY(is_directory(mode));
  1167. auto inode_or_error = create_inode(parent_inode, name, mode, 0, uid, gid);
  1168. if (inode_or_error.is_error())
  1169. return inode_or_error.error();
  1170. auto& inode = inode_or_error.value();
  1171. dbgln_if(EXT2_DEBUG, "Ext2FS: create_directory: created new directory named '{} with inode {}", name, inode->index());
  1172. Vector<Ext2FSDirectoryEntry> entries;
  1173. entries.empend(".", inode->index(), static_cast<u8>(EXT2_FT_DIR));
  1174. entries.empend("..", parent_inode.index(), static_cast<u8>(EXT2_FT_DIR));
  1175. auto result = static_cast<Ext2FSInode&>(*inode).write_directory(entries);
  1176. if (result.is_error())
  1177. return result;
  1178. result = parent_inode.increment_link_count();
  1179. if (result.is_error())
  1180. return result;
  1181. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1182. ++bgd.bg_used_dirs_count;
  1183. m_block_group_descriptors_dirty = true;
  1184. return KSuccess;
  1185. }
  1186. KResultOr<NonnullRefPtr<Inode>> Ext2FS::create_inode(Ext2FSInode& parent_inode, const String& name, mode_t mode, dev_t dev, uid_t uid, gid_t gid)
  1187. {
  1188. if (name.length() > EXT2_NAME_LEN)
  1189. return ENAMETOOLONG;
  1190. if (parent_inode.m_raw_inode.i_links_count == 0)
  1191. return ENOENT;
  1192. ext2_inode e2inode {};
  1193. auto now = kgettimeofday().to_truncated_seconds();
  1194. e2inode.i_mode = mode;
  1195. e2inode.i_uid = uid;
  1196. e2inode.i_gid = gid;
  1197. e2inode.i_size = 0;
  1198. e2inode.i_atime = now;
  1199. e2inode.i_ctime = now;
  1200. e2inode.i_mtime = now;
  1201. e2inode.i_dtime = 0;
  1202. e2inode.i_flags = 0;
  1203. // For directories, add +1 link count for the "." entry in self.
  1204. e2inode.i_links_count = is_directory(mode);
  1205. if (is_character_device(mode))
  1206. e2inode.i_block[0] = dev;
  1207. else if (is_block_device(mode))
  1208. e2inode.i_block[1] = dev;
  1209. auto inode_id = allocate_inode();
  1210. if (inode_id.is_error())
  1211. return inode_id.error();
  1212. dbgln_if(EXT2_DEBUG, "Ext2FS: writing initial metadata for inode {}", inode_id.value());
  1213. auto success = write_ext2_inode(inode_id.value(), e2inode);
  1214. VERIFY(success);
  1215. auto new_inode = get_inode({ fsid(), inode_id.value() });
  1216. VERIFY(new_inode);
  1217. dbgln_if(EXT2_DEBUG, "Ext2FS: Adding inode '{}' (mode {:o}) to parent directory {}", name, mode, parent_inode.index());
  1218. auto result = parent_inode.add_child(*new_inode, name, mode);
  1219. if (result.is_error())
  1220. return result;
  1221. return new_inode.release_nonnull();
  1222. }
  1223. bool Ext2FSInode::populate_lookup_cache() const
  1224. {
  1225. LOCKER(m_lock);
  1226. if (!m_lookup_cache.is_empty())
  1227. return true;
  1228. HashMap<String, InodeIndex> children;
  1229. KResult result = traverse_as_directory([&children](auto& entry) {
  1230. children.set(entry.name, entry.inode.index());
  1231. return true;
  1232. });
  1233. if (!result.is_success())
  1234. return false;
  1235. if (!m_lookup_cache.is_empty())
  1236. return false;
  1237. m_lookup_cache = move(children);
  1238. return true;
  1239. }
  1240. RefPtr<Inode> Ext2FSInode::lookup(StringView name)
  1241. {
  1242. VERIFY(is_directory());
  1243. if (!populate_lookup_cache())
  1244. return {};
  1245. LOCKER(m_lock);
  1246. auto it = m_lookup_cache.find(name.hash(), [&](auto& entry) { return entry.key == name; });
  1247. if (it != m_lookup_cache.end())
  1248. return fs().get_inode({ fsid(), (*it).value });
  1249. return {};
  1250. }
  1251. void Ext2FSInode::one_ref_left()
  1252. {
  1253. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1254. }
  1255. int Ext2FSInode::set_atime(time_t t)
  1256. {
  1257. LOCKER(m_lock);
  1258. if (fs().is_readonly())
  1259. return -EROFS;
  1260. m_raw_inode.i_atime = t;
  1261. set_metadata_dirty(true);
  1262. return 0;
  1263. }
  1264. int Ext2FSInode::set_ctime(time_t t)
  1265. {
  1266. LOCKER(m_lock);
  1267. if (fs().is_readonly())
  1268. return -EROFS;
  1269. m_raw_inode.i_ctime = t;
  1270. set_metadata_dirty(true);
  1271. return 0;
  1272. }
  1273. int Ext2FSInode::set_mtime(time_t t)
  1274. {
  1275. LOCKER(m_lock);
  1276. if (fs().is_readonly())
  1277. return -EROFS;
  1278. m_raw_inode.i_mtime = t;
  1279. set_metadata_dirty(true);
  1280. return 0;
  1281. }
  1282. KResult Ext2FSInode::increment_link_count()
  1283. {
  1284. LOCKER(m_lock);
  1285. if (fs().is_readonly())
  1286. return EROFS;
  1287. if (m_raw_inode.i_links_count == max_link_count)
  1288. return EMLINK;
  1289. ++m_raw_inode.i_links_count;
  1290. set_metadata_dirty(true);
  1291. return KSuccess;
  1292. }
  1293. KResult Ext2FSInode::decrement_link_count()
  1294. {
  1295. LOCKER(m_lock);
  1296. if (fs().is_readonly())
  1297. return EROFS;
  1298. VERIFY(m_raw_inode.i_links_count);
  1299. --m_raw_inode.i_links_count;
  1300. if (ref_count() == 1 && m_raw_inode.i_links_count == 0)
  1301. fs().uncache_inode(index());
  1302. set_metadata_dirty(true);
  1303. return KSuccess;
  1304. }
  1305. void Ext2FS::uncache_inode(InodeIndex index)
  1306. {
  1307. LOCKER(m_lock);
  1308. m_inode_cache.remove(index);
  1309. }
  1310. KResultOr<size_t> Ext2FSInode::directory_entry_count() const
  1311. {
  1312. VERIFY(is_directory());
  1313. LOCKER(m_lock);
  1314. populate_lookup_cache();
  1315. return m_lookup_cache.size();
  1316. }
  1317. KResult Ext2FSInode::chmod(mode_t mode)
  1318. {
  1319. LOCKER(m_lock);
  1320. if (m_raw_inode.i_mode == mode)
  1321. return KSuccess;
  1322. m_raw_inode.i_mode = mode;
  1323. set_metadata_dirty(true);
  1324. return KSuccess;
  1325. }
  1326. KResult Ext2FSInode::chown(uid_t uid, gid_t gid)
  1327. {
  1328. LOCKER(m_lock);
  1329. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1330. return KSuccess;
  1331. m_raw_inode.i_uid = uid;
  1332. m_raw_inode.i_gid = gid;
  1333. set_metadata_dirty(true);
  1334. return KSuccess;
  1335. }
  1336. KResult Ext2FSInode::truncate(u64 size)
  1337. {
  1338. LOCKER(m_lock);
  1339. if (static_cast<u64>(m_raw_inode.i_size) == size)
  1340. return KSuccess;
  1341. auto result = resize(size);
  1342. if (result.is_error())
  1343. return result;
  1344. set_metadata_dirty(true);
  1345. return KSuccess;
  1346. }
  1347. KResultOr<int> Ext2FSInode::get_block_address(int index)
  1348. {
  1349. LOCKER(m_lock);
  1350. if (m_block_list.is_empty())
  1351. m_block_list = compute_block_list();
  1352. if (index < 0 || (size_t)index >= m_block_list.size())
  1353. return 0;
  1354. return m_block_list[index].value();
  1355. }
  1356. unsigned Ext2FS::total_block_count() const
  1357. {
  1358. LOCKER(m_lock);
  1359. return super_block().s_blocks_count;
  1360. }
  1361. unsigned Ext2FS::free_block_count() const
  1362. {
  1363. LOCKER(m_lock);
  1364. return super_block().s_free_blocks_count;
  1365. }
  1366. unsigned Ext2FS::total_inode_count() const
  1367. {
  1368. LOCKER(m_lock);
  1369. return super_block().s_inodes_count;
  1370. }
  1371. unsigned Ext2FS::free_inode_count() const
  1372. {
  1373. LOCKER(m_lock);
  1374. return super_block().s_free_inodes_count;
  1375. }
  1376. KResult Ext2FS::prepare_to_unmount() const
  1377. {
  1378. LOCKER(m_lock);
  1379. for (auto& it : m_inode_cache) {
  1380. if (it.value->ref_count() > 1)
  1381. return EBUSY;
  1382. }
  1383. m_inode_cache.clear();
  1384. return KSuccess;
  1385. }
  1386. }