Ext2FileSystem.cpp 52 KB

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