Ext2FileSystem.cpp 51 KB

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