Ext2FileSystem.cpp 47 KB

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