Ext2FileSystem.cpp 50 KB

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