Ext2FileSystem.cpp 58 KB

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