Ext2FileSystem.cpp 45 KB

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