Ext2FileSystem.cpp 57 KB

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