Ext2FileSystem.cpp 45 KB

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