Ext2FileSystem.cpp 45 KB

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