Ext2FileSystem.cpp 47 KB

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