Ext2FileSystem.cpp 46 KB

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