Ext2FileSystem.cpp 55 KB

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