Ext2FileSystem.cpp 44 KB

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