Ext2FileSystem.cpp 50 KB

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