Ext2FileSystem.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402
  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 = 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. void Ext2FS::dump_block_bitmap(unsigned groupIndex) const
  666. {
  667. LOCKER(m_lock);
  668. ASSERT(groupIndex <= m_block_group_count);
  669. auto& bgd = group_descriptor(groupIndex);
  670. unsigned blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  671. unsigned block_count = ceil_div(blocks_in_group, 8u);
  672. auto bitmap_blocks = read_blocks(bgd.bg_block_bitmap, block_count);
  673. ASSERT(bitmap_blocks);
  674. kprintf("ext2fs: group[%u] block bitmap (bitmap occupies %u blocks):\n", groupIndex, block_count);
  675. auto bitmap = Bitmap::wrap(bitmap_blocks.pointer(), blocks_in_group);
  676. for (unsigned i = 0; i < blocks_in_group; ++i) {
  677. kprintf("%c", bitmap.get(i) ? '1' : '0');
  678. }
  679. kprintf("\n");
  680. }
  681. void Ext2FS::dump_inode_bitmap(unsigned groupIndex) const
  682. {
  683. LOCKER(m_lock);
  684. traverse_inode_bitmap(groupIndex, [] (unsigned, const Bitmap& bitmap) {
  685. for (int i = 0; i < bitmap.size(); ++i)
  686. kprintf("%c", bitmap.get(i) ? '1' : '0');
  687. return true;
  688. });
  689. }
  690. template<typename F>
  691. void Ext2FS::traverse_inode_bitmap(unsigned group_index, F callback) const
  692. {
  693. ASSERT(group_index <= m_block_group_count);
  694. auto& bgd = group_descriptor(group_index);
  695. unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count);
  696. unsigned block_count = ceil_div(inodes_in_group, 8u);
  697. unsigned first_inode_in_group = (group_index - 1) * inodes_per_group();
  698. unsigned bits_per_block = block_size() * 8;
  699. for (unsigned i = 0; i < block_count; ++i) {
  700. auto block = read_block(bgd.bg_inode_bitmap + i);
  701. ASSERT(block);
  702. bool should_continue = callback(first_inode_in_group + i * (i * bits_per_block) + 1, Bitmap::wrap(block.pointer(), inodes_in_group));
  703. if (!should_continue)
  704. break;
  705. }
  706. }
  707. bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode)
  708. {
  709. LOCKER(m_lock);
  710. unsigned block_index;
  711. unsigned offset;
  712. auto block = read_block_containing_inode(inode, block_index, offset);
  713. if (!block)
  714. return false;
  715. memcpy(reinterpret_cast<ext2_inode*>(block.offset_pointer(offset)), &e2inode, inode_size());
  716. bool success = write_block(block_index, block);
  717. ASSERT(success);
  718. return success;
  719. }
  720. Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex group_index, int count)
  721. {
  722. LOCKER(m_lock);
  723. dbgprintf("Ext2FS: allocate_blocks(group: %u, count: %u)\n", group_index, count);
  724. if (count == 0)
  725. return { };
  726. auto& bgd = group_descriptor(group_index);
  727. if (bgd.bg_free_blocks_count < count) {
  728. 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);
  729. return { };
  730. }
  731. // FIXME: Implement a scan that finds consecutive blocks if possible.
  732. Vector<BlockIndex> blocks;
  733. auto bitmap_block = read_block(bgd.bg_block_bitmap);
  734. int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count);
  735. auto block_bitmap = Bitmap::wrap(bitmap_block.pointer(), blocks_in_group);
  736. BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + 1;
  737. for (int i = 0; i < block_bitmap.size(); ++i) {
  738. if (!block_bitmap.get(i)) {
  739. blocks.append(first_block_in_group + i);
  740. if (blocks.size() == count)
  741. break;
  742. }
  743. }
  744. ASSERT(blocks.size() == count);
  745. dbgprintf("Ext2FS: allocate_block found these blocks:\n");
  746. for (auto& bi : blocks) {
  747. dbgprintf(" > %u\n", bi);
  748. }
  749. return blocks;
  750. }
  751. unsigned Ext2FS::allocate_inode(GroupIndex preferred_group, off_t expected_size)
  752. {
  753. LOCKER(m_lock);
  754. dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expectedSize: %u)\n", preferred_group, expected_size);
  755. unsigned needed_blocks = ceil_div(expected_size, block_size());
  756. dbgprintf("Ext2FS: minimum needed blocks: %u\n", needed_blocks);
  757. unsigned groupIndex = 0;
  758. auto is_suitable_group = [this, needed_blocks] (unsigned groupIndex) {
  759. auto& bgd = group_descriptor(groupIndex);
  760. return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks;
  761. };
  762. if (preferred_group && is_suitable_group(preferred_group)) {
  763. groupIndex = preferred_group;
  764. } else {
  765. for (unsigned i = 1; i <= m_block_group_count; ++i) {
  766. if (is_suitable_group(i))
  767. groupIndex = i;
  768. }
  769. }
  770. if (!groupIndex) {
  771. kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", needed_blocks);
  772. return 0;
  773. }
  774. dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", groupIndex, needed_blocks);
  775. unsigned first_free_inode_in_group = 0;
  776. traverse_inode_bitmap(groupIndex, [&first_free_inode_in_group] (unsigned firstInodeInBitmap, const Bitmap& bitmap) {
  777. for (int i = 0; i < bitmap.size(); ++i) {
  778. if (!bitmap.get(i)) {
  779. first_free_inode_in_group = firstInodeInBitmap + i;
  780. return false;
  781. }
  782. }
  783. return true;
  784. });
  785. if (!first_free_inode_in_group) {
  786. kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n");
  787. return 0;
  788. }
  789. unsigned inode = first_free_inode_in_group;
  790. dbgprintf("Ext2FS: found suitable inode %u\n", inode);
  791. ASSERT(get_inode_allocation_state(inode) == false);
  792. // FIXME: allocate blocks if needed!
  793. return inode;
  794. }
  795. Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const
  796. {
  797. if (!block_index)
  798. return 0;
  799. return (block_index - 1) / blocks_per_group() + 1;
  800. }
  801. unsigned Ext2FS::group_index_from_inode(unsigned inode) const
  802. {
  803. if (!inode)
  804. return 0;
  805. return (inode - 1) / inodes_per_group() + 1;
  806. }
  807. bool Ext2FS::get_inode_allocation_state(InodeIndex index) const
  808. {
  809. LOCKER(m_lock);
  810. if (index == 0)
  811. return true;
  812. unsigned group_index = group_index_from_inode(index);
  813. auto& bgd = group_descriptor(group_index);
  814. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  815. unsigned inodes_per_bitmap_block = block_size() * 8;
  816. unsigned bit_index = (index_in_group - 1) % inodes_per_bitmap_block;
  817. auto block = read_block(bgd.bg_inode_bitmap);
  818. ASSERT(block);
  819. auto bitmap = Bitmap::wrap(block.pointer(), inodes_per_bitmap_block);
  820. return bitmap.get(bit_index);
  821. }
  822. bool Ext2FS::set_inode_allocation_state(unsigned index, bool newState)
  823. {
  824. LOCKER(m_lock);
  825. unsigned group_index = group_index_from_inode(index);
  826. auto& bgd = group_descriptor(group_index);
  827. unsigned index_in_group = index - ((group_index - 1) * inodes_per_group());
  828. unsigned inodes_per_bitmap_block = block_size() * 8;
  829. unsigned bit_index = (index_in_group - 1) % inodes_per_bitmap_block;
  830. auto block = read_block(bgd.bg_inode_bitmap);
  831. ASSERT(block);
  832. auto bitmap = Bitmap::wrap(block.pointer(), inodes_per_bitmap_block);
  833. bool current_state = bitmap.get(bit_index);
  834. dbgprintf("Ext2FS: set_inode_allocation_state(%u) %u -> %u\n", index, current_state, newState);
  835. if (current_state == newState)
  836. return true;
  837. bitmap.set(bit_index, newState);
  838. bool success = write_block(bgd.bg_inode_bitmap, block);
  839. ASSERT(success);
  840. // Update superblock
  841. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  842. dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1);
  843. if (newState)
  844. --sb.s_free_inodes_count;
  845. else
  846. ++sb.s_free_inodes_count;
  847. write_super_block(sb);
  848. // Update BGD
  849. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  850. if (newState)
  851. --mutable_bgd.bg_free_inodes_count;
  852. else
  853. ++mutable_bgd.bg_free_inodes_count;
  854. dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1);
  855. flush_block_group_descriptor_table();
  856. return true;
  857. }
  858. bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state)
  859. {
  860. LOCKER(m_lock);
  861. dbgprintf("Ext2FS: set_block_allocation_state(block=%u, state=%u)\n", block_index, new_state);
  862. unsigned group_index = group_index_from_block_index(block_index);
  863. auto& bgd = group_descriptor(group_index);
  864. BlockIndex index_in_group = block_index - ((group_index - 1) * blocks_per_group());
  865. unsigned blocks_per_bitmap_block = block_size() * 8;
  866. unsigned bit_index = (index_in_group - 1) % blocks_per_bitmap_block;
  867. dbgprintf(" index_in_group: %u\n", index_in_group);
  868. dbgprintf(" blocks_per_bitmap_block: %u\n", blocks_per_bitmap_block);
  869. dbgprintf(" bit_index: %u\n", bit_index);
  870. dbgprintf(" read_block(%u)\n", bgd.bg_block_bitmap);
  871. auto block = read_block(bgd.bg_block_bitmap);
  872. ASSERT(block);
  873. auto bitmap = Bitmap::wrap(block.pointer(), blocks_per_bitmap_block);
  874. bool current_state = bitmap.get(bit_index);
  875. dbgprintf("Ext2FS: block %u state: %u -> %u\n", block_index, current_state, new_state);
  876. if (current_state == new_state)
  877. return true;
  878. bitmap.set(bit_index, new_state);
  879. bool success = write_block(bgd.bg_block_bitmap, block);
  880. ASSERT(success);
  881. // Update superblock
  882. auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.pointer());
  883. dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1);
  884. if (new_state)
  885. --sb.s_free_blocks_count;
  886. else
  887. ++sb.s_free_blocks_count;
  888. write_super_block(sb);
  889. // Update BGD
  890. auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd);
  891. if (new_state)
  892. --mutable_bgd.bg_free_blocks_count;
  893. else
  894. ++mutable_bgd.bg_free_blocks_count;
  895. dbgprintf("Ext2FS: group free block count %u -> %u\n", bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1);
  896. flush_block_group_descriptor_table();
  897. return true;
  898. }
  899. RetainPtr<Inode> Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, int& error)
  900. {
  901. LOCKER(m_lock);
  902. ASSERT(parent_id.fsid() == fsid());
  903. // Fix up the mode to definitely be a directory.
  904. // FIXME: This is a bit on the hackish side.
  905. mode &= ~0170000;
  906. mode |= 0040000;
  907. // NOTE: When creating a new directory, make the size 1 block.
  908. // There's probably a better strategy here, but this works for now.
  909. auto inode = create_inode(parent_id, name, mode, block_size(), error);
  910. if (!inode)
  911. return nullptr;
  912. dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode->identifier().index());
  913. Vector<DirectoryEntry> entries;
  914. entries.append({ ".", inode->identifier(), EXT2_FT_DIR });
  915. entries.append({ "..", parent_id, EXT2_FT_DIR });
  916. bool success = write_directory_inode(inode->identifier().index(), move(entries));
  917. ASSERT(success);
  918. auto parent_inode = get_inode(parent_id);
  919. error = parent_inode->increment_link_count();
  920. if (error < 0)
  921. return nullptr;
  922. auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index())));
  923. ++bgd.bg_used_dirs_count;
  924. dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count);
  925. flush_block_group_descriptor_table();
  926. error = 0;
  927. return inode;
  928. }
  929. RetainPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, off_t size, int& error)
  930. {
  931. LOCKER(m_lock);
  932. ASSERT(parent_id.fsid() == fsid());
  933. auto parent_inode = get_inode(parent_id);
  934. dbgprintf("Ext2FS: Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parent_inode->identifier().index());
  935. // NOTE: This doesn't commit the inode allocation just yet!
  936. auto inode_id = allocate_inode(0, size);
  937. if (!inode_id) {
  938. kprintf("Ext2FS: create_inode: allocate_inode failed\n");
  939. error = -ENOSPC;
  940. return { };
  941. }
  942. auto needed_blocks = ceil_div(size, block_size());
  943. auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks);
  944. if (blocks.size() != needed_blocks) {
  945. kprintf("Ext2FS: create_inode: allocate_blocks failed\n");
  946. error = -ENOSPC;
  947. return { };
  948. }
  949. byte file_type = 0;
  950. if (is_regular_file(mode))
  951. file_type = EXT2_FT_REG_FILE;
  952. else if (is_directory(mode))
  953. file_type = EXT2_FT_DIR;
  954. else if (is_character_device(mode))
  955. file_type = EXT2_FT_CHRDEV;
  956. else if (is_block_device(mode))
  957. file_type = EXT2_FT_BLKDEV;
  958. else if (is_fifo(mode))
  959. file_type = EXT2_FT_FIFO;
  960. else if (is_socket(mode))
  961. file_type = EXT2_FT_SOCK;
  962. else if (is_symlink(mode))
  963. file_type = EXT2_FT_SYMLINK;
  964. // Try adding it to the directory first, in case the name is already in use.
  965. auto result = parent_inode->add_child({ fsid(), inode_id }, name, file_type);
  966. if (result.is_error()) {
  967. error = result;
  968. return { };
  969. }
  970. // Looks like we're good, time to update the inode bitmap and group+global inode counters.
  971. bool success = set_inode_allocation_state(inode_id, true);
  972. ASSERT(success);
  973. for (auto block_index : blocks) {
  974. success = set_block_allocation_state(block_index, true);
  975. ASSERT(success);
  976. }
  977. unsigned initial_links_count;
  978. if (is_directory(mode))
  979. initial_links_count = 2; // (parent directory + "." entry in self)
  980. else
  981. initial_links_count = 1;
  982. struct timeval now;
  983. kgettimeofday(now);
  984. ext2_inode e2inode;
  985. memset(&e2inode, 0, sizeof(ext2_inode));
  986. e2inode.i_mode = mode;
  987. e2inode.i_uid = current->process().euid();
  988. e2inode.i_gid = current->process().egid();
  989. e2inode.i_size = size;
  990. e2inode.i_atime = now.tv_sec;
  991. e2inode.i_ctime = now.tv_sec;
  992. e2inode.i_mtime = now.tv_sec;
  993. e2inode.i_dtime = 0;
  994. e2inode.i_links_count = initial_links_count;
  995. success = write_block_list_for_inode(inode_id, e2inode, blocks);
  996. ASSERT(success);
  997. dbgprintf("Ext2FS: writing initial metadata for inode %u\n", inode_id);
  998. e2inode.i_flags = 0;
  999. success = write_ext2_inode(inode_id, e2inode);
  1000. ASSERT(success);
  1001. // We might have cached the fact that this inode didn't exist. Wipe the slate.
  1002. m_inode_cache.remove(inode_id);
  1003. return get_inode({ fsid(), inode_id });
  1004. }
  1005. RetainPtr<Inode> Ext2FSInode::parent() const
  1006. {
  1007. LOCKER(m_lock);
  1008. if (m_parent_id.is_valid())
  1009. return fs().get_inode(m_parent_id);
  1010. unsigned group_index = fs().group_index_from_inode(index());
  1011. unsigned first_inode_in_group = fs().inodes_per_group() * (group_index - 1);
  1012. Vector<Retained<Ext2FSInode>> directories_in_group;
  1013. for (unsigned i = 0; i < fs().inodes_per_group(); ++i) {
  1014. auto group_member = fs().get_inode({ fsid(), first_inode_in_group + i });
  1015. if (!group_member)
  1016. continue;
  1017. if (group_member->is_directory())
  1018. directories_in_group.append(*group_member);
  1019. }
  1020. for (auto& directory : directories_in_group) {
  1021. if (!directory->reverse_lookup(identifier()).is_null()) {
  1022. m_parent_id = directory->identifier();
  1023. break;
  1024. }
  1025. }
  1026. ASSERT(m_parent_id.is_valid());
  1027. return fs().get_inode(m_parent_id);
  1028. }
  1029. void Ext2FSInode::populate_lookup_cache() const
  1030. {
  1031. LOCKER(m_lock);
  1032. if (!m_lookup_cache.is_empty())
  1033. return;
  1034. HashMap<String, unsigned> children;
  1035. traverse_as_directory([&children] (auto& entry) {
  1036. children.set(String(entry.name, entry.name_length), entry.inode.index());
  1037. return true;
  1038. });
  1039. if (!m_lookup_cache.is_empty())
  1040. return;
  1041. m_lookup_cache = move(children);
  1042. }
  1043. InodeIdentifier Ext2FSInode::lookup(const String& name)
  1044. {
  1045. ASSERT(is_directory());
  1046. populate_lookup_cache();
  1047. LOCKER(m_lock);
  1048. auto it = m_lookup_cache.find(name);
  1049. if (it != m_lookup_cache.end())
  1050. return { fsid(), (*it).value };
  1051. return { };
  1052. }
  1053. String Ext2FSInode::reverse_lookup(InodeIdentifier child_id)
  1054. {
  1055. ASSERT(is_directory());
  1056. ASSERT(child_id.fsid() == fsid());
  1057. populate_lookup_cache();
  1058. LOCKER(m_lock);
  1059. for (auto it : m_lookup_cache) {
  1060. if (it.value == child_id.index())
  1061. return it.key;
  1062. }
  1063. return { };
  1064. }
  1065. void Ext2FSInode::one_retain_left()
  1066. {
  1067. // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now.
  1068. }
  1069. int Ext2FSInode::set_atime(time_t t)
  1070. {
  1071. LOCKER(m_lock);
  1072. if (fs().is_readonly())
  1073. return -EROFS;
  1074. m_raw_inode.i_atime = t;
  1075. set_metadata_dirty(true);
  1076. return 0;
  1077. }
  1078. int Ext2FSInode::set_ctime(time_t t)
  1079. {
  1080. LOCKER(m_lock);
  1081. if (fs().is_readonly())
  1082. return -EROFS;
  1083. m_raw_inode.i_ctime = t;
  1084. set_metadata_dirty(true);
  1085. return 0;
  1086. }
  1087. int Ext2FSInode::set_mtime(time_t t)
  1088. {
  1089. LOCKER(m_lock);
  1090. if (fs().is_readonly())
  1091. return -EROFS;
  1092. m_raw_inode.i_mtime = t;
  1093. set_metadata_dirty(true);
  1094. return 0;
  1095. }
  1096. int Ext2FSInode::increment_link_count()
  1097. {
  1098. LOCKER(m_lock);
  1099. if (fs().is_readonly())
  1100. return -EROFS;
  1101. ++m_raw_inode.i_links_count;
  1102. set_metadata_dirty(true);
  1103. return 0;
  1104. }
  1105. int Ext2FSInode::decrement_link_count()
  1106. {
  1107. LOCKER(m_lock);
  1108. if (fs().is_readonly())
  1109. return -EROFS;
  1110. ASSERT(m_raw_inode.i_links_count);
  1111. --m_raw_inode.i_links_count;
  1112. if (m_raw_inode.i_links_count == 0)
  1113. fs().uncache_inode(index());
  1114. set_metadata_dirty(true);
  1115. return 0;
  1116. }
  1117. void Ext2FS::uncache_inode(InodeIndex index)
  1118. {
  1119. LOCKER(m_lock);
  1120. m_inode_cache.remove(index);
  1121. }
  1122. size_t Ext2FSInode::directory_entry_count() const
  1123. {
  1124. ASSERT(is_directory());
  1125. LOCKER(m_lock);
  1126. populate_lookup_cache();
  1127. return m_lookup_cache.size();
  1128. }
  1129. KResult Ext2FSInode::chmod(mode_t mode)
  1130. {
  1131. LOCKER(m_lock);
  1132. if (m_raw_inode.i_mode == mode)
  1133. return KSuccess;
  1134. m_raw_inode.i_mode = mode;
  1135. set_metadata_dirty(true);
  1136. return KSuccess;
  1137. }
  1138. KResult Ext2FSInode::chown(uid_t uid, gid_t gid)
  1139. {
  1140. LOCKER(m_lock);
  1141. if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid)
  1142. return KSuccess;
  1143. m_raw_inode.i_uid = uid;
  1144. m_raw_inode.i_gid = gid;
  1145. set_metadata_dirty(true);
  1146. return KSuccess;
  1147. }
  1148. KResult Ext2FSInode::truncate(off_t size)
  1149. {
  1150. LOCKER(m_lock);
  1151. if ((off_t)m_raw_inode.i_size == size)
  1152. return KSuccess;
  1153. m_raw_inode.i_size = size;
  1154. set_metadata_dirty(true);
  1155. return KSuccess;
  1156. }
  1157. unsigned Ext2FS::total_block_count() const
  1158. {
  1159. LOCKER(m_lock);
  1160. return super_block().s_blocks_count;
  1161. }
  1162. unsigned Ext2FS::free_block_count() const
  1163. {
  1164. LOCKER(m_lock);
  1165. return super_block().s_free_blocks_count;
  1166. }
  1167. unsigned Ext2FS::total_inode_count() const
  1168. {
  1169. LOCKER(m_lock);
  1170. return super_block().s_inodes_count;
  1171. }
  1172. unsigned Ext2FS::free_inode_count() const
  1173. {
  1174. LOCKER(m_lock);
  1175. return super_block().s_free_inodes_count;
  1176. }