Ext2FileSystem.cpp 58 KB

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