Ext2FileSystem.cpp 43 KB

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