Ext2FileSystem.cpp 55 KB

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