Ext2FileSystem.cpp 54 KB

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