Ext2FileSystem.cpp 55 KB

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