Ext2FileSystem.cpp 55 KB

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