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