Ext2FileSystem.cpp 54 KB

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