Ext2FileSystem.cpp 51 KB

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