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. KResult 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 KSuccess;
  206. }
  207. // NOTE: There is a mismatch between i_blocks and blocks.size() since i_blocks includes meta blocks and blocks.size() does not.
  208. auto old_block_count = ceil_div(static_cast<size_t>(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 KSuccess;
  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. auto result = write_block(e2inode.i_block[EXT2_IND_BLOCK], buffer, stream.size());
  267. if (result.is_error())
  268. return result;
  269. }
  270. if (!remaining_blocks)
  271. return KSuccess;
  272. bool dind_block_dirty = false;
  273. bool dind_block_new = !e2inode.i_block[EXT2_DIND_BLOCK];
  274. if (dind_block_new) {
  275. BlockIndex new_dindirect_block = new_meta_blocks.take_last();
  276. if (e2inode.i_block[EXT2_DIND_BLOCK] != new_dindirect_block)
  277. inode_dirty = true;
  278. e2inode.i_block[EXT2_DIND_BLOCK] = new_dindirect_block;
  279. if (inode_dirty) {
  280. #ifdef EXT2_DEBUG
  281. dbgln("Ext2FS: Adding the doubly-indirect block to i_block array of inode {}", inode_index);
  282. #endif
  283. write_ext2_inode(inode_index, e2inode);
  284. inode_dirty = false;
  285. }
  286. }
  287. if (old_shape.doubly_indirect_blocks == new_shape.doubly_indirect_blocks) {
  288. // No need to update the doubly indirect block data.
  289. remaining_blocks -= new_shape.doubly_indirect_blocks;
  290. output_block_index += new_shape.doubly_indirect_blocks;
  291. } else {
  292. unsigned indirect_block_count = new_shape.doubly_indirect_blocks / entries_per_block;
  293. if ((new_shape.doubly_indirect_blocks % entries_per_block) != 0)
  294. indirect_block_count++;
  295. auto dind_block_contents = ByteBuffer::create_uninitialized(block_size());
  296. if (dind_block_new) {
  297. memset(dind_block_contents.data(), 0, dind_block_contents.size());
  298. dind_block_dirty = true;
  299. } else {
  300. auto buffer = UserOrKernelBuffer::for_kernel_buffer(dind_block_contents.data());
  301. auto result = read_block(e2inode.i_block[EXT2_DIND_BLOCK], &buffer, block_size());
  302. if (result.is_error()) {
  303. dbgln("Ext2FS: write_block_list_for_inode had error: {}", result.error());
  304. return result;
  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. dbgln("Ext2FS: write_block_list_for_inode had error: {}", result.error());
  327. return result;
  328. }
  329. }
  330. auto* ind_block_as_pointers = (unsigned*)ind_block_contents.data();
  331. unsigned entries_to_write = new_shape.doubly_indirect_blocks - (i * entries_per_block);
  332. if (entries_to_write > entries_per_block)
  333. entries_to_write = entries_per_block;
  334. ASSERT(entries_to_write <= entries_per_block);
  335. for (unsigned j = 0; j < entries_to_write; ++j) {
  336. BlockIndex output_block = blocks[output_block_index++];
  337. if (ind_block_as_pointers[j] != output_block) {
  338. ind_block_as_pointers[j] = output_block;
  339. ind_block_dirty = true;
  340. }
  341. --remaining_blocks;
  342. }
  343. for (unsigned j = entries_to_write; j < entries_per_block; ++j) {
  344. if (ind_block_as_pointers[j] != 0) {
  345. ind_block_as_pointers[j] = 0;
  346. ind_block_dirty = true;
  347. }
  348. }
  349. if (ind_block_dirty) {
  350. auto buffer = UserOrKernelBuffer::for_kernel_buffer(ind_block_contents.data());
  351. int err = write_block(indirect_block_index, buffer, block_size());
  352. ASSERT(err >= 0);
  353. }
  354. }
  355. for (unsigned i = indirect_block_count; i < entries_per_block; ++i) {
  356. if (dind_block_as_pointers[i] != 0) {
  357. dind_block_as_pointers[i] = 0;
  358. dind_block_dirty = true;
  359. }
  360. }
  361. if (dind_block_dirty) {
  362. auto buffer = UserOrKernelBuffer::for_kernel_buffer(dind_block_contents.data());
  363. int err = write_block(e2inode.i_block[EXT2_DIND_BLOCK], buffer, block_size());
  364. ASSERT(err >= 0);
  365. }
  366. }
  367. if (!remaining_blocks)
  368. return KSuccess;
  369. // FIXME: Implement!
  370. dbgln("we don't know how to write tind ext2fs blocks yet!");
  371. ASSERT_NOT_REACHED();
  372. }
  373. Vector<Ext2FS::BlockIndex> Ext2FS::block_list_for_inode(const ext2_inode& e2inode, bool include_block_list_blocks) const
  374. {
  375. auto block_list = block_list_for_inode_impl(e2inode, include_block_list_blocks);
  376. while (!block_list.is_empty() && block_list.last() == 0)
  377. block_list.take_last();
  378. return block_list;
  379. }
  380. Vector<Ext2FS::BlockIndex> Ext2FS::block_list_for_inode_impl(const ext2_inode& e2inode, bool include_block_list_blocks) const
  381. {
  382. LOCKER(m_lock);
  383. unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block());
  384. unsigned block_count = ceil_div(static_cast<size_t>(e2inode.i_size), block_size());
  385. // If we are handling a symbolic link, the path is stored in the 60 bytes in
  386. // the inode that are used for the 12 direct and 3 indirect block pointers,
  387. // If the path is longer than 60 characters, a block is allocated, and the
  388. // block contains the destination path. The file size corresponds to the
  389. // path length of the destination.
  390. if (is_symlink(e2inode.i_mode) && e2inode.i_blocks == 0)
  391. block_count = 0;
  392. #ifdef EXT2_DEBUG
  393. dbgln("Ext2FS::block_list_for_inode(): i_size={}, i_blocks={}, block_count={}", e2inode.i_size, e2inode.i_blocks, block_count);
  394. #endif
  395. unsigned blocks_remaining = block_count;
  396. if (include_block_list_blocks) {
  397. auto shape = compute_block_list_shape(block_count);
  398. blocks_remaining += shape.meta_blocks;
  399. }
  400. Vector<BlockIndex> list;
  401. auto add_block = [&](BlockIndex bi) {
  402. if (blocks_remaining) {
  403. list.append(bi);
  404. --blocks_remaining;
  405. }
  406. };
  407. if (include_block_list_blocks) {
  408. // This seems like an excessive over-estimate but w/e.
  409. list.ensure_capacity(blocks_remaining * 2);
  410. } else {
  411. list.ensure_capacity(blocks_remaining);
  412. }
  413. unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS);
  414. for (unsigned i = 0; i < direct_count; ++i) {
  415. auto block_index = e2inode.i_block[i];
  416. add_block(block_index);
  417. }
  418. if (!blocks_remaining)
  419. return list;
  420. // Don't need to make copy of add_block, since this capture will only
  421. // be called before block_list_for_inode_impl finishes.
  422. auto process_block_array = [&](unsigned array_block_index, auto&& callback) {
  423. if (include_block_list_blocks)
  424. add_block(array_block_index);
  425. auto count = min(blocks_remaining, entries_per_block);
  426. u32 array[count];
  427. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)array);
  428. auto result = read_block(array_block_index, &buffer, sizeof(array), 0);
  429. if (result.is_error()) {
  430. // FIXME: Stop here and propagate this error.
  431. dbgln("Ext2FS: block_list_for_inode_impl had error: {}", result.error());
  432. }
  433. for (BlockIndex i = 0; i < count; ++i)
  434. callback(array[i]);
  435. };
  436. process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](unsigned block_index) {
  437. add_block(block_index);
  438. });
  439. if (!blocks_remaining)
  440. return list;
  441. process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](unsigned block_index) {
  442. process_block_array(block_index, [&](unsigned block_index2) {
  443. add_block(block_index2);
  444. });
  445. });
  446. if (!blocks_remaining)
  447. return list;
  448. process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](unsigned block_index) {
  449. process_block_array(block_index, [&](unsigned block_index2) {
  450. process_block_array(block_index2, [&](unsigned block_index3) {
  451. add_block(block_index3);
  452. });
  453. });
  454. });
  455. return list;
  456. }
  457. void Ext2FS::free_inode(Ext2FSInode& inode)
  458. {
  459. LOCKER(m_lock);
  460. ASSERT(inode.m_raw_inode.i_links_count == 0);
  461. #ifdef EXT2_DEBUG
  462. dbgln("Ext2FS: Inode {} has no more links, time to delete!", inode.index());
  463. #endif
  464. // Mark all blocks used by this inode as free.
  465. auto block_list = block_list_for_inode(inode.m_raw_inode, true);
  466. for (auto block_index : block_list) {
  467. ASSERT(block_index <= super_block().s_blocks_count);
  468. if (block_index)
  469. set_block_allocation_state(block_index, false);
  470. }
  471. // If the inode being freed is a directory, update block group directory counter.
  472. if (inode.is_directory()) {
  473. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index())));
  474. --bgd.bg_used_dirs_count;
  475. dbgln("Ext2FS: Decremented bg_used_dirs_count to {}", bgd.bg_used_dirs_count);
  476. m_block_group_descriptors_dirty = true;
  477. }
  478. // NOTE: After this point, the inode metadata is wiped.
  479. memset(&inode.m_raw_inode, 0, sizeof(ext2_inode));
  480. inode.m_raw_inode.i_dtime = kgettimeofday().tv_sec;
  481. write_ext2_inode(inode.index(), inode.m_raw_inode);
  482. // Mark the inode as free.
  483. set_inode_allocation_state(inode.index(), false);
  484. }
  485. void Ext2FS::flush_block_group_descriptor_table()
  486. {
  487. LOCKER(m_lock);
  488. unsigned blocks_to_write = ceil_div(m_block_group_count * sizeof(ext2_group_desc), block_size());
  489. unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1;
  490. auto buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)block_group_descriptors());
  491. auto result = write_blocks(first_block_of_bgdt, blocks_to_write, buffer);
  492. if (result.is_error())
  493. dbgln("Ext2FS: flush_block_group_descriptor_table had error: {}", result.error());
  494. }
  495. void Ext2FS::flush_writes()
  496. {
  497. LOCKER(m_lock);
  498. if (m_super_block_dirty) {
  499. flush_super_block();
  500. m_super_block_dirty = false;
  501. }
  502. if (m_block_group_descriptors_dirty) {
  503. flush_block_group_descriptor_table();
  504. m_block_group_descriptors_dirty = false;
  505. }
  506. for (auto& cached_bitmap : m_cached_bitmaps) {
  507. if (cached_bitmap->dirty) {
  508. auto buffer = UserOrKernelBuffer::for_kernel_buffer(cached_bitmap->buffer.data());
  509. auto result = write_block(cached_bitmap->bitmap_block_index, buffer, block_size());
  510. if (result.is_error()) {
  511. dbgln("Ext2FS: flush_writes() had error {}", result.error());
  512. }
  513. cached_bitmap->dirty = false;
  514. #ifdef EXT2_DEBUG
  515. dbgln("Flushed bitmap block {}", cached_bitmap->bitmap_block_index);
  516. #endif
  517. }
  518. }
  519. BlockBasedFS::flush_writes();
  520. // Uncache Inodes that are only kept alive by the index-to-inode lookup cache.
  521. // We don't uncache Inodes that are being watched by at least one InodeWatcher.
  522. // FIXME: It would be better to keep a capped number of Inodes around.
  523. // The problem is that they are quite heavy objects, and use a lot of heap memory
  524. // for their (child name lookup) and (block list) caches.
  525. Vector<InodeIndex> unused_inodes;
  526. for (auto& it : m_inode_cache) {
  527. if (it.value->ref_count() != 1)
  528. continue;
  529. if (it.value->has_watchers())
  530. continue;
  531. unused_inodes.append(it.key);
  532. }
  533. for (auto index : unused_inodes)
  534. uncache_inode(index);
  535. }
  536. Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index)
  537. : Inode(fs, index)
  538. {
  539. }
  540. Ext2FSInode::~Ext2FSInode()
  541. {
  542. if (m_raw_inode.i_links_count == 0)
  543. fs().free_inode(*this);
  544. }
  545. InodeMetadata Ext2FSInode::metadata() const
  546. {
  547. LOCKER(m_lock);
  548. InodeMetadata metadata;
  549. metadata.inode = identifier();
  550. metadata.size = m_raw_inode.i_size;
  551. metadata.mode = m_raw_inode.i_mode;
  552. metadata.uid = m_raw_inode.i_uid;
  553. metadata.gid = m_raw_inode.i_gid;
  554. metadata.link_count = m_raw_inode.i_links_count;
  555. metadata.atime = m_raw_inode.i_atime;
  556. metadata.ctime = m_raw_inode.i_ctime;
  557. metadata.mtime = m_raw_inode.i_mtime;
  558. metadata.dtime = m_raw_inode.i_dtime;
  559. metadata.block_size = fs().block_size();
  560. metadata.block_count = m_raw_inode.i_blocks;
  561. if (Kernel::is_character_device(m_raw_inode.i_mode) || Kernel::is_block_device(m_raw_inode.i_mode)) {
  562. unsigned dev = m_raw_inode.i_block[0];
  563. if (!dev)
  564. dev = m_raw_inode.i_block[1];
  565. metadata.major_device = (dev & 0xfff00) >> 8;
  566. metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00);
  567. }
  568. return metadata;
  569. }
  570. void Ext2FSInode::flush_metadata()
  571. {
  572. LOCKER(m_lock);
  573. #ifdef EXT2_DEBUG
  574. dbgln("Ext2FS: flush_metadata for inode {}", index());
  575. #endif
  576. fs().write_ext2_inode(index(), m_raw_inode);
  577. if (is_directory()) {
  578. // Unless we're about to go away permanently, invalidate the lookup cache.
  579. if (m_raw_inode.i_links_count != 0) {
  580. // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache.
  581. m_lookup_cache.clear();
  582. }
  583. }
  584. set_metadata_dirty(false);
  585. }
  586. RefPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const
  587. {
  588. LOCKER(m_lock);
  589. ASSERT(inode.fsid() == fsid());
  590. {
  591. auto it = m_inode_cache.find(inode.index());
  592. if (it != m_inode_cache.end())
  593. return (*it).value;
  594. }
  595. if (!get_inode_allocation_state(inode.index())) {
  596. m_inode_cache.set(inode.index(), nullptr);
  597. return nullptr;
  598. }
  599. unsigned block_index;
  600. unsigned offset;
  601. if (!find_block_containing_inode(inode.index(), block_index, offset))
  602. return {};
  603. auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index()));
  604. auto buffer = UserOrKernelBuffer::for_kernel_buffer(reinterpret_cast<u8*>(&new_inode->m_raw_inode));
  605. auto result = read_block(block_index, &buffer, sizeof(ext2_inode), offset);
  606. if (result.is_error()) {
  607. // FIXME: Propagate the actual error.
  608. return nullptr;
  609. }
  610. m_inode_cache.set(inode.index(), new_inode);
  611. return new_inode;
  612. }
  613. ssize_t Ext2FSInode::read_bytes(off_t offset, ssize_t count, UserOrKernelBuffer& buffer, FileDescription* description) const
  614. {
  615. Locker inode_locker(m_lock);
  616. ASSERT(offset >= 0);
  617. if (m_raw_inode.i_size == 0)
  618. return 0;
  619. // Symbolic links shorter than 60 characters are store inline inside the i_block array.
  620. // This avoids wasting an entire block on short links. (Most links are short.)
  621. if (is_symlink() && size() < max_inline_symlink_length) {
  622. ASSERT(offset == 0);
  623. ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count));
  624. if (!buffer.write(((const u8*)m_raw_inode.i_block) + offset, (size_t)nread))
  625. return -EFAULT;
  626. return nread;
  627. }
  628. Locker fs_locker(fs().m_lock);
  629. if (m_block_list.is_empty())
  630. m_block_list = fs().block_list_for_inode(m_raw_inode);
  631. if (m_block_list.is_empty()) {
  632. klog() << "ext2fs: read_bytes: empty block list for inode " << index();
  633. return -EIO;
  634. }
  635. bool allow_cache = !description || !description->is_direct();
  636. const int block_size = fs().block_size();
  637. size_t first_block_logical_index = offset / block_size;
  638. size_t last_block_logical_index = (offset + count) / block_size;
  639. if (last_block_logical_index >= m_block_list.size())
  640. last_block_logical_index = m_block_list.size() - 1;
  641. int offset_into_first_block = offset % block_size;
  642. ssize_t nread = 0;
  643. size_t remaining_count = min((off_t)count, (off_t)size() - offset);
  644. #ifdef EXT2_VERY_DEBUG
  645. dbgln("Ext2FS: Reading up to {} bytes, {} bytes into inode {} to {}", count, offset, index(), buffer.user_or_kernel_ptr());
  646. #endif
  647. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  648. auto block_index = m_block_list[bi];
  649. ASSERT(block_index);
  650. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  651. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  652. auto buffer_offset = buffer.offset(nread);
  653. int err = fs().read_block(block_index, &buffer_offset, num_bytes_to_copy, offset_into_block, allow_cache);
  654. if (err < 0) {
  655. klog() << "ext2fs: read_bytes: read_block(" << block_index << ") failed (lbi: " << bi << ")";
  656. return err;
  657. }
  658. remaining_count -= num_bytes_to_copy;
  659. nread += num_bytes_to_copy;
  660. }
  661. return nread;
  662. }
  663. KResult Ext2FSInode::resize(u64 new_size)
  664. {
  665. u64 old_size = size();
  666. if (old_size == new_size)
  667. return KSuccess;
  668. u64 block_size = fs().block_size();
  669. size_t blocks_needed_before = ceil_div(old_size, block_size);
  670. size_t blocks_needed_after = ceil_div(new_size, block_size);
  671. #ifdef EXT2_DEBUG
  672. dbgln("Ext2FSInode::resize(): blocks needed before (size was {}): {}", old_size, blocks_needed_before);
  673. dbgln("Ext2FSInode::resize(): blocks needed after (size is {}): {}", new_size, blocks_needed_after);
  674. #endif
  675. if (blocks_needed_after > blocks_needed_before) {
  676. u32 additional_blocks_needed = blocks_needed_after - blocks_needed_before;
  677. if (additional_blocks_needed > fs().super_block().s_free_blocks_count)
  678. return ENOSPC;
  679. }
  680. Vector<Ext2FS::BlockIndex> block_list;
  681. if (!m_block_list.is_empty())
  682. block_list = m_block_list;
  683. else
  684. block_list = fs().block_list_for_inode(m_raw_inode);
  685. if (blocks_needed_after > blocks_needed_before) {
  686. auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before);
  687. block_list.append(move(new_blocks));
  688. } else if (blocks_needed_after < blocks_needed_before) {
  689. #ifdef EXT2_DEBUG
  690. dbgln("Ext2FS: Shrinking inode {}. Old block list is {} entries:", index(), block_list.size());
  691. for (auto block_index : block_list) {
  692. dbgln(" # {}", block_index);
  693. }
  694. #endif
  695. while (block_list.size() != blocks_needed_after) {
  696. auto block_index = block_list.take_last();
  697. if (block_index)
  698. fs().set_block_allocation_state(block_index, false);
  699. }
  700. }
  701. auto result = fs().write_block_list_for_inode(index(), m_raw_inode, block_list);
  702. if (result.is_error())
  703. return result;
  704. m_raw_inode.i_size = new_size;
  705. set_metadata_dirty(true);
  706. m_block_list = move(block_list);
  707. if (new_size > old_size) {
  708. // If we're growing the inode, make sure we zero out all the new space.
  709. // FIXME: There are definitely more efficient ways to achieve this.
  710. size_t bytes_to_clear = new_size - old_size;
  711. size_t clear_from = old_size;
  712. u8 zero_buffer[PAGE_SIZE];
  713. memset(zero_buffer, 0, sizeof(zero_buffer));
  714. while (bytes_to_clear) {
  715. auto nwritten = write_bytes(clear_from, min(sizeof(zero_buffer), bytes_to_clear), UserOrKernelBuffer::for_kernel_buffer(zero_buffer), nullptr);
  716. if (nwritten < 0)
  717. return KResult((ErrnoCode)-nwritten);
  718. ASSERT(nwritten != 0);
  719. bytes_to_clear -= nwritten;
  720. clear_from += nwritten;
  721. }
  722. }
  723. return KSuccess;
  724. }
  725. ssize_t Ext2FSInode::write_bytes(off_t offset, ssize_t count, const UserOrKernelBuffer& data, FileDescription* description)
  726. {
  727. ASSERT(offset >= 0);
  728. ASSERT(count >= 0);
  729. Locker inode_locker(m_lock);
  730. Locker fs_locker(fs().m_lock);
  731. auto result = prepare_to_write_data();
  732. if (result.is_error())
  733. return result;
  734. if (is_symlink()) {
  735. ASSERT(offset == 0);
  736. if (max((size_t)(offset + count), (size_t)m_raw_inode.i_size) < max_inline_symlink_length) {
  737. #ifdef EXT2_DEBUG
  738. dbgln("Ext2FS: write_bytes poking into i_block array for inline symlink '{}' ({} bytes)", data.copy_into_string(count), count);
  739. #endif
  740. if (!data.read(((u8*)m_raw_inode.i_block) + offset, (size_t)count))
  741. return -EFAULT;
  742. if ((size_t)(offset + count) > (size_t)m_raw_inode.i_size)
  743. m_raw_inode.i_size = offset + count;
  744. set_metadata_dirty(true);
  745. return count;
  746. }
  747. }
  748. bool allow_cache = !description || !description->is_direct();
  749. const size_t block_size = fs().block_size();
  750. u64 old_size = size();
  751. u64 new_size = max(static_cast<u64>(offset) + count, (u64)size());
  752. auto resize_result = resize(new_size);
  753. if (resize_result.is_error())
  754. return resize_result;
  755. if (m_block_list.is_empty())
  756. m_block_list = fs().block_list_for_inode(m_raw_inode);
  757. if (m_block_list.is_empty()) {
  758. dbgln("Ext2FSInode::write_bytes(): empty block list for inode {}", index());
  759. return -EIO;
  760. }
  761. size_t first_block_logical_index = offset / block_size;
  762. size_t last_block_logical_index = (offset + count) / block_size;
  763. if (last_block_logical_index >= m_block_list.size())
  764. last_block_logical_index = m_block_list.size() - 1;
  765. size_t offset_into_first_block = offset % block_size;
  766. ssize_t nwritten = 0;
  767. size_t remaining_count = min((off_t)count, (off_t)new_size - offset);
  768. #ifdef EXT2_VERY_DEBUG
  769. dbgln("Ext2FS: Writing {} bytes, {} bytes into inode {} from {}", count, offset, index(), data.user_or_kernel_ptr());
  770. #endif
  771. for (size_t bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) {
  772. size_t offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0;
  773. size_t num_bytes_to_copy = min(block_size - offset_into_block, remaining_count);
  774. #ifdef EXT2_VERY_DEBUG
  775. dbgln("Ext2FS: Writing block {} (offset_into_block: {})", m_block_list[bi], offset_into_block);
  776. #endif
  777. auto result = fs().write_block(m_block_list[bi], data.offset(nwritten), num_bytes_to_copy, offset_into_block, allow_cache);
  778. if (result.is_error()) {
  779. dbgln("Ext2FS: write_block({}) failed (bi: {})", m_block_list[bi], bi);
  780. return result;
  781. }
  782. remaining_count -= num_bytes_to_copy;
  783. nwritten += num_bytes_to_copy;
  784. }
  785. #ifdef EXT2_VERY_DEBUG
  786. 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());
  787. #endif
  788. if (old_size != new_size)
  789. inode_size_changed(old_size, new_size);
  790. inode_contents_changed(offset, count, data);
  791. return nwritten;
  792. }
  793. u8 Ext2FS::internal_file_type_to_directory_entry_type(const DirectoryEntryView& entry) const
  794. {
  795. switch (entry.file_type) {
  796. case EXT2_FT_REG_FILE:
  797. return DT_REG;
  798. case EXT2_FT_DIR:
  799. return DT_DIR;
  800. case EXT2_FT_CHRDEV:
  801. return DT_CHR;
  802. case EXT2_FT_BLKDEV:
  803. return DT_BLK;
  804. case EXT2_FT_FIFO:
  805. return DT_FIFO;
  806. case EXT2_FT_SOCK:
  807. return DT_SOCK;
  808. case EXT2_FT_SYMLINK:
  809. return DT_LNK;
  810. default:
  811. return DT_UNKNOWN;
  812. }
  813. }
  814. KResult Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntryView&)> callback) const
  815. {
  816. LOCKER(m_lock);
  817. ASSERT(is_directory());
  818. #ifdef EXT2_VERY_DEBUG
  819. dbgln("Ext2FS: Traversing as directory: {}", index());
  820. #endif
  821. auto buffer_or = read_entire();
  822. if (buffer_or.is_error())
  823. return buffer_or.error();
  824. auto& buffer = *buffer_or.value();
  825. auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.data());
  826. while (entry < buffer.end_pointer()) {
  827. if (entry->inode != 0) {
  828. #ifdef EXT2_VERY_DEBUG
  829. 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));
  830. #endif
  831. if (!callback({ { entry->name, entry->name_len }, { fsid(), entry->inode }, entry->file_type }))
  832. break;
  833. }
  834. entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len);
  835. }
  836. return KSuccess;
  837. }
  838. bool Ext2FSInode::write_directory(const Vector<Ext2FSDirectoryEntry>& entries)
  839. {
  840. LOCKER(m_lock);
  841. int directory_size = 0;
  842. for (auto& entry : entries)
  843. directory_size += EXT2_DIR_REC_LEN(entry.name.length());
  844. auto block_size = fs().block_size();
  845. int blocks_needed = ceil_div(static_cast<size_t>(directory_size), block_size);
  846. int occupied_size = blocks_needed * block_size;
  847. #ifdef EXT2_DEBUG
  848. dbgln("Ext2FS: New directory inode {} contents to write (size {}, occupied {}):", index(), directory_size, occupied_size);
  849. #endif
  850. auto directory_data = ByteBuffer::create_uninitialized(occupied_size);
  851. OutputMemoryStream stream { directory_data };
  852. for (size_t i = 0; i < entries.size(); ++i) {
  853. auto& entry = entries[i];
  854. int record_length = EXT2_DIR_REC_LEN(entry.name.length());
  855. if (i == entries.size() - 1)
  856. record_length += occupied_size - directory_size;
  857. #ifdef EXT2_DEBUG
  858. 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);
  859. #endif
  860. stream << u32(entry.inode.index());
  861. stream << u16(record_length);
  862. stream << u8(entry.name.length());
  863. stream << u8(entry.file_type);
  864. stream << entry.name.bytes();
  865. int padding = record_length - entry.name.length() - 8;
  866. for (int j = 0; j < padding; ++j)
  867. stream << u8(0);
  868. }
  869. stream.fill_to_end(0);
  870. auto buffer = UserOrKernelBuffer::for_kernel_buffer(stream.data());
  871. ssize_t nwritten = write_bytes(0, stream.size(), buffer, nullptr);
  872. if (nwritten < 0)
  873. return false;
  874. set_metadata_dirty(true);
  875. return static_cast<size_t>(nwritten) == directory_data.size();
  876. }
  877. KResultOr<NonnullRefPtr<Inode>> Ext2FSInode::create_child(const String& name, mode_t mode, dev_t dev, uid_t uid, gid_t gid)
  878. {
  879. if (mode & S_IFDIR)
  880. return fs().create_directory(identifier(), name, mode, uid, gid);
  881. return fs().create_inode(identifier(), name, mode, 0, dev, uid, gid);
  882. }
  883. KResult Ext2FSInode::add_child(Inode& child, const StringView& name, mode_t mode)
  884. {
  885. LOCKER(m_lock);
  886. ASSERT(is_directory());
  887. if (name.length() > EXT2_NAME_LEN)
  888. return ENAMETOOLONG;
  889. #ifdef EXT2_DEBUG
  890. dbgln("Ext2FSInode::add_child: Adding inode {} with name '{}' and mode {:o} to directory {}", child.index(), name, mode, index());
  891. #endif
  892. Vector<Ext2FSDirectoryEntry> entries;
  893. bool name_already_exists = false;
  894. KResult result = traverse_as_directory([&](auto& entry) {
  895. if (name == entry.name) {
  896. name_already_exists = true;
  897. return false;
  898. }
  899. entries.append({ entry.name, entry.inode, entry.file_type });
  900. return true;
  901. });
  902. if (result.is_error())
  903. return result;
  904. if (name_already_exists) {
  905. dbgln("Ext2FSInode::add_child: Name '{}' already exists in inode {}", name, index());
  906. return EEXIST;
  907. }
  908. result = child.increment_link_count();
  909. if (result.is_error())
  910. return result;
  911. entries.empend(name, child.identifier(), to_ext2_file_type(mode));
  912. bool success = write_directory(entries);
  913. if (success)
  914. m_lookup_cache.set(name, child.index());
  915. did_add_child(child.identifier());
  916. return KSuccess;
  917. }
  918. KResult Ext2FSInode::remove_child(const StringView& name)
  919. {
  920. LOCKER(m_lock);
  921. #ifdef EXT2_DEBUG
  922. dbgln("Ext2FSInode::remove_child('{}') in inode {}", name, index());
  923. #endif
  924. ASSERT(is_directory());
  925. auto it = m_lookup_cache.find(name);
  926. if (it == m_lookup_cache.end())
  927. return ENOENT;
  928. auto child_inode_index = (*it).value;
  929. InodeIdentifier child_id { fsid(), child_inode_index };
  930. #ifdef EXT2_DEBUG
  931. dbgln("Ext2FSInode::remove_child(): Removing '{}' in directory {}", name, index());
  932. #endif
  933. Vector<Ext2FSDirectoryEntry> entries;
  934. KResult result = traverse_as_directory([&](auto& entry) {
  935. if (name != entry.name)
  936. entries.append({ entry.name, entry.inode, entry.file_type });
  937. return true;
  938. });
  939. if (result.is_error())
  940. return result;
  941. bool success = write_directory(entries);
  942. if (!success) {
  943. // FIXME: Plumb error from write_directory().
  944. return EIO;
  945. }
  946. m_lookup_cache.remove(name);
  947. auto child_inode = fs().get_inode(child_id);
  948. result = child_inode->decrement_link_count();
  949. if (result.is_error())
  950. return result;
  951. did_remove_child(child_id);
  952. return KSuccess;
  953. }
  954. unsigned Ext2FS::inodes_per_block() const
  955. {
  956. return EXT2_INODES_PER_BLOCK(&super_block());
  957. }
  958. unsigned Ext2FS::inodes_per_group() const
  959. {
  960. return EXT2_INODES_PER_GROUP(&super_block());
  961. }
  962. unsigned Ext2FS::inode_size() const
  963. {
  964. return EXT2_INODE_SIZE(&super_block());
  965. }
  966. unsigned Ext2FS::blocks_per_group() const
  967. {
  968. return EXT2_BLOCKS_PER_GROUP(&super_block());
  969. }
  970. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  971. {
  972. LOCKER(m_lock);
  973. unsigned block_index;
  974. unsigned offset;
  975. if (!find_block_containing_inode(inode, block_index, offset))
  976. return false;
  977. auto buffer = UserOrKernelBuffer::for_kernel_buffer(const_cast<u8*>((const u8*)&e2inode));
  978. return write_block(block_index, buffer, inode_size(), offset) >= 0;
  979. }
  980. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex preferred_group_index, size_t count)
  981. {
  982. LOCKER(m_lock);
  983. #ifdef EXT2_DEBUG
  984. dbgln("Ext2FS: allocate_blocks(preferred group: {}, count {})", preferred_group_index, count);
  985. #endif
  986. if (count == 0)
  987. return {};
  988. Vector<BlockIndex> blocks;
  989. #ifdef EXT2_DEBUG
  990. dbgln("Ext2FS: allocate_blocks:");
  991. #endif
  992. blocks.ensure_capacity(count);
  993. GroupIndex group_index = preferred_group_index;
  994. if (!group_descriptor(preferred_group_index).bg_free_blocks_count) {
  995. group_index = 1;
  996. }
  997. while (blocks.size() < count) {
  998. bool found_a_group = false;
  999. if (group_descriptor(group_index).bg_free_blocks_count) {
  1000. found_a_group = true;
  1001. } else {
  1002. if (group_index == preferred_group_index)
  1003. group_index = 1;
  1004. for (; group_index <= m_block_group_count; ++group_index) {
  1005. if (group_descriptor(group_index).bg_free_blocks_count) {
  1006. found_a_group = true;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. ASSERT(found_a_group);
  1012. auto& bgd = group_descriptor(group_index);
  1013. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  1014. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  1015. auto block_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), blocks_in_group);
  1016. BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + first_block_index();
  1017. size_t free_region_size = 0;
  1018. auto first_unset_bit_index = block_bitmap.find_longest_range_of_unset_bits(count - blocks.size(), free_region_size);
  1019. ASSERT(first_unset_bit_index.has_value());
  1020. #ifdef EXT2_DEBUG
  1021. dbgln("Ext2FS: allocating free region of size: {} [{}]", free_region_size, group_index);
  1022. #endif
  1023. for (size_t i = 0; i < free_region_size; ++i) {
  1024. BlockIndex block_index = (first_unset_bit_index.value() + i) + first_block_in_group;
  1025. set_block_allocation_state(block_index, true);
  1026. blocks.unchecked_append(block_index);
  1027. #ifdef EXT2_DEBUG
  1028. dbgln(" allocated > {}", block_index);
  1029. #endif
  1030. }
  1031. }
  1032. ASSERT(blocks.size() == count);
  1033. return blocks;
  1034. }
  1035. unsigned Ext2FS::find_a_free_inode(GroupIndex preferred_group, off_t expected_size)
  1036. {
  1037. ASSERT(expected_size >= 0);
  1038. LOCKER(m_lock);
  1039. #ifdef EXT2_DEBUG
  1040. dbgln("Ext2FS: find_a_free_inode(preferred_group: {}, expected_size: {})", preferred_group, expected_size);
  1041. #endif
  1042. unsigned needed_blocks = ceil_div(static_cast<size_t>(expected_size), block_size());
  1043. #ifdef EXT2_DEBUG
  1044. dbgln("Ext2FS: minimum needed blocks: {}", needed_blocks);
  1045. #endif
  1046. unsigned group_index = 0;
  1047. // FIXME: We shouldn't refuse to allocate an inode if there is no group that can house the whole thing.
  1048. // In those cases we should just spread it across multiple groups.
  1049. auto is_suitable_group = [this, needed_blocks](GroupIndex group_index) {
  1050. auto& bgd = group_descriptor(group_index);
  1051. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  1052. };
  1053. if (preferred_group && is_suitable_group(preferred_group)) {
  1054. group_index = preferred_group;
  1055. } else {
  1056. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  1057. if (is_suitable_group(i))
  1058. group_index = i;
  1059. }
  1060. }
  1061. if (!group_index) {
  1062. klog() << "Ext2FS: find_a_free_inode: no suitable group found for new inode with " << needed_blocks << " blocks needed :(";
  1063. return 0;
  1064. }
  1065. #ifdef EXT2_DEBUG
  1066. dbgln("Ext2FS: find_a_free_inode: found suitable group [{}] for new inode with {} blocks needed :^)", group_index, needed_blocks);
  1067. #endif
  1068. auto& bgd = group_descriptor(group_index);
  1069. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  1070. unsigned first_free_inode_in_group = 0;
  1071. unsigned first_inode_in_group = (group_index - 1) * inodes_per_group() + 1;
  1072. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  1073. auto inode_bitmap = Bitmap::wrap(cached_bitmap.buffer.data(), inodes_in_group);
  1074. for (size_t i = 0; i < inode_bitmap.size(); ++i) {
  1075. if (inode_bitmap.get(i))
  1076. continue;
  1077. first_free_inode_in_group = first_inode_in_group + i;
  1078. break;
  1079. }
  1080. if (!first_free_inode_in_group) {
  1081. klog() << "Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(";
  1082. return 0;
  1083. }
  1084. unsigned inode = first_free_inode_in_group;
  1085. #ifdef EXT2_DEBUG
  1086. dbgln("Ext2FS: found suitable inode {}", inode);
  1087. #endif
  1088. ASSERT(get_inode_allocation_state(inode) == false);
  1089. return inode;
  1090. }
  1091. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  1092. {
  1093. if (!block_index)
  1094. return 0;
  1095. return (block_index - 1) / blocks_per_group() + 1;
  1096. }
  1097. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  1098. {
  1099. if (!inode)
  1100. return 0;
  1101. return (inode - 1) / inodes_per_group() + 1;
  1102. }
  1103. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  1104. {
  1105. LOCKER(m_lock);
  1106. if (index == 0)
  1107. return true;
  1108. unsigned group_index = group_index_from_inode(index);
  1109. auto& bgd = group_descriptor(group_index);
  1110. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  1111. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1112. auto& cached_bitmap = const_cast<Ext2FS&>(*this).get_bitmap_block(bgd.bg_inode_bitmap);
  1113. return cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1114. }
  1115. bool Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state)
  1116. {
  1117. LOCKER(m_lock);
  1118. unsigned group_index = group_index_from_inode(inode_index);
  1119. auto& bgd = group_descriptor(group_index);
  1120. unsigned index_in_group = inode_index - ((group_index - 1) * inodes_per_group());
  1121. unsigned bit_index = (index_in_group - 1) % inodes_per_group();
  1122. auto& cached_bitmap = get_bitmap_block(bgd.bg_inode_bitmap);
  1123. bool current_state = cached_bitmap.bitmap(inodes_per_group()).get(bit_index);
  1124. #ifdef EXT2_DEBUG
  1125. dbgln("Ext2FS: set_inode_allocation_state({}) {} -> {}", inode_index, current_state, new_state);
  1126. #endif
  1127. if (current_state == new_state) {
  1128. ASSERT_NOT_REACHED();
  1129. return true;
  1130. }
  1131. cached_bitmap.bitmap(inodes_per_group()).set(bit_index, new_state);
  1132. cached_bitmap.dirty = true;
  1133. // Update superblock
  1134. if (new_state)
  1135. --m_super_block.s_free_inodes_count;
  1136. else
  1137. ++m_super_block.s_free_inodes_count;
  1138. m_super_block_dirty = true;
  1139. // Update BGD
  1140. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1141. if (new_state)
  1142. --mutable_bgd.bg_free_inodes_count;
  1143. else
  1144. ++mutable_bgd.bg_free_inodes_count;
  1145. m_block_group_descriptors_dirty = true;
  1146. return true;
  1147. }
  1148. Ext2FS::BlockIndex Ext2FS::first_block_index() const
  1149. {
  1150. return block_size() == 1024 ? 1 : 0;
  1151. }
  1152. Ext2FS::CachedBitmap& Ext2FS::get_bitmap_block(BlockIndex bitmap_block_index)
  1153. {
  1154. for (auto& cached_bitmap : m_cached_bitmaps) {
  1155. if (cached_bitmap->bitmap_block_index == bitmap_block_index)
  1156. return *cached_bitmap;
  1157. }
  1158. auto block = KBuffer::create_with_size(block_size(), Region::Access::Read | Region::Access::Write, "Ext2FS: Cached bitmap block");
  1159. auto buffer = UserOrKernelBuffer::for_kernel_buffer(block.data());
  1160. int err = read_block(bitmap_block_index, &buffer, block_size());
  1161. ASSERT(err >= 0);
  1162. m_cached_bitmaps.append(make<CachedBitmap>(bitmap_block_index, move(block)));
  1163. return *m_cached_bitmaps.last();
  1164. }
  1165. bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  1166. {
  1167. ASSERT(block_index != 0);
  1168. LOCKER(m_lock);
  1169. GroupIndex group_index = group_index_from_block_index(block_index);
  1170. auto& bgd = group_descriptor(group_index);
  1171. BlockIndex index_in_group = (block_index - first_block_index()) - ((group_index - 1) * blocks_per_group());
  1172. unsigned bit_index = index_in_group % blocks_per_group();
  1173. auto& cached_bitmap = get_bitmap_block(bgd.bg_block_bitmap);
  1174. bool current_state = cached_bitmap.bitmap(blocks_per_group()).get(bit_index);
  1175. #ifdef EXT2_DEBUG
  1176. dbgln("Ext2FS: block {} state: {} -> {} (in bitmap block {})", block_index, current_state, new_state, bgd.bg_block_bitmap);
  1177. #endif
  1178. if (current_state == new_state) {
  1179. ASSERT_NOT_REACHED();
  1180. return true;
  1181. }
  1182. cached_bitmap.bitmap(blocks_per_group()).set(bit_index, new_state);
  1183. cached_bitmap.dirty = true;
  1184. // Update superblock
  1185. if (new_state)
  1186. --m_super_block.s_free_blocks_count;
  1187. else
  1188. ++m_super_block.s_free_blocks_count;
  1189. m_super_block_dirty = true;
  1190. // Update BGD
  1191. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  1192. if (new_state)
  1193. --mutable_bgd.bg_free_blocks_count;
  1194. else
  1195. ++mutable_bgd.bg_free_blocks_count;
  1196. m_block_group_descriptors_dirty = true;
  1197. return true;
  1198. }
  1199. KResult Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, uid_t uid, gid_t gid)
  1200. {
  1201. LOCKER(m_lock);
  1202. ASSERT(parent_id.fsid() == fsid());
  1203. // Fix up the mode to definitely be a directory.
  1204. // FIXME: This is a bit on the hackish side.
  1205. mode &= ~0170000;
  1206. mode |= 0040000;
  1207. // NOTE: When creating a new directory, make the size 1 block.
  1208. // There's probably a better strategy here, but this works for now.
  1209. auto inode_or_error = create_inode(parent_id, name, mode, block_size(), 0, uid, gid);
  1210. if (inode_or_error.is_error())
  1211. return inode_or_error.error();
  1212. auto& inode = inode_or_error.value();
  1213. #ifdef EXT2_DEBUG
  1214. dbgln("Ext2FS: create_directory: created new directory named '{} with inode {}", name, inode->index());
  1215. #endif
  1216. Vector<Ext2FSDirectoryEntry> entries;
  1217. entries.empend(".", inode->identifier(), static_cast<u8>(EXT2_FT_DIR));
  1218. entries.empend("..", parent_id, static_cast<u8>(EXT2_FT_DIR));
  1219. bool success = static_cast<Ext2FSInode&>(*inode).write_directory(entries);
  1220. ASSERT(success);
  1221. auto parent_inode = get_inode(parent_id);
  1222. auto result = parent_inode->increment_link_count();
  1223. if (result.is_error())
  1224. return result;
  1225. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  1226. ++bgd.bg_used_dirs_count;
  1227. m_block_group_descriptors_dirty = true;
  1228. return KSuccess;
  1229. }
  1230. 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)
  1231. {
  1232. LOCKER(m_lock);
  1233. ASSERT(size >= 0);
  1234. ASSERT(parent_id.fsid() == fsid());
  1235. auto parent_inode = get_inode(parent_id);
  1236. ASSERT(parent_inode);
  1237. if (static_cast<const Ext2FSInode&>(*parent_inode).m_raw_inode.i_links_count == 0)
  1238. return ENOENT;
  1239. if (name.length() > EXT2_NAME_LEN)
  1240. return ENAMETOOLONG;
  1241. #ifdef EXT2_DEBUG
  1242. dbgln("Ext2FS: Adding inode '{}' (mode {:o}) to parent directory {}", name, mode, parent_inode->index());
  1243. #endif
  1244. size_t needed_blocks = ceil_div(static_cast<size_t>(size), block_size());
  1245. if ((size_t)needed_blocks > super_block().s_free_blocks_count) {
  1246. dbgln("Ext2FS: create_inode: not enough free blocks");
  1247. return ENOSPC;
  1248. }
  1249. // NOTE: This doesn't commit the inode allocation just yet!
  1250. auto inode_id = find_a_free_inode(0, size);
  1251. if (!inode_id) {
  1252. klog() << "Ext2FS: create_inode: allocate_inode failed";
  1253. return ENOSPC;
  1254. }
  1255. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  1256. ASSERT(blocks.size() == needed_blocks);
  1257. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  1258. bool success = set_inode_allocation_state(inode_id, true);
  1259. ASSERT(success);
  1260. struct timeval now;
  1261. kgettimeofday(now);
  1262. ext2_inode e2inode;
  1263. memset(&e2inode, 0, sizeof(ext2_inode));
  1264. e2inode.i_mode = mode;
  1265. e2inode.i_uid = uid;
  1266. e2inode.i_gid = gid;
  1267. e2inode.i_size = size;
  1268. e2inode.i_atime = now.tv_sec;
  1269. e2inode.i_ctime = now.tv_sec;
  1270. e2inode.i_mtime = now.tv_sec;
  1271. e2inode.i_dtime = 0;
  1272. // For directories, add +1 link count for the "." entry in self.
  1273. e2inode.i_links_count = is_directory(mode);
  1274. if (is_character_device(mode))
  1275. e2inode.i_block[0] = dev;
  1276. else if (is_block_device(mode))
  1277. e2inode.i_block[1] = dev;
  1278. auto result = write_block_list_for_inode(inode_id, e2inode, blocks);
  1279. if (result.is_error())
  1280. return result;
  1281. #ifdef EXT2_DEBUG
  1282. dbgln("Ext2FS: writing initial metadata for inode {}", inode_id);
  1283. #endif
  1284. e2inode.i_flags = 0;
  1285. success = write_ext2_inode(inode_id, e2inode);
  1286. ASSERT(success);
  1287. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  1288. m_inode_cache.remove(inode_id);
  1289. auto inode = get_inode({ fsid(), inode_id });
  1290. // If we've already computed a block list, no sense in throwing it away.
  1291. static_cast<Ext2FSInode&>(*inode).m_block_list = move(blocks);
  1292. result = parent_inode->add_child(*inode, name, mode);
  1293. if (result.is_error())
  1294. return result;
  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 EROFS;
  1361. if (m_raw_inode.i_links_count == max_link_count)
  1362. return 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 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 EBUSY;
  1447. }
  1448. m_inode_cache.clear();
  1449. return KSuccess;
  1450. }
  1451. }